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