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