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