[Tizen] Fix to avoid empty texture rendering issue
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / texture-manager-impl.cpp
1  /*
2  * Copyright (c) 2018 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/images/texture-set-image.h>
29 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
30 #include <dali/integration-api/debug.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
37 namespace
38 {
39
40 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
41 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
42
43 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
44 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
45
46 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
47 {
48   using Dali::EnvironmentVariable::GetEnvironmentVariable;
49   auto numberString = GetEnvironmentVariable(environmentVariable);
50   auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
51   constexpr auto MAX_NUMBER_OF_THREADS = 100u;
52   DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS );
53   return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue;
54 }
55
56 size_t GetNumberOfLocalLoaderThreads()
57 {
58   return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
59 }
60
61 size_t GetNumberOfRemoteLoaderThreads()
62 {
63   return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
64 }
65
66 } // namespace
67
68 namespace Dali
69 {
70
71 namespace Toolkit
72 {
73
74 namespace Internal
75 {
76
77 namespace
78 {
79
80 #ifdef DEBUG_ENABLED
81 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TEXTURE_MANAGER" );
82 #endif
83
84 const uint32_t      DEFAULT_ATLAS_SIZE( 1024u );                     ///< This size can fit 8 by 8 images of average size 128 * 128
85 const Vector4       FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f );       ///< UV Rectangle that covers the full Texture
86 const int           INVALID_INDEX( -1 );                             ///< Invalid index used to represent a non-existant TextureInfo struct
87 const int           INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
88
89
90 void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
91 {
92   if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
93   {
94     if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
95     {
96       pixelBuffer.MultiplyColorByAlpha();
97     }
98   }
99   else
100   {
101     preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
102   }
103 }
104
105 } // Anonymous namespace
106
107 TextureManager::MaskingData::MaskingData()
108 : mAlphaMaskUrl(),
109   mAlphaMaskId( INVALID_TEXTURE_ID ),
110   mContentScaleFactor( 1.0f ),
111   mCropToMask( true )
112 {
113 }
114
115 TextureManager::TextureManager()
116 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
117   mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
118   mExternalTextures(),
119   mLifecycleObservers(),
120   mBrokenImageUrl(""),
121   mCurrentTextureId( 0 )
122 {
123 }
124
125 TextureManager::~TextureManager()
126 {
127   for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
128   {
129     (*iter)->TextureManagerDestroyed();
130   }
131 }
132
133 TextureSet TextureManager::LoadTexture(
134   const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
135   Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
136   bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
137   Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus,
138   Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
139   AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
140   TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
141 {
142   TextureSet textureSet;
143
144   loadingStatus = false;
145   textureRect = FULL_ATLAS_RECT;
146
147   if( VisualUrl::TEXTURE == url.GetProtocolType())
148   {
149     std::string location = url.GetLocation();
150     if( location.size() > 0u )
151     {
152       TextureId id = std::stoi( location );
153       for( auto&& elem : mExternalTextures )
154       {
155         if( elem.textureId == id )
156         {
157           preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
158           textureId = elem.textureId;
159           return elem.textureSet;
160         }
161       }
162     }
163   }
164   else if( synchronousLoading )
165   {
166     PixelData data;
167     if( url.IsValid() )
168     {
169       Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
170                                        orientationCorrection  );
171       if( pixelBuffer )
172       {
173         PreMultiply( pixelBuffer, preMultiplyOnLoad );
174         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
175       }
176     }
177     if( !data )
178     {
179       // use broken image
180       textureSet = TextureSet::New();
181       Devel::PixelBuffer pixelBuffer = LoadImageFromFile( mBrokenImageUrl );
182       if( pixelBuffer )
183       {
184         PreMultiply( pixelBuffer, preMultiplyOnLoad );
185         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
186       }
187       Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
188                                       data.GetWidth(), data.GetHeight() );
189       texture.Upload( data );
190       textureSet = TextureSet::New();
191       textureSet.SetTexture( 0u, texture );
192     }
193     else
194     {
195       if( atlasingStatus ) // attempt atlasing
196       {
197         textureSet = imageAtlasManager->Add( textureRect, data );
198       }
199       if( !textureSet ) // big image, no atlasing or atlasing failed
200       {
201         atlasingStatus = false;
202         Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
203                                         data.GetWidth(), data.GetHeight() );
204         texture.Upload( data );
205         textureSet = TextureSet::New();
206         textureSet.SetTexture( 0u, texture );
207       }
208       else
209       {
210         textureRectSize.SetWidth(data.GetWidth());
211         textureRectSize.SetHeight(data.GetHeight());
212       }
213     }
214   }
215   else
216   {
217     loadingStatus = true;
218     if( atlasingStatus )
219     {
220       textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
221     }
222     if( !textureSet ) // big image, no atlasing or atlasing failed
223     {
224       atlasingStatus = false;
225       if( !maskInfo )
226       {
227         textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
228                                  textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
229       }
230       else
231       {
232         textureId = RequestLoad( url,
233                                  maskInfo->mAlphaMaskId,
234                                  maskInfo->mContentScaleFactor,
235                                  desiredSize,
236                                  fittingMode, samplingMode,
237                                  TextureManager::NO_ATLAS,
238                                  maskInfo->mCropToMask,
239                                  textureObserver,
240                                  orientationCorrection,
241                                  reloadPolicy, preMultiplyOnLoad );
242       }
243
244       TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
245       switch (loadState)
246       {
247         case TextureManager::NOT_STARTED :
248         case TextureManager::LOADING :
249         case TextureManager::LOAD_FAILED :
250         {
251           loadingStatus = true;
252           break;
253         }
254         default :
255         {
256           loadingStatus = false;
257           break;
258         }
259       }
260
261       if( loadState == TextureManager::UPLOADED )
262       {
263         // UploadComplete has already been called - keep the same texture set
264         textureSet = GetTextureSet( textureId );
265       }
266     }
267     else
268     {
269       textureRectSize = desiredSize;
270     }
271   }
272
273   if( ! atlasingStatus && textureSet )
274   {
275     Sampler sampler = Sampler::New();
276     sampler.SetWrapMode(  wrapModeU, wrapModeV  );
277     textureSet.SetSampler( 0u, sampler );
278   }
279
280   return textureSet;
281 }
282
283 TextureManager::TextureId TextureManager::RequestLoad(
284   const VisualUrl&                url,
285   const ImageDimensions           desiredSize,
286   FittingMode::Type               fittingMode,
287   Dali::SamplingMode::Type        samplingMode,
288   const UseAtlas                  useAtlas,
289   TextureUploadObserver*          observer,
290   bool                            orientationCorrection,
291   TextureManager::ReloadPolicy    reloadPolicy,
292   TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
293 {
294   return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
295                               false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
296                               preMultiplyOnLoad );
297 }
298
299 TextureManager::TextureId TextureManager::RequestLoad(
300   const VisualUrl&                url,
301   TextureId                       maskTextureId,
302   float                           contentScale,
303   const ImageDimensions           desiredSize,
304   FittingMode::Type               fittingMode,
305   Dali::SamplingMode::Type        samplingMode,
306   const UseAtlas                  useAtlas,
307   bool                            cropToMask,
308   TextureUploadObserver*          observer,
309   bool                            orientationCorrection,
310   TextureManager::ReloadPolicy    reloadPolicy,
311   TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
312 {
313   return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
314                               cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
315                               preMultiplyOnLoad );
316 }
317
318 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
319 {
320   // Use the normal load procedure to get the alpha mask.
321   auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
322   return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
323                               SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
324                               TextureManager::ReloadPolicy::CACHED, preMultiply );
325 }
326
327 TextureManager::TextureId TextureManager::RequestLoadInternal(
328   const VisualUrl&                url,
329   TextureId                       maskTextureId,
330   float                           contentScale,
331   const ImageDimensions           desiredSize,
332   FittingMode::Type               fittingMode,
333   Dali::SamplingMode::Type        samplingMode,
334   UseAtlas                        useAtlas,
335   bool                            cropToMask,
336   StorageType                     storageType,
337   TextureUploadObserver*          observer,
338   bool                            orientationCorrection,
339   TextureManager::ReloadPolicy    reloadPolicy,
340   TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
341 {
342   // First check if the requested Texture is cached.
343   const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
344                                                 maskTextureId, preMultiplyOnLoad );
345
346   TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
347
348   // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
349   int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
350                                       maskTextureId, preMultiplyOnLoad );
351
352   // Check if the requested Texture exists in the cache.
353   if( cacheIndex != INVALID_CACHE_INDEX )
354   {
355     if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
356     {
357       // Mark this texture being used by another client resource. Forced reload would replace the current texture
358       // without the need for incrementing the reference count.
359       ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
360     }
361     textureId = mTextureInfoContainer[ cacheIndex ].textureId;
362     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
363                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
364   }
365
366   if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
367   {
368     // We need a new Texture.
369     textureId = GenerateUniqueTextureId();
370     bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
371     mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
372                                                   desiredSize, contentScale, fittingMode, samplingMode,
373                                                   false, cropToMask, useAtlas, textureHash, orientationCorrection,
374                                                   preMultiply ) );
375     cacheIndex = mTextureInfoContainer.size() - 1u;
376
377     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
378                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
379   }
380
381   // The below code path is common whether we are using the cache or not.
382   // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
383   // or a new TextureInfo just created.
384   TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
385   textureInfo.maskTextureId = maskTextureId;
386   textureInfo.storageType = storageType;
387   textureInfo.orientationCorrection = orientationCorrection;
388
389   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
390                  textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
391                  textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
392                  textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
393                  textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
394
395   // Force reloading of texture by setting loadState unless already loading or cancelled.
396   if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
397        TextureManager::CANCELLED != textureInfo.loadState )
398   {
399     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
400                    url.GetUrl().c_str(), observer, cacheIndex, textureId );
401     textureInfo.loadState = TextureManager::NOT_STARTED;
402   }
403
404   // Check if we should add the observer.
405   // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
406   switch( textureInfo.loadState )
407   {
408     case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
409     case TextureManager::NOT_STARTED:
410     {
411       LoadTexture( textureInfo );
412       ObserveTexture( textureInfo, observer );
413       break;
414     }
415     case TextureManager::LOADING:
416     {
417       ObserveTexture( textureInfo, observer );
418       break;
419     }
420     case TextureManager::UPLOADED:
421     {
422       if( observer )
423       {
424         // The Texture has already loaded. The other observers have already been notified.
425         // We need to send a "late" loaded notification for this observer.
426         observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
427                                   textureInfo.useAtlas, textureInfo.atlasRect,
428                                   textureInfo.preMultiplied );
429       }
430       break;
431     }
432     case TextureManager::CANCELLED:
433     {
434       // A cancelled texture hasn't finished loading yet. Treat as a loading texture
435       // (it's ref count has already been incremented, above)
436       textureInfo.loadState = TextureManager::LOADING;
437       ObserveTexture( textureInfo, observer );
438       break;
439     }
440     case TextureManager::LOAD_FINISHED:
441     case TextureManager::WAITING_FOR_MASK:
442       // Loading has already completed. Do nothing.
443       break;
444   }
445
446   // Return the TextureId for which this Texture can now be referenced by externally.
447   return textureId;
448 }
449
450 void TextureManager::Remove( const TextureManager::TextureId textureId )
451 {
452   int textureInfoIndex = GetCacheIndexFromId( textureId );
453   if( textureInfoIndex != INVALID_INDEX )
454   {
455     TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
456
457     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
458                    textureId, textureInfoIndex,
459                    textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
460                    textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
461                    textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
462                    textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
463
464     // Decrement the reference count and check if this is the last user of this Texture.
465     if( --textureInfo.referenceCount <= 0 )
466     {
467       // This is the last remove for this Texture.
468       textureInfo.referenceCount = 0;
469       bool removeTextureInfo = false;
470
471       // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
472       if( textureInfo.loadState == UPLOADED )
473       {
474         if( textureInfo.atlas )
475         {
476           textureInfo.atlas.Remove( textureInfo.atlasRect );
477         }
478         removeTextureInfo = true;
479       }
480       else if( textureInfo.loadState == LOADING )
481       {
482         // We mark the textureInfo for removal.
483         // Once the load has completed, this method will be called again.
484         textureInfo.loadState = CANCELLED;
485       }
486       else
487       {
488         // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
489         removeTextureInfo = true;
490       }
491
492       // If the state allows us to remove the TextureInfo data, we do so.
493       if( removeTextureInfo )
494       {
495         // Permanently remove the textureInfo struct.
496         mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
497       }
498     }
499   }
500 }
501
502 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
503 {
504   VisualUrl visualUrl("");
505   int cacheIndex = GetCacheIndexFromId( textureId );
506
507   if( cacheIndex != INVALID_CACHE_INDEX )
508   {
509     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
510                    cacheIndex, textureId );
511
512     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
513     visualUrl = cachedTextureInfo.url;
514   }
515   return visualUrl;
516 }
517
518 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
519 {
520   LoadState loadState = TextureManager::NOT_STARTED;
521
522   int cacheIndex = GetCacheIndexFromId( textureId );
523   if( cacheIndex != INVALID_CACHE_INDEX )
524   {
525     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
526     loadState = cachedTextureInfo.loadState;
527   }
528   else
529   {
530     for( auto&& elem : mExternalTextures )
531     {
532       if( elem.textureId == textureId )
533       {
534         loadState = LoadState::UPLOADED;
535         break;
536       }
537     }
538   }
539   return loadState;
540 }
541
542 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
543 {
544   LoadState loadState = TextureManager::NOT_STARTED;
545
546   int cacheIndex = GetCacheIndexFromId( textureId );
547   if( cacheIndex != INVALID_CACHE_INDEX )
548   {
549     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
550     loadState = cachedTextureInfo.loadState;
551   }
552
553   return loadState;
554 }
555
556 TextureSet TextureManager::GetTextureSet( TextureId textureId )
557 {
558   TextureSet textureSet;// empty handle
559
560   int cacheIndex = GetCacheIndexFromId( textureId );
561   if( cacheIndex != INVALID_CACHE_INDEX )
562   {
563     TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
564     textureSet = cachedTextureInfo.textureSet;
565   }
566   else
567   {
568     for( auto&& elem : mExternalTextures )
569     {
570       if( elem.textureId == textureId )
571       {
572         textureSet = elem.textureSet;
573         break;
574       }
575     }
576   }
577   return textureSet;
578 }
579
580 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
581 {
582   TextureManager::ExternalTextureInfo info;
583   info.textureId = GenerateUniqueTextureId();
584   info.textureSet = textureSet;
585   mExternalTextures.emplace_back( info );
586   return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
587 }
588
589 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
590 {
591   if( url.size() > 0u )
592   {
593     // get the location from the Url
594     VisualUrl parseUrl( url );
595     if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
596     {
597       std::string location = parseUrl.GetLocation();
598       if( location.size() > 0u )
599       {
600         TextureId id = std::stoi( location );
601         const auto end = mExternalTextures.end();
602         for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
603         {
604           if( iter->textureId == id )
605           {
606             auto textureSet = iter->textureSet;
607             mExternalTextures.erase( iter );
608             return textureSet;
609           }
610         }
611       }
612     }
613   }
614   return TextureSet();
615 }
616
617
618 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
619 {
620   // make sure an observer doesn't observe the same object twice
621   // otherwise it will get multiple calls to ObjectDestroyed()
622   DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
623   mLifecycleObservers.PushBack( &observer );
624 }
625
626 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
627 {
628   // Find the observer...
629   auto endIter =  mLifecycleObservers.End();
630   for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
631   {
632     if( (*iter) == &observer)
633     {
634       mLifecycleObservers.Erase( iter );
635       break;
636     }
637   }
638   DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
639 }
640
641
642 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
643 {
644   bool success = true;
645
646   if( textureInfo.loadState == NOT_STARTED )
647   {
648     textureInfo.loadState = LOADING;
649
650     if( !textureInfo.loadSynchronously )
651     {
652       auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
653       auto loadingHelperIt = loadersContainer.GetNext();
654       DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
655       loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
656                             textureInfo.desiredSize, textureInfo.fittingMode,
657                             textureInfo.samplingMode, textureInfo.orientationCorrection );
658     }
659   }
660
661   return success;
662 }
663
664 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
665                                      TextureUploadObserver* observer )
666 {
667   if( observer )
668   {
669     textureInfo.observerList.PushBack( observer );
670     observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
671   }
672 }
673
674 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
675                                         Devel::PixelBuffer pixelBuffer )
676 {
677   DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
678
679   if( loadingContainer.size() >= 1u )
680   {
681     AsyncLoadingInfo loadingInfo = loadingContainer.front();
682
683     if( loadingInfo.loadId == id )
684     {
685       int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
686       if( cacheIndex != INVALID_CACHE_INDEX )
687       {
688         TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
689
690         DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "  CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
691
692         if( textureInfo.loadState != CANCELLED )
693         {
694           // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
695           PostLoad( textureInfo, pixelBuffer );
696         }
697         else
698         {
699           Remove( textureInfo.textureId );
700         }
701       }
702     }
703
704     loadingContainer.pop_front();
705   }
706 }
707
708 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
709 {
710   // Was the load successful?
711   if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
712   {
713     // No atlas support for now
714     textureInfo.useAtlas = NO_ATLAS;
715
716     if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
717     {
718       // If there is a mask texture ID associated with this texture, then apply the mask
719       // if it's already loaded. If it hasn't, and the mask is still loading,
720       // wait for the mask to finish loading.
721       if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
722       {
723         LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
724         if( maskLoadState == LOADING )
725         {
726           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
727           textureInfo.loadState = WAITING_FOR_MASK;
728         }
729         else if( maskLoadState == LOAD_FINISHED )
730         {
731           ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
732           UploadTexture( pixelBuffer, textureInfo );
733           NotifyObservers( textureInfo, true );
734         }
735       }
736       else
737       {
738         UploadTexture( pixelBuffer, textureInfo );
739         NotifyObservers( textureInfo, true );
740       }
741     }
742     else
743     {
744       textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
745       textureInfo.loadState = LOAD_FINISHED;
746
747       // Check if there was another texture waiting for this load to complete
748       // (e.g. if this was an image mask, and its load is on a different thread)
749       CheckForWaitingTexture( textureInfo );
750     }
751   }
752   else
753   {
754     DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
755     // @todo If the load was unsuccessful, upload the broken image.
756     textureInfo.loadState = LOAD_FAILED;
757     CheckForWaitingTexture( textureInfo );
758     NotifyObservers( textureInfo, false );
759   }
760 }
761
762 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
763 {
764   // Search the cache, checking if any texture has this texture id as a
765   // maskTextureId:
766   const unsigned int size = mTextureInfoContainer.size();
767
768   for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
769   {
770     if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
771         mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
772     {
773       TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
774       Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
775       textureInfo.pixelBuffer.Reset();
776
777       if( maskTextureInfo.loadState == LOAD_FINISHED )
778       {
779         ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
780         UploadTexture( pixelBuffer, textureInfo );
781         NotifyObservers( textureInfo, true );
782       }
783       else
784       {
785         DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
786         textureInfo.loadState = LOAD_FAILED;
787         NotifyObservers( textureInfo, false );
788       }
789     }
790   }
791 }
792
793 void TextureManager::ApplyMask(
794   Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
795   float contentScale, bool cropToMask )
796 {
797   int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
798   if( maskCacheIndex != INVALID_CACHE_INDEX )
799   {
800     Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
801     pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
802   }
803 }
804
805
806 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
807 {
808   if( textureInfo.useAtlas != USE_ATLAS )
809   {
810     DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "  TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
811
812     // If the texture doesn't have an alpha channel, can't pre-multiply it.
813     // Ensure that we don't change the load parameter (it's used for hashing), and instead set
814     // the status for use in the observer.
815     auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
816       TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
817     PreMultiply( pixelBuffer, preMultiply );
818     textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
819
820     Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
821                                     pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
822
823     PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
824     texture.Upload( pixelData );
825     if ( ! textureInfo.textureSet )
826     {
827       textureInfo.textureSet = TextureSet::New();
828     }
829     textureInfo.textureSet.SetTexture( 0u, texture );
830   }
831
832   // Update the load state.
833   // Note: This is regardless of success as we care about whether a
834   // load attempt is in progress or not.  If unsuccessful, a broken
835   // image is still loaded.
836   textureInfo.loadState = UPLOADED;
837 }
838
839 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
840 {
841   TextureId textureId = textureInfo.textureId;
842
843   // If there is an observer: Notify the load is complete, whether successful or not,
844   // and erase it from the list
845   unsigned int observerCount = textureInfo.observerList.Count();
846   TextureInfo* info = &textureInfo;
847
848   while( observerCount )
849   {
850     TextureUploadObserver* observer = info->observerList[0];
851
852     // During UploadComplete() a Control ResourceReady() signal is emitted.
853     // During that signal the app may add remove /add Textures (e.g. via
854     // ImageViews).  At this point no more observers can be added to the
855     // observerList, because textureInfo.loadState = UPLOADED. However it is
856     // possible for observers to be removed, hence we check the observer list
857     // count every iteration.
858
859     // The reference to the textureInfo struct can also become invalidated,
860     // because new load requests can modify the mTextureInfoContainer list
861     // (e.g. if more requests are pushed back it can cause the list to be
862     // resized invalidating the reference to the TextureInfo ).
863     observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
864                               info->preMultiplied );
865     observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
866
867     // Get the textureInfo from the container again as it may have been
868     // invalidated,
869
870     int textureInfoIndex = GetCacheIndexFromId( textureId );
871     if( textureInfoIndex == INVALID_CACHE_INDEX)
872     {
873       return; // texture has been removed - can stop.
874     }
875
876     info = &mTextureInfoContainer[ textureInfoIndex ];
877     observerCount = info->observerList.Count();
878     if ( observerCount > 0 )
879     {
880       // remove the observer that was just triggered if it's still in the list
881       for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
882       {
883         if( *j == observer )
884         {
885           info->observerList.Erase( j );
886           observerCount--;
887           break;
888         }
889       }
890     }
891   }
892 }
893
894 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
895 {
896   return mCurrentTextureId++;
897 }
898
899 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
900 {
901   const unsigned int size = mTextureInfoContainer.size();
902
903   for( unsigned int i = 0; i < size; ++i )
904   {
905     if( mTextureInfoContainer[i].textureId == textureId )
906     {
907       return i;
908     }
909   }
910
911   return INVALID_CACHE_INDEX;
912 }
913
914 TextureManager::TextureHash TextureManager::GenerateHash(
915   const std::string&             url,
916   const ImageDimensions          size,
917   const FittingMode::Type        fittingMode,
918   const Dali::SamplingMode::Type samplingMode,
919   const UseAtlas                 useAtlas,
920   TextureId                      maskTextureId,
921   TextureManager::MultiplyOnLoad preMultiplyOnLoad)
922 {
923   std::string hashTarget( url );
924   const size_t urlLength = hashTarget.length();
925   const uint16_t width = size.GetWidth();
926   const uint16_t height = size.GetWidth();
927
928   // If either the width or height has been specified, include the resizing options in the hash
929   if( width != 0 || height != 0 )
930   {
931     // We are appending 5 bytes to the URL to form the hash input.
932     hashTarget.resize( urlLength + 5u );
933     char* hashTargetPtr = &( hashTarget[ urlLength ] );
934
935     // Pack the width and height (4 bytes total).
936     *hashTargetPtr++ = size.GetWidth() & 0xff;
937     *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
938     *hashTargetPtr++ = size.GetHeight() & 0xff;
939     *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
940
941     // Bit-pack the FittingMode, SamplingMode and atlasing.
942     // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
943     *hashTargetPtr   = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
944   }
945   else
946   {
947     // We are not including sizing information, but we still need an extra byte for atlasing.
948     hashTarget.resize( urlLength + 1u );
949
950     // Add the atlasing to the hash input.
951     switch( useAtlas )
952     {
953       case UseAtlas::NO_ATLAS:
954       {
955         hashTarget[ urlLength ] = 'f';
956         break;
957       }
958       case UseAtlas::USE_ATLAS:
959       {
960         hashTarget[ urlLength ] = 't';
961         break;
962       }
963     }
964   }
965
966   if( maskTextureId != INVALID_TEXTURE_ID )
967   {
968     auto textureIdIndex = hashTarget.length();
969     hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
970     unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
971
972     // Append the texture id to the end of the URL byte by byte:
973     // (to avoid SIGBUS / alignment issues)
974     for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
975     {
976       *hashTargetPtr++ = maskTextureId & 0xff;
977       maskTextureId >>= 8u;
978     }
979   }
980
981   auto premultipliedIndex = hashTarget.length();
982   hashTarget.resize( premultipliedIndex + 1 );
983   switch( preMultiplyOnLoad )
984   {
985     case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
986     {
987       hashTarget[ premultipliedIndex ] = 't';
988       break;
989     }
990     case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
991     {
992       hashTarget[ premultipliedIndex ] = 'f';
993       break;
994     }
995   }
996
997   return Dali::CalculateHash( hashTarget );
998 }
999
1000 int TextureManager::FindCachedTexture(
1001   const TextureManager::TextureHash hash,
1002   const std::string&                url,
1003   const ImageDimensions             size,
1004   const FittingMode::Type           fittingMode,
1005   const Dali::SamplingMode::Type    samplingMode,
1006   const bool                        useAtlas,
1007   TextureId                         maskTextureId,
1008   TextureManager::MultiplyOnLoad    preMultiplyOnLoad )
1009 {
1010   // Default to an invalid ID, in case we do not find a match.
1011   int cacheIndex = INVALID_CACHE_INDEX;
1012
1013   // Iterate through our hashes to find a match.
1014   const unsigned int count = mTextureInfoContainer.size();
1015   for( unsigned int i = 0u; i < count; ++i )
1016   {
1017     if( mTextureInfoContainer[i].hash == hash )
1018     {
1019       // We have a match, now we check all the original parameters in case of a hash collision.
1020       TextureInfo& textureInfo( mTextureInfoContainer[i] );
1021       auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
1022         TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
1023
1024       if( ( url == textureInfo.url.GetUrl() ) &&
1025           ( useAtlas == textureInfo.useAtlas ) &&
1026           ( maskTextureId == textureInfo.maskTextureId ) &&
1027           ( size == textureInfo.desiredSize ) &&
1028           ( preMultiplyOnLoad ==  multiplyOnLoad ) &&
1029           ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
1030             ( fittingMode == textureInfo.fittingMode &&
1031               samplingMode == textureInfo.samplingMode ) ) )
1032       {
1033         // The found Texture is a match.
1034         cacheIndex = i;
1035         break;
1036       }
1037     }
1038   }
1039
1040   return cacheIndex;
1041 }
1042
1043 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1044 {
1045   const unsigned int count = mTextureInfoContainer.size();
1046   for( unsigned int i = 0; i < count; ++i )
1047   {
1048     TextureInfo& textureInfo( mTextureInfoContainer[i] );
1049     for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1050          j != textureInfo.observerList.End(); )
1051     {
1052       if( *j == observer )
1053       {
1054         j = textureInfo.observerList.Erase( j );
1055       }
1056       else
1057       {
1058         ++j;
1059       }
1060     }
1061   }
1062 }
1063
1064
1065 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1066 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1067                      AsyncLoadingInfoContainerType())
1068 {
1069 }
1070
1071 void TextureManager::AsyncLoadingHelper::Load(TextureId          textureId,
1072                                               const VisualUrl&   url,
1073                                               ImageDimensions    desiredSize,
1074                                               FittingMode::Type  fittingMode,
1075                                               SamplingMode::Type samplingMode,
1076                                               bool               orientationCorrection)
1077 {
1078   mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1079   auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
1080   mLoadingInfoContainer.back().loadId = id;
1081 }
1082
1083 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1084 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1085 {
1086 }
1087
1088 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1089     Toolkit::AsyncImageLoader loader,
1090     TextureManager& textureManager,
1091     AsyncLoadingInfoContainerType&& loadingInfoContainer)
1092 : mLoader(loader),
1093   mTextureManager(textureManager),
1094   mLoadingInfoContainer(std::move(loadingInfoContainer))
1095 {
1096   DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1097       this, &AsyncLoadingHelper::AsyncLoadComplete);
1098 }
1099
1100 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t           id,
1101                                                            Devel::PixelBuffer pixelBuffer)
1102 {
1103   mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1104 }
1105
1106 void TextureManager::SetBrokenImageUrl(const std::string& brokenImageUrl)
1107 {
1108   mBrokenImageUrl = brokenImageUrl;
1109 }
1110
1111 } // namespace Internal
1112
1113 } // namespace Toolkit
1114
1115 } // namespace Dali