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