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