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