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