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