Cache for the synchronous loading.
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / texture-manager-impl.cpp
1 /*
2  * Copyright (c) 2021 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 <dali-toolkit/internal/visuals/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/devel-api/common/hash.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/math/vector4.h>
28 #include <dali/public-api/rendering/geometry.h>
29 #include <cstdlib>
30 #include <string>
31
32 // INTERNAL HEADERS
33 #include <dali-toolkit/internal/image-loader/async-image-loader-impl.h>
34 #include <dali-toolkit/internal/image-loader/image-atlas-impl.h>
35 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
36 #include <dali-toolkit/internal/visuals/rendering-addon.h>
37 #include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
38
39 namespace
40 {
41 constexpr auto INITIAL_CACHE_NUMBER                    = size_t{0u};
42 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS  = size_t{4u};
43 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
44
45 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV  = "DALI_TEXTURE_LOCAL_THREADS";
46 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
47
48 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
49 {
50   using Dali::EnvironmentVariable::GetEnvironmentVariable;
51   auto           numberString          = GetEnvironmentVariable(environmentVariable);
52   auto           numberOfThreads       = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
53   constexpr auto MAX_NUMBER_OF_THREADS = 100u;
54   DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS);
55   return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
56 }
57
58 size_t GetNumberOfLocalLoaderThreads()
59 {
60   return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
61 }
62
63 size_t GetNumberOfRemoteLoaderThreads()
64 {
65   return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
66 }
67
68 } // namespace
69
70 namespace Dali
71 {
72 namespace Toolkit
73 {
74 namespace Internal
75 {
76 namespace
77 {
78 #ifdef DEBUG_ENABLED
79 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXTURE_MANAGER");
80
81 #define GET_LOAD_STATE_STRING(loadState)                                                                                                              \
82   loadState == TextureManager::LoadState::NOT_STARTED ? "NOT_STARTED" : loadState == TextureManager::LoadState::LOADING          ? "LOADING"          \
83                                                                       : loadState == TextureManager::LoadState::LOAD_FINISHED    ? "LOAD_FINISHED"    \
84                                                                       : loadState == TextureManager::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" \
85                                                                       : loadState == TextureManager::LoadState::MASK_APPLYING    ? "MASK_APPLYING"    \
86                                                                       : loadState == TextureManager::LoadState::MASK_APPLIED     ? "MASK_APPLIED"     \
87                                                                       : loadState == TextureManager::LoadState::UPLOADED         ? "UPLOADED"         \
88                                                                       : loadState == TextureManager::LoadState::CANCELLED        ? "CANCELLED"        \
89                                                                       : loadState == TextureManager::LoadState::LOAD_FAILED      ? "LOAD_FAILED"      \
90                                                                                                                                  : "Unknown"
91
92 #endif
93
94 const uint32_t DEFAULT_ATLAS_SIZE(1024u);               ///< This size can fit 8 by 8 images of average size 128 * 128
95 const Vector4  FULL_ATLAS_RECT(0.0f, 0.0f, 1.0f, 1.0f); ///< UV Rectangle that covers the full Texture
96 const int      INVALID_INDEX(-1);                       ///< Invalid index used to represent a non-existant TextureInfo struct
97 const int      INVALID_CACHE_INDEX(-1);                 ///< Invalid Cache index
98
99 void PreMultiply(Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
100 {
101   if(Pixel::HasAlpha(pixelBuffer.GetPixelFormat()))
102   {
103     if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
104     {
105       pixelBuffer.MultiplyColorByAlpha();
106     }
107   }
108   else
109   {
110     preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
111   }
112 }
113
114 } // Anonymous namespace
115
116 TextureManager::MaskingData::MaskingData()
117 : mAlphaMaskUrl(),
118   mAlphaMaskId(INVALID_TEXTURE_ID),
119   mContentScaleFactor(1.0f),
120   mCropToMask(true)
121 {
122 }
123
124 TextureManager::TextureManager()
125 : mAsyncLocalLoaders(GetNumberOfLocalLoaderThreads(), [&]()
126                      { return AsyncLoadingHelper(*this); }),
127   mAsyncRemoteLoaders(GetNumberOfRemoteLoaderThreads(), [&]()
128                       { return AsyncLoadingHelper(*this); }),
129   mExternalTextures(),
130   mLifecycleObservers(),
131   mLoadQueue(),
132   mCurrentTextureId(0),
133   mQueueLoadFlag(false)
134 {
135   // Initialize the AddOn
136   RenderingAddOn::Get();
137 }
138
139 TextureManager::~TextureManager()
140 {
141   for(auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
142   {
143     (*iter)->TextureManagerDestroyed();
144   }
145 }
146
147 TextureSet TextureManager::LoadAnimatedImageTexture(
148   Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureManager::TextureId& textureId, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver)
149 {
150   TextureSet textureSet;
151
152   if(synchronousLoading)
153   {
154     Devel::PixelBuffer pixelBuffer;
155     if(animatedImageLoading)
156     {
157       pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
158     }
159     if(!pixelBuffer)
160     {
161       DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
162     }
163     else
164     {
165       PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
166       if(!textureSet)
167       {
168         Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
169         texture.Upload(pixelData);
170         textureSet = TextureSet::New();
171         textureSet.SetTexture(0u, texture);
172       }
173     }
174   }
175   else
176   {
177     auto preMultiply                    = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
178     textureId                           = RequestLoadInternal(animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, TextureManager::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex, false);
179     TextureManager::LoadState loadState = GetTextureStateInternal(textureId);
180     if(loadState == TextureManager::LoadState::UPLOADED)
181     {
182       // UploadComplete has already been called - keep the same texture set
183       textureSet = GetTextureSet(textureId);
184     }
185   }
186
187   if(textureSet)
188   {
189     Sampler sampler = Sampler::New();
190     sampler.SetWrapMode(wrapModeU, wrapModeV);
191     textureSet.SetSampler(0u, sampler);
192   }
193
194   return textureSet;
195 }
196
197 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
198   const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureUploadObserver* textureObserver, bool orientationCorrection, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
199 {
200   Devel::PixelBuffer pixelBuffer;
201   if(synchronousLoading)
202   {
203     if(url.IsValid())
204     {
205       if(url.IsBufferResource())
206       {
207         const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(url.GetUrl());
208         if(encodedImageBuffer)
209         {
210           pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
211         }
212       }
213       else
214       {
215         pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
216       }
217       if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
218       {
219         PreMultiply(pixelBuffer, preMultiplyOnLoad);
220       }
221     }
222   }
223   else
224   {
225     RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, false);
226   }
227
228   return pixelBuffer;
229 }
230
231 TextureSet TextureManager::LoadTexture(
232   const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo, bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect, Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver, AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection, TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
233 {
234   TextureSet textureSet;
235
236   loadingStatus = false;
237   textureRect   = FULL_ATLAS_RECT;
238
239   if(VisualUrl::TEXTURE == url.GetProtocolType())
240   {
241     std::string location = url.GetLocation();
242     if(location.size() > 0u)
243     {
244       TextureId id = std::stoi(location);
245       for(auto&& elem : mExternalTextures)
246       {
247         if(elem.textureId == id)
248         {
249           preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
250           textureId         = elem.textureId;
251           return elem.textureSet;
252         }
253       }
254     }
255   }
256   else
257   {
258     // For Atlas
259     if(synchronousLoading && atlasingStatus && imageAtlasManager->CheckAtlasAvailable(url, desiredSize))
260     {
261       Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
262
263       if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
264       {
265         Devel::PixelBuffer maskPixelBuffer = LoadImageSynchronously(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
266         if(maskPixelBuffer)
267         {
268           pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
269         }
270       }
271
272       PixelData data;
273       if(pixelBuffer)
274       {
275         PreMultiply(pixelBuffer, preMultiplyOnLoad);
276         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
277
278         if(data)
279         {
280           textureSet = imageAtlasManager->Add(textureRect, data);
281           if(textureSet)
282           {
283             textureRectSize.SetWidth(data.GetWidth());
284             textureRectSize.SetHeight(data.GetHeight());
285           }
286         }
287         else
288         {
289           DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous Texture loading with atlasing is failed.\n");
290         }
291       }
292       if(!textureSet)
293       {
294         atlasingStatus = false;
295       }
296     }
297
298     if(!textureSet)
299     {
300       loadingStatus = true;
301       if(atlasingStatus)
302       {
303         textureSet = imageAtlasManager->Add(textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
304       }
305       if(!textureSet) // big image, no atlasing or atlasing failed
306       {
307         atlasingStatus = false;
308         if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
309         {
310           textureId = RequestLoad(url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad, synchronousLoading);
311         }
312         else
313         {
314           maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl, synchronousLoading);
315           textureId              = RequestLoad(url,
316                                   maskInfo->mAlphaMaskId,
317                                   maskInfo->mContentScaleFactor,
318                                   desiredSize,
319                                   fittingMode,
320                                   samplingMode,
321                                   TextureManager::NO_ATLAS,
322                                   maskInfo->mCropToMask,
323                                   textureObserver,
324                                   orientationCorrection,
325                                   reloadPolicy,
326                                   preMultiplyOnLoad,
327                                   synchronousLoading);
328         }
329
330         TextureManager::LoadState loadState = GetTextureStateInternal(textureId);
331         if(loadState == TextureManager::LoadState::UPLOADED)
332         {
333           // UploadComplete has already been called - keep the same texture set
334           textureSet = GetTextureSet(textureId);
335         }
336
337         // If we are loading the texture, or waiting for the ready signal handler to complete, inform
338         // caller that they need to wait.
339         loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
340                          loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
341                          loadState == TextureManager::LoadState::MASK_APPLYING ||
342                          loadState == TextureManager::LoadState::MASK_APPLIED ||
343                          loadState == TextureManager::LoadState::NOT_STARTED ||
344                          mQueueLoadFlag);
345       }
346       else
347       {
348         textureRectSize = desiredSize;
349       }
350     }
351   }
352
353   if(!atlasingStatus && textureSet)
354   {
355     Sampler sampler = Sampler::New();
356     sampler.SetWrapMode(wrapModeU, wrapModeV);
357     textureSet.SetSampler(0u, sampler);
358   }
359
360   if(synchronousLoading)
361   {
362     loadingStatus = false;
363   }
364
365   return textureSet;
366 }
367
368 TextureManager::TextureId TextureManager::RequestLoad(
369   const VisualUrl&                url,
370   const ImageDimensions           desiredSize,
371   FittingMode::Type               fittingMode,
372   Dali::SamplingMode::Type        samplingMode,
373   const UseAtlas                  useAtlas,
374   TextureUploadObserver*          observer,
375   bool                            orientationCorrection,
376   TextureManager::ReloadPolicy    reloadPolicy,
377   TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
378   bool                            synchronousLoading)
379 {
380   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);
381 }
382
383 TextureManager::TextureId TextureManager::RequestLoad(
384   const VisualUrl&                url,
385   TextureId                       maskTextureId,
386   float                           contentScale,
387   const ImageDimensions           desiredSize,
388   FittingMode::Type               fittingMode,
389   Dali::SamplingMode::Type        samplingMode,
390   const UseAtlas                  useAtlas,
391   bool                            cropToMask,
392   TextureUploadObserver*          observer,
393   bool                            orientationCorrection,
394   TextureManager::ReloadPolicy    reloadPolicy,
395   TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
396   bool                            synchronousLoading)
397 {
398   return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading);
399 }
400
401 TextureManager::TextureId TextureManager::RequestMaskLoad(const VisualUrl& maskUrl, bool synchronousLoading)
402 {
403   // Use the normal load procedure to get the alpha mask.
404   auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
405   return RequestLoadInternal(maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true, TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u, synchronousLoading);
406 }
407
408 TextureManager::TextureId TextureManager::RequestLoadInternal(
409   const VisualUrl&                url,
410   TextureId                       maskTextureId,
411   float                           contentScale,
412   const ImageDimensions           desiredSize,
413   FittingMode::Type               fittingMode,
414   Dali::SamplingMode::Type        samplingMode,
415   UseAtlas                        useAtlas,
416   bool                            cropToMask,
417   StorageType                     storageType,
418   TextureUploadObserver*          observer,
419   bool                            orientationCorrection,
420   TextureManager::ReloadPolicy    reloadPolicy,
421   TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
422   Dali::AnimatedImageLoading      animatedImageLoading,
423   uint32_t                        frameIndex,
424   bool                            synchronousLoading)
425 {
426   // First check if the requested Texture is cached.
427   bool isAnimatedImage = (animatedImageLoading) ? true : false;
428
429   TextureHash textureHash = INITIAL_CACHE_NUMBER;
430   int         cacheIndex  = INVALID_CACHE_INDEX;
431   if(storageType != StorageType::RETURN_PIXEL_BUFFER && !isAnimatedImage)
432   {
433     textureHash = GenerateHash(url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId);
434
435     // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
436     cacheIndex = FindCachedTexture(textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, preMultiplyOnLoad);
437   }
438
439   TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
440   // Check if the requested Texture exists in the cache.
441   if(cacheIndex != INVALID_CACHE_INDEX)
442   {
443     if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
444     {
445       // Mark this texture being used by another client resource. Forced reload would replace the current texture
446       // without the need for incrementing the reference count.
447       ++(mTextureInfoContainer[cacheIndex].referenceCount);
448     }
449     textureId = mTextureInfoContainer[cacheIndex].textureId;
450
451     // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
452     preMultiplyOnLoad = mTextureInfoContainer[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
453
454     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
455   }
456
457   if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
458   {
459     if(VisualUrl::BUFFER == url.GetProtocolType())
460     {
461       std::string location = url.GetLocation();
462       if(location.size() > 0u)
463       {
464         TextureId                 targetId           = std::stoi(location);
465         const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(targetId);
466         if(encodedImageBuffer)
467         {
468           textureId = targetId;
469
470           // Increase EncodedImageBuffer reference during it contains mTextureInfoContainer.
471           UseExternalResource(url.GetUrl());
472         }
473       }
474     }
475
476     if(textureId == INVALID_TEXTURE_ID)
477     {
478       textureId = GenerateUniqueTextureId();
479     }
480
481     bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
482     mTextureInfoContainer.push_back(TextureInfo(textureId, maskTextureId, url, desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
483     cacheIndex = mTextureInfoContainer.size() - 1u;
484
485     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, textureId);
486   }
487
488   // The below code path is common whether we are using the cache or not.
489   // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
490   // or a new TextureInfo just created.
491   TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
492   textureInfo.maskTextureId         = maskTextureId;
493   textureInfo.storageType           = storageType;
494   textureInfo.orientationCorrection = orientationCorrection;
495
496   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
497
498   // Force reloading of texture by setting loadState unless already loading or cancelled.
499   if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
500      TextureManager::LoadState::LOADING != textureInfo.loadState &&
501      TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
502      TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
503      TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
504      TextureManager::LoadState::CANCELLED != textureInfo.loadState)
505   {
506     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
507
508     textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
509   }
510
511   if(!synchronousLoading)
512   {
513     // Check if we should add the observer.
514     // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
515     switch(textureInfo.loadState)
516     {
517       case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
518       case TextureManager::LoadState::NOT_STARTED:
519       {
520         LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
521         break;
522       }
523       case TextureManager::LoadState::LOADING:
524       case TextureManager::LoadState::WAITING_FOR_MASK:
525       case TextureManager::LoadState::MASK_APPLYING:
526       case TextureManager::LoadState::MASK_APPLIED:
527       {
528         ObserveTexture(textureInfo, observer);
529         break;
530       }
531       case TextureManager::LoadState::UPLOADED:
532       {
533         if(observer)
534         {
535           LoadOrQueueTexture(textureInfo, observer);
536         }
537         break;
538       }
539       case TextureManager::LoadState::CANCELLED:
540       {
541         // A cancelled texture hasn't finished loading yet. Treat as a loading texture
542         // (it's ref count has already been incremented, above)
543         textureInfo.loadState = TextureManager::LoadState::LOADING;
544         ObserveTexture(textureInfo, observer);
545         break;
546       }
547       case TextureManager::LoadState::LOAD_FINISHED:
548       {
549         // Loading has already completed.
550         if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
551         {
552           LoadOrQueueTexture(textureInfo, observer);
553         }
554         break;
555       }
556     }
557   }
558   else
559   {
560     // If the image is already finished to load, use cached texture.
561     // We don't need to consider Observer becaouse this is synchronous loading.
562     if(textureInfo.loadState == TextureManager::LoadState::UPLOADED ||
563        textureInfo.loadState == TextureManager::LoadState::LOAD_FINISHED)
564     {
565       return textureId;
566     }
567     else
568     {
569       Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);;
570
571       if(!pixelBuffer)
572       {
573         // If pixelBuffer loading is failed in synchronously, call Remove() method.
574         Remove(textureId, nullptr);
575         return INVALID_TEXTURE_ID;
576       }
577
578       if(storageType == StorageType::KEEP_PIXEL_BUFFER) // For the mask image loading.
579       {
580         textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
581         textureInfo.loadState   = LoadState::LOAD_FINISHED;
582       }
583       else // For the image loading.
584       {
585         if(maskTextureId != INVALID_TEXTURE_ID)
586         {
587           int maskCacheIndex = GetCacheIndexFromId(maskTextureId);
588           if(maskCacheIndex != INVALID_CACHE_INDEX)
589           {
590             Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
591             if(maskPixelBuffer)
592             {
593               pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask);
594             }
595           }
596           else
597           {
598             DALI_LOG_ERROR("Mask image is not stored in cache.\n");
599           }
600         }
601         PreMultiply(pixelBuffer, preMultiplyOnLoad);
602
603         // Upload texture
604         UploadTexture(pixelBuffer, textureInfo);
605       }
606     }
607   }
608
609   // Return the TextureId for which this Texture can now be referenced by externally.
610   return textureId;
611 }
612
613 void TextureManager::Remove(const TextureManager::TextureId textureId, TextureUploadObserver* observer)
614 {
615   int textureInfoIndex = GetCacheIndexFromId(textureId);
616
617   if(textureInfoIndex != INVALID_INDEX)
618   {
619     TextureInfo& textureInfo(mTextureInfoContainer[textureInfoIndex]);
620
621     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) url:%s\n  cacheIdx:%d loadState:%s reference count = %d\n", textureId, textureInfo.url.GetUrl().c_str(), textureInfoIndex, GET_LOAD_STATE_STRING(textureInfo.loadState), textureInfo.referenceCount);
622
623     // Decrement the reference count and check if this is the last user of this Texture.
624     if(--textureInfo.referenceCount <= 0)
625     {
626       // This is the last remove for this Texture.
627       textureInfo.referenceCount = 0;
628       bool removeTextureInfo     = false;
629
630       // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
631       if(textureInfo.loadState == LoadState::UPLOADED)
632       {
633         if(textureInfo.atlas)
634         {
635           textureInfo.atlas.Remove(textureInfo.atlasRect);
636         }
637         removeTextureInfo = true;
638       }
639       else if(textureInfo.loadState == LoadState::LOADING)
640       {
641         // We mark the textureInfo for removal.
642         // Once the load has completed, this method will be called again.
643         textureInfo.loadState = LoadState::CANCELLED;
644       }
645       else
646       {
647         // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
648         removeTextureInfo = true;
649       }
650
651       // If the state allows us to remove the TextureInfo data, we do so.
652       if(removeTextureInfo)
653       {
654         // If url location is BUFFER, decrease reference count of EncodedImageBuffer.
655         if(textureInfo.url.IsBufferResource())
656         {
657           RemoveExternalEncodedImageBuffer(textureInfo.url.GetUrl());
658         }
659         // Permanently remove the textureInfo struct.
660         mTextureInfoContainer.erase(mTextureInfoContainer.begin() + textureInfoIndex);
661       }
662     }
663
664     if(observer)
665     {
666       // Remove element from the LoadQueue
667       for(auto&& element : mLoadQueue)
668       {
669         if(element.mObserver == observer)
670         {
671           // Do not erase the item. We will clear it later in ProcessQueuedTextures().
672           element.mObserver = nullptr;
673           break;
674         }
675       }
676     }
677   }
678 }
679
680 VisualUrl TextureManager::GetVisualUrl(TextureId textureId)
681 {
682   VisualUrl visualUrl("");
683   int       cacheIndex = GetCacheIndexFromId(textureId);
684
685   if(cacheIndex != INVALID_CACHE_INDEX)
686   {
687     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n", cacheIndex, textureId);
688
689     TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
690     visualUrl = cachedTextureInfo.url;
691   }
692   return visualUrl;
693 }
694
695 TextureManager::LoadState TextureManager::GetTextureState(TextureId textureId)
696 {
697   LoadState loadState = TextureManager::LoadState::NOT_STARTED;
698
699   int cacheIndex = GetCacheIndexFromId(textureId);
700   if(cacheIndex != INVALID_CACHE_INDEX)
701   {
702     TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
703     loadState = cachedTextureInfo.loadState;
704   }
705   else
706   {
707     for(auto&& elem : mExternalTextures)
708     {
709       if(elem.textureId == textureId)
710       {
711         loadState = LoadState::UPLOADED;
712         break;
713       }
714     }
715   }
716   return loadState;
717 }
718
719 TextureManager::LoadState TextureManager::GetTextureStateInternal(TextureId textureId)
720 {
721   LoadState loadState = TextureManager::LoadState::NOT_STARTED;
722
723   int cacheIndex = GetCacheIndexFromId(textureId);
724   if(cacheIndex != INVALID_CACHE_INDEX)
725   {
726     TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
727     loadState = cachedTextureInfo.loadState;
728   }
729
730   return loadState;
731 }
732
733 Devel::PixelBuffer TextureManager::LoadImageSynchronously(const VisualUrl&         url,
734                                                           const ImageDimensions    desiredSize,
735                                                           FittingMode::Type        fittingMode,
736                                                           Dali::SamplingMode::Type samplingMode,
737                                                           bool                     orientationCorrection)
738 {
739   Devel::PixelBuffer pixelBuffer;
740   if(url.IsBufferResource())
741   {
742     const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(url.GetUrl());
743     if(encodedImageBuffer)
744     {
745       pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
746     }
747   }
748   else
749   {
750     pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
751   }
752   return pixelBuffer;
753 }
754
755 TextureSet TextureManager::GetTextureSet(TextureId textureId)
756 {
757   TextureSet textureSet; // empty handle
758
759   int cacheIndex = GetCacheIndexFromId(textureId);
760   if(cacheIndex != INVALID_CACHE_INDEX)
761   {
762     TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
763     textureSet = cachedTextureInfo.textureSet;
764   }
765   else
766   {
767     for(auto&& elem : mExternalTextures)
768     {
769       if(elem.textureId == textureId)
770       {
771         textureSet = elem.textureSet;
772         break;
773       }
774     }
775   }
776   return textureSet;
777 }
778
779 EncodedImageBuffer TextureManager::GetEncodedImageBuffer(TextureId textureId)
780 {
781   EncodedImageBuffer encodedImageBuffer; // empty handle
782   for(auto&& elem : mEncodedBufferTextures)
783   {
784     if(elem.textureId == textureId)
785     {
786       encodedImageBuffer = elem.encodedImageBuffer;
787       break;
788     }
789   }
790   return encodedImageBuffer;
791 }
792
793 EncodedImageBuffer TextureManager::GetEncodedImageBuffer(const std::string& url)
794 {
795   EncodedImageBuffer encodedImageBuffer; // empty handle
796   if(url.size() > 0 && VisualUrl::BUFFER == VisualUrl::GetProtocolType(url))
797   {
798     std::string location = VisualUrl::GetLocation(url);
799     if(location.size() > 0u)
800     {
801       TextureId targetId = std::stoi(location);
802       return GetEncodedImageBuffer(targetId);
803     }
804   }
805   return encodedImageBuffer;
806 }
807
808 std::string TextureManager::AddExternalTexture(TextureSet& textureSet)
809 {
810   TextureManager::ExternalTextureInfo info;
811   info.textureId  = GenerateUniqueTextureId();
812   info.textureSet = textureSet;
813   mExternalTextures.emplace_back(info);
814
815   return VisualUrl::CreateTextureUrl(std::to_string(info.textureId));
816 }
817
818 std::string TextureManager::AddExternalEncodedImageBuffer(const EncodedImageBuffer& encodedImageBuffer)
819 {
820   // Duplication check
821   for(auto&& elem : mEncodedBufferTextures)
822   {
823     if(elem.encodedImageBuffer == encodedImageBuffer)
824     {
825       // If same buffer added, increase reference count and return.
826       elem.referenceCount++;
827       return VisualUrl::CreateBufferUrl(std::to_string(elem.textureId));
828     }
829   }
830   TextureManager::EncodedBufferTextureInfo info(GenerateUniqueTextureId(), encodedImageBuffer);
831   mEncodedBufferTextures.emplace_back(info);
832   return VisualUrl::CreateBufferUrl(std::to_string(info.textureId));
833 }
834
835 TextureSet TextureManager::RemoveExternalTexture(const std::string& url)
836 {
837   if(url.size() > 0u)
838   {
839     if(VisualUrl::TEXTURE == VisualUrl::GetProtocolType(url))
840     {
841       // get the location from the Url
842       std::string location = VisualUrl::GetLocation(url);
843       if(location.size() > 0u)
844       {
845         TextureId  id  = std::stoi(location);
846         const auto end = mExternalTextures.end();
847         for(auto iter = mExternalTextures.begin(); iter != end; ++iter)
848         {
849           if(iter->textureId == id)
850           {
851             auto textureSet = iter->textureSet;
852             if(--(iter->referenceCount) <= 0)
853             {
854               mExternalTextures.erase(iter);
855             }
856             return textureSet;
857           }
858         }
859       }
860     }
861   }
862   return TextureSet();
863 }
864
865 EncodedImageBuffer TextureManager::RemoveExternalEncodedImageBuffer(const std::string& url)
866 {
867   if(url.size() > 0u)
868   {
869     if(VisualUrl::BUFFER == VisualUrl::GetProtocolType(url))
870     {
871       // get the location from the Url
872       std::string location = VisualUrl::GetLocation(url);
873       if(location.size() > 0u)
874       {
875         TextureId  id  = std::stoi(location);
876         const auto end = mEncodedBufferTextures.end();
877         for(auto iter = mEncodedBufferTextures.begin(); iter != end; ++iter)
878         {
879           if(iter->textureId == id)
880           {
881             auto encodedImageBuffer = iter->encodedImageBuffer;
882             if(--(iter->referenceCount) <= 0)
883             {
884               mEncodedBufferTextures.erase(iter);
885             }
886             return encodedImageBuffer;
887           }
888         }
889       }
890     }
891   }
892   return EncodedImageBuffer();
893 }
894
895 void TextureManager::UseExternalResource(const VisualUrl& url)
896 {
897   if(VisualUrl::TEXTURE == url.GetProtocolType())
898   {
899     std::string location = url.GetLocation();
900     if(location.size() > 0u)
901     {
902       TextureId id = std::stoi(location);
903       for(auto&& elem : mExternalTextures)
904       {
905         if(elem.textureId == id)
906         {
907           elem.referenceCount++;
908           return;
909         }
910       }
911     }
912   }
913   else if(VisualUrl::BUFFER == url.GetProtocolType())
914   {
915     std::string location = url.GetLocation();
916     if(location.size() > 0u)
917     {
918       TextureId id = std::stoi(location);
919       for(auto&& elem : mEncodedBufferTextures)
920       {
921         if(elem.textureId == id)
922         {
923           elem.referenceCount++;
924           return;
925         }
926       }
927     }
928   }
929 }
930
931 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
932 {
933   // make sure an observer doesn't observe the same object twice
934   // otherwise it will get multiple calls to ObjectDestroyed()
935   DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
936   mLifecycleObservers.PushBack(&observer);
937 }
938
939 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
940 {
941   // Find the observer...
942   auto endIter = mLifecycleObservers.End();
943   for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
944   {
945     if((*iter) == &observer)
946     {
947       mLifecycleObservers.Erase(iter);
948       break;
949     }
950   }
951   DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
952 }
953
954 void TextureManager::LoadOrQueueTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
955 {
956   switch(textureInfo.loadState)
957   {
958     case LoadState::NOT_STARTED:
959     case LoadState::LOAD_FAILED:
960     {
961       if(mQueueLoadFlag)
962       {
963         QueueLoadTexture(textureInfo, observer);
964       }
965       else
966       {
967         LoadTexture(textureInfo, observer);
968       }
969       break;
970     }
971     case LoadState::UPLOADED:
972     {
973       if(mQueueLoadFlag)
974       {
975         QueueLoadTexture(textureInfo, observer);
976       }
977       else
978       {
979         // The Texture has already loaded. The other observers have already been notified.
980         // We need to send a "late" loaded notification for this observer.
981         observer->UploadComplete(true, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied);
982       }
983       break;
984     }
985     case LoadState::LOADING:
986     case LoadState::CANCELLED:
987     case LoadState::LOAD_FINISHED:
988     case LoadState::WAITING_FOR_MASK:
989     case LoadState::MASK_APPLYING:
990     case LoadState::MASK_APPLIED:
991     {
992       break;
993     }
994   }
995 }
996
997 void TextureManager::QueueLoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
998 {
999   auto textureId = textureInfo.textureId;
1000   mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
1001
1002   observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
1003 }
1004
1005 void TextureManager::LoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
1006 {
1007   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
1008
1009   textureInfo.loadState = LoadState::LOADING;
1010   if(!textureInfo.loadSynchronously)
1011   {
1012     auto& loadersContainer  = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1013     auto  loadingHelperIt   = loadersContainer.GetNext();
1014     auto  premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1015     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1016     if(textureInfo.animatedImageLoading)
1017     {
1018       loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex);
1019     }
1020     else
1021     {
1022       loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
1023     }
1024   }
1025   ObserveTexture(textureInfo, observer);
1026 }
1027
1028 void TextureManager::ProcessQueuedTextures()
1029 {
1030   for(auto&& element : mLoadQueue)
1031   {
1032     if(!element.mObserver)
1033     {
1034       continue;
1035     }
1036
1037     int cacheIndex = GetCacheIndexFromId(element.mTextureId);
1038     if(cacheIndex != INVALID_CACHE_INDEX)
1039     {
1040       TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
1041       if(textureInfo.loadState == LoadState::UPLOADED)
1042       {
1043         element.mObserver->UploadComplete(true, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied);
1044       }
1045       else if(textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1046       {
1047         element.mObserver->LoadComplete(true, textureInfo.pixelBuffer, textureInfo.url, textureInfo.preMultiplied);
1048       }
1049       else
1050       {
1051         LoadTexture(textureInfo, element.mObserver);
1052       }
1053     }
1054   }
1055   mLoadQueue.Clear();
1056 }
1057
1058 void TextureManager::ObserveTexture(TextureInfo&           textureInfo,
1059                                     TextureUploadObserver* observer)
1060 {
1061   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
1062
1063   if(observer)
1064   {
1065     textureInfo.observerList.PushBack(observer);
1066     observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
1067   }
1068 }
1069
1070 void TextureManager::AsyncLoadComplete(AsyncLoadingInfoContainerType& loadingContainer, uint32_t id, Devel::PixelBuffer pixelBuffer)
1071 {
1072   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id);
1073
1074   if(loadingContainer.size() >= 1u)
1075   {
1076     AsyncLoadingInfo loadingInfo = loadingContainer.front();
1077
1078     if(loadingInfo.loadId == id)
1079     {
1080       int cacheIndex = GetCacheIndexFromId(loadingInfo.textureId);
1081       if(cacheIndex != INVALID_CACHE_INDEX)
1082       {
1083         TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
1084
1085         DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "  textureId:%d Url:%s CacheIndex:%d LoadState: %d\n", textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState);
1086
1087         if(textureInfo.loadState != LoadState::CANCELLED)
1088         {
1089           // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
1090           PostLoad(textureInfo, pixelBuffer);
1091         }
1092         else
1093         {
1094           Remove(textureInfo.textureId, nullptr);
1095         }
1096       }
1097     }
1098
1099     loadingContainer.pop_front();
1100   }
1101 }
1102
1103 void TextureManager::PostLoad(TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
1104 {
1105   // Was the load successful?
1106   if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
1107   {
1108     // No atlas support for now
1109     textureInfo.useAtlas      = NO_ATLAS;
1110     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1111
1112     if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
1113     {
1114       // If there is a mask texture ID associated with this texture, then apply the mask
1115       // if it's already loaded. If it hasn't, and the mask is still loading,
1116       // wait for the mask to finish loading.
1117       // note, If the texture is already uploaded synchronously during loading,
1118       // we don't need to apply mask.
1119       if(textureInfo.loadState != LoadState::UPLOADED &&
1120          textureInfo.maskTextureId != INVALID_TEXTURE_ID)
1121       {
1122         if(textureInfo.loadState == LoadState::MASK_APPLYING)
1123         {
1124           textureInfo.loadState = LoadState::MASK_APPLIED;
1125           UploadTexture(pixelBuffer, textureInfo);
1126           NotifyObservers(textureInfo, true);
1127         }
1128         else
1129         {
1130           LoadState maskLoadState = GetTextureStateInternal(textureInfo.maskTextureId);
1131           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
1132           if(maskLoadState == LoadState::LOADING)
1133           {
1134             textureInfo.loadState = LoadState::WAITING_FOR_MASK;
1135           }
1136           else if(maskLoadState == LoadState::LOAD_FINISHED)
1137           {
1138             // Send New Task to Thread
1139             ApplyMask(textureInfo, textureInfo.maskTextureId);
1140           }
1141         }
1142       }
1143       else
1144       {
1145         UploadTexture(pixelBuffer, textureInfo);
1146         NotifyObservers(textureInfo, true);
1147       }
1148     }
1149     else
1150     {
1151       textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
1152       textureInfo.loadState   = LoadState::LOAD_FINISHED;
1153
1154       if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1155       {
1156         NotifyObservers(textureInfo, true);
1157       }
1158       else
1159       {
1160         // Check if there was another texture waiting for this load to complete
1161         // (e.g. if this was an image mask, and its load is on a different thread)
1162         CheckForWaitingTexture(textureInfo);
1163       }
1164     }
1165   }
1166   else
1167   {
1168     textureInfo.loadState = LoadState::LOAD_FAILED;
1169     CheckForWaitingTexture(textureInfo);
1170     NotifyObservers(textureInfo, false);
1171   }
1172 }
1173
1174 void TextureManager::CheckForWaitingTexture(TextureInfo& maskTextureInfo)
1175 {
1176   // Search the cache, checking if any texture has this texture id as a
1177   // maskTextureId:
1178   const unsigned int size = mTextureInfoContainer.size();
1179
1180   for(unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex)
1181   {
1182     if(mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
1183        mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
1184     {
1185       TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
1186
1187       if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED)
1188       {
1189         // Send New Task to Thread
1190         ApplyMask(textureInfo, maskTextureInfo.textureId);
1191       }
1192       else
1193       {
1194         textureInfo.pixelBuffer.Reset();
1195         textureInfo.loadState = LoadState::LOAD_FAILED;
1196         NotifyObservers(textureInfo, false);
1197       }
1198     }
1199   }
1200 }
1201
1202 void TextureManager::ApplyMask(TextureInfo& textureInfo, TextureId maskTextureId)
1203 {
1204   int maskCacheIndex = GetCacheIndexFromId(maskTextureId);
1205   if(maskCacheIndex != INVALID_CACHE_INDEX)
1206   {
1207     Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
1208     Devel::PixelBuffer pixelBuffer     = textureInfo.pixelBuffer;
1209     textureInfo.pixelBuffer.Reset();
1210
1211     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
1212
1213     textureInfo.loadState   = LoadState::MASK_APPLYING;
1214     auto& loadersContainer  = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1215     auto  loadingHelperIt   = loadersContainer.GetNext();
1216     auto  premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1217     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1218     loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
1219   }
1220 }
1221
1222 void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo)
1223 {
1224   if(textureInfo.loadState != LoadState::UPLOADED && textureInfo.useAtlas != USE_ATLAS)
1225   {
1226     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "  TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
1227
1228     // Check if this pixelBuffer is premultiplied
1229     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1230
1231     auto& renderingAddOn = RenderingAddOn::Get();
1232     if(renderingAddOn.IsValid())
1233     {
1234       renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
1235     }
1236
1237     Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1238
1239     PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1240     texture.Upload(pixelData);
1241     if(!textureInfo.textureSet)
1242     {
1243       textureInfo.textureSet = TextureSet::New();
1244     }
1245     textureInfo.textureSet.SetTexture(0u, texture);
1246   }
1247
1248   // Update the load state.
1249   // Note: This is regardless of success as we care about whether a
1250   // load attempt is in progress or not.  If unsuccessful, a broken
1251   // image is still loaded.
1252   textureInfo.loadState = LoadState::UPLOADED;
1253 }
1254
1255 void TextureManager::NotifyObservers(TextureInfo& textureInfo, bool success)
1256 {
1257   TextureId textureId = textureInfo.textureId;
1258
1259   // If there is an observer: Notify the load is complete, whether successful or not,
1260   // and erase it from the list
1261   TextureInfo* info = &textureInfo;
1262
1263   mQueueLoadFlag = true;
1264
1265   while(info->observerList.Count())
1266   {
1267     TextureUploadObserver* observer = info->observerList[0];
1268
1269     // During UploadComplete() a Control ResourceReady() signal is emitted.
1270     // During that signal the app may add remove /add Textures (e.g. via
1271     // ImageViews).
1272     // It is possible for observers to be removed from the observer list,
1273     // and it is also possible for the mTextureInfoContainer to be modified,
1274     // invalidating the reference to the textureInfo struct.
1275     // Texture load requests for the same URL are deferred until the end of this
1276     // method.
1277     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n", textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState));
1278
1279     // It is possible for the observer to be deleted.
1280     // Disconnect and remove the observer first.
1281     observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1282
1283     info->observerList.Erase(info->observerList.begin());
1284
1285     if(info->storageType == StorageType::RETURN_PIXEL_BUFFER)
1286     {
1287       observer->LoadComplete(success, info->pixelBuffer, info->url, info->preMultiplied);
1288     }
1289     else
1290     {
1291       observer->UploadComplete(success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect, info->preMultiplied);
1292     }
1293
1294     // Get the textureInfo from the container again as it may have been invalidated.
1295     int textureInfoIndex = GetCacheIndexFromId(textureId);
1296     if(textureInfoIndex == INVALID_CACHE_INDEX)
1297     {
1298       break; // texture has been removed - can stop.
1299     }
1300     info = &mTextureInfoContainer[textureInfoIndex];
1301   }
1302
1303   mQueueLoadFlag = false;
1304   ProcessQueuedTextures();
1305
1306   if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1307   {
1308     Remove(info->textureId, nullptr);
1309   }
1310 }
1311
1312 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
1313 {
1314   return mCurrentTextureId++;
1315 }
1316
1317 int TextureManager::GetCacheIndexFromId(const TextureId textureId)
1318 {
1319   const unsigned int size = mTextureInfoContainer.size();
1320
1321   for(unsigned int i = 0; i < size; ++i)
1322   {
1323     if(mTextureInfoContainer[i].textureId == textureId)
1324     {
1325       return i;
1326     }
1327   }
1328
1329   return INVALID_CACHE_INDEX;
1330 }
1331
1332 TextureManager::TextureHash TextureManager::GenerateHash(
1333   const std::string&             url,
1334   const ImageDimensions          size,
1335   const FittingMode::Type        fittingMode,
1336   const Dali::SamplingMode::Type samplingMode,
1337   const UseAtlas                 useAtlas,
1338   TextureId                      maskTextureId)
1339 {
1340   std::string    hashTarget(url);
1341   const size_t   urlLength = hashTarget.length();
1342   const uint16_t width     = size.GetWidth();
1343   const uint16_t height    = size.GetWidth();
1344
1345   // If either the width or height has been specified, include the resizing options in the hash
1346   if(width != 0 || height != 0)
1347   {
1348     // We are appending 5 bytes to the URL to form the hash input.
1349     hashTarget.resize(urlLength + 5u);
1350     char* hashTargetPtr = &(hashTarget[urlLength]);
1351
1352     // Pack the width and height (4 bytes total).
1353     *hashTargetPtr++ = size.GetWidth() & 0xff;
1354     *hashTargetPtr++ = (size.GetWidth() >> 8u) & 0xff;
1355     *hashTargetPtr++ = size.GetHeight() & 0xff;
1356     *hashTargetPtr++ = (size.GetHeight() >> 8u) & 0xff;
1357
1358     // Bit-pack the FittingMode, SamplingMode and atlasing.
1359     // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
1360     *hashTargetPtr = (fittingMode << 4u) | (samplingMode << 1) | useAtlas;
1361   }
1362   else
1363   {
1364     // We are not including sizing information, but we still need an extra byte for atlasing.
1365     hashTarget.resize(urlLength + 1u);
1366
1367     // Add the atlasing to the hash input.
1368     switch(useAtlas)
1369     {
1370       case UseAtlas::NO_ATLAS:
1371       {
1372         hashTarget[urlLength] = 'f';
1373         break;
1374       }
1375       case UseAtlas::USE_ATLAS:
1376       {
1377         hashTarget[urlLength] = 't';
1378         break;
1379       }
1380     }
1381   }
1382
1383   if(maskTextureId != INVALID_TEXTURE_ID)
1384   {
1385     auto textureIdIndex = hashTarget.length();
1386     hashTarget.resize(hashTarget.length() + sizeof(TextureId));
1387     unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&(hashTarget[textureIdIndex]));
1388
1389     // Append the texture id to the end of the URL byte by byte:
1390     // (to avoid SIGBUS / alignment issues)
1391     for(size_t byteIter = 0; byteIter < sizeof(TextureId); ++byteIter)
1392     {
1393       *hashTargetPtr++ = maskTextureId & 0xff;
1394       maskTextureId >>= 8u;
1395     }
1396   }
1397
1398   return Dali::CalculateHash(hashTarget);
1399 }
1400
1401 int TextureManager::FindCachedTexture(
1402   const TextureManager::TextureHash hash,
1403   const std::string&                url,
1404   const ImageDimensions             size,
1405   const FittingMode::Type           fittingMode,
1406   const Dali::SamplingMode::Type    samplingMode,
1407   const bool                        useAtlas,
1408   TextureId                         maskTextureId,
1409   TextureManager::MultiplyOnLoad    preMultiplyOnLoad)
1410 {
1411   // Default to an invalid ID, in case we do not find a match.
1412   int cacheIndex = INVALID_CACHE_INDEX;
1413
1414   // Iterate through our hashes to find a match.
1415   const unsigned int count = mTextureInfoContainer.size();
1416   for(unsigned int i = 0u; i < count; ++i)
1417   {
1418     if(mTextureInfoContainer[i].hash == hash)
1419     {
1420       // We have a match, now we check all the original parameters in case of a hash collision.
1421       TextureInfo& textureInfo(mTextureInfoContainer[i]);
1422
1423       if((url == textureInfo.url.GetUrl()) &&
1424          (useAtlas == textureInfo.useAtlas) &&
1425          (maskTextureId == textureInfo.maskTextureId) &&
1426          (size == textureInfo.desiredSize) &&
1427          ((size.GetWidth() == 0 && size.GetHeight() == 0) ||
1428           (fittingMode == textureInfo.fittingMode &&
1429            samplingMode == textureInfo.samplingMode)))
1430       {
1431         // 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different.
1432         // 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false.
1433         if((preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad) || (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied))
1434         {
1435           // The found Texture is a match.
1436           cacheIndex = i;
1437           break;
1438         }
1439       }
1440     }
1441   }
1442
1443   return cacheIndex;
1444 }
1445
1446 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1447 {
1448   const unsigned int count = mTextureInfoContainer.size();
1449   for(unsigned int i = 0; i < count; ++i)
1450   {
1451     TextureInfo& textureInfo(mTextureInfoContainer[i]);
1452     for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1453         j != textureInfo.observerList.End();)
1454     {
1455       if(*j == observer)
1456       {
1457         j = textureInfo.observerList.Erase(j);
1458       }
1459       else
1460       {
1461         ++j;
1462       }
1463     }
1464   }
1465
1466   // Remove element from the LoadQueue
1467   for(auto&& element : mLoadQueue)
1468   {
1469     if(element.mObserver == observer)
1470     {
1471       element.mObserver = nullptr;
1472     }
1473   }
1474 }
1475
1476 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1477 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager, AsyncLoadingInfoContainerType())
1478 {
1479 }
1480
1481 void TextureManager::AsyncLoadingHelper::LoadAnimatedImage(TextureId                  textureId,
1482                                                            Dali::AnimatedImageLoading animatedImageLoading,
1483                                                            uint32_t                   frameIndex)
1484 {
1485   mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1486   auto id                             = GetImplementation(mLoader).LoadAnimatedImage(animatedImageLoading, frameIndex);
1487   mLoadingInfoContainer.back().loadId = id;
1488 }
1489
1490 void TextureManager::AsyncLoadingHelper::Load(TextureId                                textureId,
1491                                               const VisualUrl&                         url,
1492                                               ImageDimensions                          desiredSize,
1493                                               FittingMode::Type                        fittingMode,
1494                                               SamplingMode::Type                       samplingMode,
1495                                               bool                                     orientationCorrection,
1496                                               DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
1497 {
1498   mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1499   if(DALI_UNLIKELY(url.IsBufferResource()))
1500   {
1501     auto id                             = GetImplementation(mLoader).LoadEncodedImageBuffer(mTextureManager.GetEncodedImageBuffer(url.GetUrl()), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad);
1502     mLoadingInfoContainer.back().loadId = id;
1503   }
1504   else
1505   {
1506     auto id                             = GetImplementation(mLoader).Load(url, desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad);
1507     mLoadingInfoContainer.back().loadId = id;
1508   }
1509 }
1510
1511 void TextureManager::AsyncLoadingHelper::ApplyMask(TextureId                                textureId,
1512                                                    Devel::PixelBuffer                       pixelBuffer,
1513                                                    Devel::PixelBuffer                       maskPixelBuffer,
1514                                                    float                                    contentScale,
1515                                                    bool                                     cropToMask,
1516                                                    DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
1517 {
1518   mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1519   auto id                             = GetImplementation(mLoader).ApplyMask(pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad);
1520   mLoadingInfoContainer.back().loadId = id;
1521 }
1522
1523 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1524 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1525 {
1526 }
1527
1528 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1529   Toolkit::AsyncImageLoader       loader,
1530   TextureManager&                 textureManager,
1531   AsyncLoadingInfoContainerType&& loadingInfoContainer)
1532 : mLoader(loader),
1533   mTextureManager(textureManager),
1534   mLoadingInfoContainer(std::move(loadingInfoContainer))
1535 {
1536   DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1537     this, &AsyncLoadingHelper::AsyncLoadComplete);
1538 }
1539
1540 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t           id,
1541                                                            Devel::PixelBuffer pixelBuffer)
1542 {
1543   mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1544 }
1545
1546 Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements)
1547 {
1548   return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1549 }
1550
1551 } // namespace Internal
1552
1553 } // namespace Toolkit
1554
1555 } // namespace Dali