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