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