cac3b4711bf4af87dd4ab3eb1fe8fa759512ba5b
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / texture-manager / texture-manager-impl.cpp
1 /*
2  * Copyright (c) 2022 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 "texture-manager-impl.h"
20
21 // EXTERNAL HEADERS
22 #include <dali/devel-api/adaptor-framework/environment-variable.h>
23 #include <dali/devel-api/adaptor-framework/image-loading.h>
24 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/public-api/rendering/geometry.h>
27
28 // INTERNAL HEADERS
29 #include <dali-toolkit/internal/texture-manager/texture-async-loading-helper.h>
30 #include <dali-toolkit/internal/texture-manager/texture-cache-manager.h>
31 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
32 #include <dali-toolkit/internal/visuals/rendering-addon.h>
33
34 namespace
35 {
36 constexpr auto INITIAL_HASH_NUMBER                     = size_t{0u};
37 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS  = size_t{4u};
38 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
39
40 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV  = "DALI_TEXTURE_LOCAL_THREADS";
41 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
42
43 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
44 {
45   using Dali::EnvironmentVariable::GetEnvironmentVariable;
46   auto           numberString          = GetEnvironmentVariable(environmentVariable);
47   auto           numberOfThreads       = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
48   constexpr auto MAX_NUMBER_OF_THREADS = 100u;
49   DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS);
50   return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
51 }
52
53 size_t GetNumberOfLocalLoaderThreads()
54 {
55   return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
56 }
57
58 size_t GetNumberOfRemoteLoaderThreads()
59 {
60   return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
61 }
62
63 } // namespace
64
65 namespace Dali
66 {
67 namespace Toolkit
68 {
69 namespace Internal
70 {
71 #ifdef DEBUG_ENABLED
72 // Define logfilter Internal namespace level so other files (e.g. texture-cache-manager.cpp) can also use this filter.
73 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXTURE_MANAGER");
74
75 // clang-format off
76 #define GET_LOAD_STATE_STRING(loadState) \
77   loadState == TextureManagerType::LoadState::NOT_STARTED      ? "NOT_STARTED"      : \
78   loadState == TextureManagerType::LoadState::LOADING          ? "LOADING"          : \
79   loadState == TextureManagerType::LoadState::LOAD_FINISHED    ? "LOAD_FINISHED"    : \
80   loadState == TextureManagerType::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" : \
81   loadState == TextureManagerType::LoadState::MASK_APPLYING    ? "MASK_APPLYING"    : \
82   loadState == TextureManagerType::LoadState::MASK_APPLIED     ? "MASK_APPLIED"     : \
83   loadState == TextureManagerType::LoadState::UPLOADED         ? "UPLOADED"         : \
84   loadState == TextureManagerType::LoadState::CANCELLED        ? "CANCELLED"        : \
85   loadState == TextureManagerType::LoadState::LOAD_FAILED      ? "LOAD_FAILED"      : \
86                                                                  "Unknown"
87 // clang-format on
88 #endif
89
90 namespace
91 {
92 const uint32_t DEFAULT_ATLAS_SIZE(1024u);               ///< This size can fit 8 by 8 images of average size 128 * 128
93 const Vector4  FULL_ATLAS_RECT(0.0f, 0.0f, 1.0f, 1.0f); ///< UV Rectangle that covers the full Texture
94
95 void PreMultiply(Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
96 {
97   if(Pixel::HasAlpha(pixelBuffer.GetPixelFormat()))
98   {
99     if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
100     {
101       pixelBuffer.MultiplyColorByAlpha();
102     }
103   }
104   else
105   {
106     preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
107   }
108 }
109
110 } // Anonymous namespace
111
112 TextureManager::MaskingData::MaskingData()
113 : mAlphaMaskUrl(),
114   mAlphaMaskId(INVALID_TEXTURE_ID),
115   mContentScaleFactor(1.0f),
116   mCropToMask(true),
117   mPreappliedMasking(true),
118   mMaskImageLoadingFailed(false)
119 {
120 }
121
122 TextureManager::TextureManager()
123 : mTextureCacheManager(),
124   mAsyncLocalLoaders(GetNumberOfLocalLoaderThreads(), [&]()
125                      { return TextureAsyncLoadingHelper(*this); }),
126   mAsyncRemoteLoaders(GetNumberOfRemoteLoaderThreads(), [&]()
127                       { return TextureAsyncLoadingHelper(*this); }),
128   mLifecycleObservers(),
129   mLoadQueue(),
130   mRemoveQueue(),
131   mQueueLoadFlag(false)
132 {
133   // Initialize the AddOn
134   RenderingAddOn::Get();
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::LoadAnimatedImageTexture(
146   const VisualUrl&                url,
147   Dali::AnimatedImageLoading      animatedImageLoading,
148   const uint32_t&                 frameIndex,
149   TextureManager::TextureId&      textureId,
150   MaskingDataPointer&             maskInfo,
151   const Dali::SamplingMode::Type& samplingMode,
152   const Dali::WrapMode::Type&     wrapModeU,
153   const Dali::WrapMode::Type&     wrapModeV,
154   const bool&                     synchronousLoading,
155   TextureUploadObserver*          textureObserver,
156   TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
157 {
158   TextureSet textureSet;
159
160   if(synchronousLoading)
161   {
162     Devel::PixelBuffer pixelBuffer;
163     if(animatedImageLoading)
164     {
165       pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
166     }
167     if(!pixelBuffer)
168     {
169       DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
170     }
171     else
172     {
173       Texture maskTexture;
174       if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
175       {
176         Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
177         if(maskPixelBuffer)
178         {
179           if(!maskInfo->mPreappliedMasking)
180           {
181             PixelData maskPixelData = Devel::PixelBuffer::Convert(maskPixelBuffer); // takes ownership of buffer
182             maskTexture             = Texture::New(Dali::TextureType::TEXTURE_2D, maskPixelData.GetPixelFormat(), maskPixelData.GetWidth(), maskPixelData.GetHeight());
183             maskTexture.Upload(maskPixelData);
184           }
185           else
186           {
187             pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
188           }
189         }
190         else
191         {
192           DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous mask image loading is failed\n");
193         }
194       }
195
196       if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
197       {
198         PreMultiply(pixelBuffer, preMultiplyOnLoad);
199       }
200
201       PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
202       if(!textureSet)
203       {
204         Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
205         texture.Upload(pixelData);
206         textureSet = TextureSet::New();
207         textureSet.SetTexture(0u, texture);
208         if(maskTexture)
209         {
210           textureSet.SetTexture(1u, maskTexture);
211         }
212       }
213     }
214   }
215   else
216   {
217     TextureId alphaMaskId        = INVALID_TEXTURE_ID;
218     float     contentScaleFactor = 1.0f;
219     bool      cropToMask         = false;
220     if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
221     {
222       maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl, maskInfo->mPreappliedMasking ? StorageType::KEEP_PIXEL_BUFFER : StorageType::KEEP_TEXTURE);
223       alphaMaskId            = maskInfo->mAlphaMaskId;
224       if(maskInfo->mPreappliedMasking)
225       {
226         contentScaleFactor = maskInfo->mContentScaleFactor;
227         cropToMask         = maskInfo->mCropToMask;
228       }
229     }
230
231     textureId = RequestLoadInternal(url, alphaMaskId, contentScaleFactor, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, UseAtlas::NO_ATLAS, cropToMask, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiplyOnLoad, animatedImageLoading, frameIndex, false);
232
233     TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
234     if(loadState == TextureManager::LoadState::UPLOADED)
235     {
236       // LoadComplete has already been called - keep the same texture set
237       textureSet = GetTextureSet(textureId);
238     }
239   }
240
241   if(textureSet)
242   {
243     Sampler sampler = Sampler::New();
244     sampler.SetWrapMode(wrapModeU, wrapModeV);
245     textureSet.SetSampler(0u, sampler);
246   }
247
248   return textureSet;
249 }
250
251 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
252   const VisualUrl&                url,
253   const Dali::ImageDimensions&    desiredSize,
254   const Dali::FittingMode::Type&  fittingMode,
255   const Dali::SamplingMode::Type& samplingMode,
256   const bool&                     synchronousLoading,
257   TextureUploadObserver*          textureObserver,
258   const bool&                     orientationCorrection,
259   TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
260 {
261   Devel::PixelBuffer pixelBuffer;
262   if(synchronousLoading)
263   {
264     if(url.IsValid())
265     {
266       if(url.IsBufferResource())
267       {
268         const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
269         if(encodedImageBuffer)
270         {
271           pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
272         }
273       }
274       else
275       {
276         pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
277       }
278       if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
279       {
280         PreMultiply(pixelBuffer, preMultiplyOnLoad);
281       }
282     }
283   }
284   else
285   {
286     RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, UseAtlas::NO_ATLAS, false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, false);
287   }
288
289   return pixelBuffer;
290 }
291
292 TextureSet TextureManager::LoadTexture(
293   const VisualUrl&                    url,
294   const Dali::ImageDimensions&        desiredSize,
295   const Dali::FittingMode::Type&      fittingMode,
296   const Dali::SamplingMode::Type&     samplingMode,
297   MaskingDataPointer&                 maskInfo,
298   const bool&                         synchronousLoading,
299   TextureManager::TextureId&          textureId,
300   Vector4&                            textureRect,
301   Dali::ImageDimensions&              textureRectSize,
302   bool&                               atlasingStatus,
303   bool&                               loadingStatus,
304   const Dali::WrapMode::Type&         wrapModeU,
305   const Dali::WrapMode::Type&         wrapModeV,
306   TextureUploadObserver*              textureObserver,
307   AtlasUploadObserver*                atlasObserver,
308   ImageAtlasManagerPtr                imageAtlasManager,
309   const bool&                         orientationCorrection,
310   const TextureManager::ReloadPolicy& reloadPolicy,
311   TextureManager::MultiplyOnLoad&     preMultiplyOnLoad)
312 {
313   TextureSet textureSet;
314
315   loadingStatus = false;
316   textureRect   = FULL_ATLAS_RECT;
317
318   if(VisualUrl::TEXTURE == url.GetProtocolType())
319   {
320     std::string location = url.GetLocation();
321     if(location.size() > 0u)
322     {
323       TextureId id = std::stoi(location);
324       textureSet   = mTextureCacheManager.GetExternalTextureSet(id);
325       if(textureSet)
326       {
327         preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
328         textureId         = id;
329         return textureSet;
330       }
331     }
332   }
333   else
334   {
335     // For Atlas
336     if(synchronousLoading && atlasingStatus)
337     {
338       const bool synchronousAtlasAvaliable = (desiredSize != ImageDimensions() || url.IsLocalResource()) ? imageAtlasManager->CheckAtlasAvailable(url, desiredSize)
339                                                                                                          : false;
340       if(synchronousAtlasAvaliable)
341       {
342         Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
343
344         if(pixelBuffer && maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
345         {
346           Devel::PixelBuffer maskPixelBuffer = LoadImageSynchronously(maskInfo->mAlphaMaskUrl, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
347           if(maskPixelBuffer)
348           {
349             pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
350           }
351         }
352
353         PixelData data;
354         if(pixelBuffer)
355         {
356           PreMultiply(pixelBuffer, preMultiplyOnLoad);
357           data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
358
359           if(data)
360           {
361             textureSet = imageAtlasManager->Add(textureRect, data);
362             if(textureSet)
363             {
364               textureRectSize.SetWidth(data.GetWidth());
365               textureRectSize.SetHeight(data.GetHeight());
366             }
367           }
368           else
369           {
370             DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous Texture loading with atlasing is failed.\n");
371           }
372         }
373         if(!textureSet)
374         {
375           atlasingStatus = false;
376         }
377       }
378     }
379
380     if(!textureSet)
381     {
382       loadingStatus = true;
383       // Atlas manager can chage desired size when it is set by 0,0.
384       // We should store into textureRectSize only if atlasing successed.
385       // So copy inputed desiredSize, and replace value into textureRectSize only if atlasing success.
386       Dali::ImageDimensions atlasDesiredSize = desiredSize;
387       if(atlasingStatus)
388       {
389         if(url.IsBufferResource())
390         {
391           const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(url.GetUrl());
392           if(encodedImageBuffer)
393           {
394             textureSet = imageAtlasManager->Add(textureRect, encodedImageBuffer, desiredSize, fittingMode, true, atlasObserver);
395           }
396         }
397         else
398         {
399           textureSet = imageAtlasManager->Add(textureRect, url, atlasDesiredSize, fittingMode, true, atlasObserver);
400         }
401       }
402       if(!textureSet) // big image, no atlasing or atlasing failed
403       {
404         atlasingStatus = false;
405         if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
406         {
407           textureId = RequestLoad(
408             url,
409             desiredSize,
410             fittingMode,
411             samplingMode,
412             UseAtlas::NO_ATLAS,
413             textureObserver,
414             orientationCorrection,
415             reloadPolicy,
416             preMultiplyOnLoad,
417             synchronousLoading);
418         }
419         else
420         {
421           maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl, maskInfo->mPreappliedMasking ? StorageType::KEEP_PIXEL_BUFFER : StorageType::KEEP_TEXTURE, synchronousLoading);
422           textureId              = RequestLoad(
423             url,
424             maskInfo->mAlphaMaskId,
425             maskInfo->mContentScaleFactor,
426             desiredSize,
427             fittingMode,
428             samplingMode,
429             UseAtlas::NO_ATLAS,
430             maskInfo->mCropToMask,
431             textureObserver,
432             orientationCorrection,
433             reloadPolicy,
434             preMultiplyOnLoad,
435             synchronousLoading);
436         }
437
438         TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
439         if(loadState == TextureManager::LoadState::UPLOADED)
440         {
441           // LoadComplete has already been called - keep the same texture set
442           textureSet = mTextureCacheManager.GetTextureSet(textureId);
443         }
444
445         // If we are loading the texture, or waiting for the ready signal handler to complete, inform
446         // caller that they need to wait.
447         loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
448                          loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
449                          loadState == TextureManager::LoadState::MASK_APPLYING ||
450                          loadState == TextureManager::LoadState::MASK_APPLIED ||
451                          loadState == TextureManager::LoadState::NOT_STARTED ||
452                          mQueueLoadFlag);
453       }
454       else
455       {
456         textureRectSize = atlasDesiredSize;
457       }
458     }
459   }
460
461   if(!atlasingStatus && textureSet)
462   {
463     Sampler sampler = Sampler::New();
464     sampler.SetWrapMode(wrapModeU, wrapModeV);
465     textureSet.SetSampler(0u, sampler);
466   }
467
468   if(synchronousLoading)
469   {
470     loadingStatus = false;
471   }
472
473   return textureSet;
474 }
475
476 TextureManager::TextureId TextureManager::RequestLoad(
477   const VisualUrl&                    url,
478   const ImageDimensions&              desiredSize,
479   const Dali::FittingMode::Type&      fittingMode,
480   const Dali::SamplingMode::Type&     samplingMode,
481   const UseAtlas&                     useAtlas,
482   TextureUploadObserver*              observer,
483   const bool&                         orientationCorrection,
484   const TextureManager::ReloadPolicy& reloadPolicy,
485   TextureManager::MultiplyOnLoad&     preMultiplyOnLoad,
486   const bool&                         synchronousLoading)
487 {
488   return RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas, false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading);
489 }
490
491 TextureManager::TextureId TextureManager::RequestLoad(
492   const VisualUrl&                    url,
493   const TextureManager::TextureId&    maskTextureId,
494   const float&                        contentScale,
495   const Dali::ImageDimensions&        desiredSize,
496   const Dali::FittingMode::Type&      fittingMode,
497   const Dali::SamplingMode::Type&     samplingMode,
498   const TextureManager::UseAtlas&     useAtlas,
499   const bool&                         cropToMask,
500   TextureUploadObserver*              observer,
501   const bool&                         orientationCorrection,
502   const TextureManager::ReloadPolicy& reloadPolicy,
503   TextureManager::MultiplyOnLoad&     preMultiplyOnLoad,
504   const bool&                         synchronousLoading)
505 {
506   return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading);
507 }
508
509 TextureManager::TextureId TextureManager::RequestMaskLoad(
510   const VisualUrl& maskUrl,
511   StorageType      storageType,
512   const bool&      synchronousLoading)
513 {
514   // Use the normal load procedure to get the alpha mask.
515   auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
516   return RequestLoadInternal(maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, UseAtlas::NO_ATLAS, false, storageType, NULL, true, TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u, synchronousLoading);
517 }
518
519 TextureManager::TextureId TextureManager::RequestLoadInternal(
520   const VisualUrl&                    url,
521   const TextureManager::TextureId&    maskTextureId,
522   const float&                        contentScale,
523   const Dali::ImageDimensions&        desiredSize,
524   const Dali::FittingMode::Type&      fittingMode,
525   const Dali::SamplingMode::Type&     samplingMode,
526   const TextureManager::UseAtlas&     useAtlas,
527   const bool&                         cropToMask,
528   const TextureManager::StorageType&  storageType,
529   TextureUploadObserver*              observer,
530   const bool&                         orientationCorrection,
531   const TextureManager::ReloadPolicy& reloadPolicy,
532   TextureManager::MultiplyOnLoad&     preMultiplyOnLoad,
533   Dali::AnimatedImageLoading          animatedImageLoading,
534   const std::uint32_t&                frameIndex,
535   const bool&                         synchronousLoading)
536 {
537   TextureHash       textureHash = INITIAL_HASH_NUMBER;
538   TextureCacheIndex cacheIndex  = INVALID_CACHE_INDEX;
539   if(storageType != StorageType::RETURN_PIXEL_BUFFER && frameIndex == 0)
540   {
541     textureHash = mTextureCacheManager.GenerateHash(url, desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, cropToMask, frameIndex);
542
543     // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
544     cacheIndex = mTextureCacheManager.FindCachedTexture(textureHash, url, desiredSize, fittingMode, samplingMode, useAtlas, storageType, maskTextureId, cropToMask, preMultiplyOnLoad, (animatedImageLoading) ? true : false, frameIndex);
545   }
546
547   TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
548   // Check if the requested Texture exists in the cache.
549   if(cacheIndex != INVALID_CACHE_INDEX)
550   {
551     if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
552     {
553       // Mark this texture being used by another client resource. Forced reload would replace the current texture
554       // without the need for incrementing the reference count.
555       ++(mTextureCacheManager[cacheIndex].referenceCount);
556     }
557     textureId = mTextureCacheManager[cacheIndex].textureId;
558
559     // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
560     preMultiplyOnLoad = mTextureCacheManager[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
561
562     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d, frameindex=%d, premultiplied=%d\n", url.GetUrl().c_str(), observer, cacheIndex.GetIndex(), textureId, frameIndex, mTextureCacheManager[cacheIndex].preMultiplied ? 1 : 0);
563   }
564
565   if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
566   {
567     textureId = mTextureCacheManager.GenerateTextureId();
568
569     bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
570
571     // Cache new texutre, and get cacheIndex.
572     cacheIndex = mTextureCacheManager.AppendCache(TextureInfo(textureId, maskTextureId, url, desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
573
574     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d, frameindex=%d\n", url.GetUrl().c_str(), observer, cacheIndex.GetIndex(), textureId, frameIndex);
575   }
576
577   // The below code path is common whether we are using the cache or not.
578   // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
579   // or a new TextureInfo just created.
580   TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
581   textureInfo.maskTextureId         = maskTextureId;
582   textureInfo.storageType           = storageType;
583   textureInfo.orientationCorrection = orientationCorrection;
584
585   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
586
587   // Force reloading of texture by setting loadState unless already loading or cancelled.
588   if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
589      TextureManager::LoadState::LOADING != textureInfo.loadState &&
590      TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
591      TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
592      TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
593      TextureManager::LoadState::CANCELLED != textureInfo.loadState)
594   {
595     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex.GetIndex(), textureId);
596
597     textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
598   }
599
600   if(!synchronousLoading)
601   {
602     // Check if we should add the observer.
603     // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
604     switch(textureInfo.loadState)
605     {
606       case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
607       case TextureManager::LoadState::NOT_STARTED:
608       {
609         LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
610         break;
611       }
612       case TextureManager::LoadState::LOADING:
613       case TextureManager::LoadState::WAITING_FOR_MASK:
614       case TextureManager::LoadState::MASK_APPLYING:
615       case TextureManager::LoadState::MASK_APPLIED:
616       {
617         ObserveTexture(textureInfo, observer);
618         break;
619       }
620       case TextureManager::LoadState::UPLOADED:
621       {
622         if(observer)
623         {
624           LoadOrQueueTexture(textureInfo, observer);
625         }
626         break;
627       }
628       case TextureManager::LoadState::CANCELLED:
629       {
630         // A cancelled texture hasn't finished loading yet. Treat as a loading texture
631         // (it's ref count has already been incremented, above)
632         textureInfo.loadState = TextureManager::LoadState::LOADING;
633         ObserveTexture(textureInfo, observer);
634         break;
635       }
636       case TextureManager::LoadState::LOAD_FINISHED:
637       {
638         // Loading has already completed.
639         if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
640         {
641           LoadOrQueueTexture(textureInfo, observer);
642         }
643         break;
644       }
645     }
646   }
647   else
648   {
649     // If the image is already finished to load, use cached texture.
650     // We don't need to consider Observer because this is synchronous loading.
651     if(!(textureInfo.loadState == TextureManager::LoadState::UPLOADED ||
652          textureInfo.loadState == TextureManager::LoadState::LOAD_FINISHED))
653     {
654       Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
655
656       if(!pixelBuffer)
657       {
658         // If pixelBuffer loading is failed in synchronously, call Remove() method.
659         Remove(textureId, nullptr);
660         return INVALID_TEXTURE_ID;
661       }
662
663       if(storageType == StorageType::KEEP_PIXEL_BUFFER) // For the mask image loading.
664       {
665         textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
666         textureInfo.loadState   = LoadState::LOAD_FINISHED;
667       }
668       else // For the image loading.
669       {
670         if(maskTextureId != INVALID_TEXTURE_ID)
671         {
672           TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
673           if(maskCacheIndex != INVALID_CACHE_INDEX)
674           {
675             Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
676             if(maskPixelBuffer)
677             {
678               pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask);
679             }
680             else
681             {
682               DALI_LOG_ERROR("Mask image cached invalid pixel buffer!\n");
683             }
684           }
685           else
686           {
687             DALI_LOG_ERROR("Mask image is not stored in cache.\n");
688           }
689         }
690         PreMultiply(pixelBuffer, preMultiplyOnLoad);
691
692         // Upload texture
693         UploadTexture(pixelBuffer, textureInfo);
694       }
695     }
696   }
697   return textureId;
698 }
699
700 void TextureManager::Remove(const TextureManager::TextureId& textureId, TextureUploadObserver* observer)
701 {
702   if(textureId != INVALID_TEXTURE_ID)
703   {
704     if(mQueueLoadFlag)
705     {
706       // Remove textureId after NotifyObserver finished
707       mRemoveQueue.PushBack(textureId);
708     }
709     else
710     {
711       // Remove textureId in CacheManager.
712       mTextureCacheManager.RemoveCache(textureId);
713     }
714
715     if(observer)
716     {
717       // Remove element from the LoadQueue
718       for(auto&& element : mLoadQueue)
719       {
720         if(element.mObserver == observer)
721         {
722           // Do not erase the item. We will clear it later in ProcessLoadQueue().
723           element.mObserver = nullptr;
724           break;
725         }
726       }
727     }
728   }
729 }
730
731 Devel::PixelBuffer TextureManager::LoadImageSynchronously(
732   const VisualUrl&                url,
733   const Dali::ImageDimensions&    desiredSize,
734   const Dali::FittingMode::Type&  fittingMode,
735   const Dali::SamplingMode::Type& samplingMode,
736   const bool&                     orientationCorrection)
737 {
738   Devel::PixelBuffer pixelBuffer;
739   if(url.IsBufferResource())
740   {
741     const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
742     if(encodedImageBuffer)
743     {
744       pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
745     }
746   }
747   else
748   {
749     pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
750   }
751   return pixelBuffer;
752 }
753
754 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
755 {
756   // make sure an observer doesn't observe the same object twice
757   // otherwise it will get multiple calls to ObjectDestroyed()
758   DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
759   mLifecycleObservers.PushBack(&observer);
760 }
761
762 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
763 {
764   // Find the observer...
765   auto endIter = mLifecycleObservers.End();
766   for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
767   {
768     if((*iter) == &observer)
769     {
770       mLifecycleObservers.Erase(iter);
771       break;
772     }
773   }
774   DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
775 }
776
777 void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
778 {
779   switch(textureInfo.loadState)
780   {
781     case LoadState::NOT_STARTED:
782     case LoadState::LOAD_FAILED:
783     {
784       if(mQueueLoadFlag)
785       {
786         QueueLoadTexture(textureInfo, observer);
787       }
788       else
789       {
790         LoadTexture(textureInfo, observer);
791       }
792       break;
793     }
794     case LoadState::UPLOADED:
795     {
796       if(mQueueLoadFlag)
797       {
798         QueueLoadTexture(textureInfo, observer);
799       }
800       else
801       {
802         // The Texture has already loaded. The other observers have already been notified.
803         // We need to send a "late" loaded notification for this observer.
804         EmitLoadComplete(observer, textureInfo, true);
805       }
806       break;
807     }
808     case LoadState::LOADING:
809     case LoadState::CANCELLED:
810     case LoadState::LOAD_FINISHED:
811     case LoadState::WAITING_FOR_MASK:
812     case LoadState::MASK_APPLYING:
813     case LoadState::MASK_APPLIED:
814     {
815       break;
816     }
817   }
818 }
819
820 void TextureManager::QueueLoadTexture(const TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
821 {
822   const auto& textureId = textureInfo.textureId;
823   mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
824
825   observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
826 }
827
828 void TextureManager::LoadTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
829 {
830   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
831
832   textureInfo.loadState = LoadState::LOADING;
833   if(!textureInfo.loadSynchronously)
834   {
835     auto& loadersContainer  = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
836     auto  loadingHelperIt   = loadersContainer.GetNext();
837     auto  premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
838     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
839     if(textureInfo.animatedImageLoading)
840     {
841       loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex, premultiplyOnLoad);
842     }
843     else
844     {
845       loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
846     }
847   }
848   ObserveTexture(textureInfo, observer);
849 }
850
851 void TextureManager::ProcessLoadQueue()
852 {
853   for(auto&& element : mLoadQueue)
854   {
855     if(!element.mObserver)
856     {
857       continue;
858     }
859
860     TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(element.mTextureId);
861     if(cacheIndex != INVALID_CACHE_INDEX)
862     {
863       TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
864       if((textureInfo.loadState == LoadState::UPLOADED) || (textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER))
865       {
866         EmitLoadComplete(element.mObserver, textureInfo, true);
867       }
868       else
869       {
870         LoadTexture(textureInfo, element.mObserver);
871       }
872     }
873   }
874   mLoadQueue.Clear();
875 }
876
877 void TextureManager::ProcessRemoveQueue()
878 {
879   for(const auto& textureId : mRemoveQueue)
880   {
881     mTextureCacheManager.RemoveCache(textureId);
882   }
883   mRemoveQueue.Clear();
884 }
885
886 void TextureManager::ObserveTexture(TextureManager::TextureInfo& textureInfo,
887                                     TextureUploadObserver*       observer)
888 {
889   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
890
891   if(observer)
892   {
893     textureInfo.observerList.PushBack(observer);
894     observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
895   }
896 }
897
898 void TextureManager::AsyncLoadComplete(const TextureManager::TextureId& textureId, Devel::PixelBuffer pixelBuffer)
899 {
900   TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
901   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( textureId:%d CacheIndex:%d )\n", textureId, cacheIndex.GetIndex());
902   if(cacheIndex != INVALID_CACHE_INDEX)
903   {
904     TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
905
906     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "  textureId:%d Url:%s CacheIndex:%d LoadState: %s\n", textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex.GetIndex(), GET_LOAD_STATE_STRING(textureInfo.loadState));
907
908     if(textureInfo.loadState != LoadState::CANCELLED)
909     {
910       // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
911       PostLoad(textureInfo, pixelBuffer);
912     }
913     else
914     {
915       Remove(textureInfo.textureId, nullptr);
916     }
917   }
918 }
919
920 void TextureManager::PostLoad(TextureManager::TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
921 {
922   // Was the load successful?
923   if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
924   {
925     // No atlas support for now
926     textureInfo.useAtlas      = UseAtlas::NO_ATLAS;
927     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
928
929     if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
930     {
931       // If there is a mask texture ID associated with this texture, then apply the mask
932       // if it's already loaded. If it hasn't, and the mask is still loading,
933       // wait for the mask to finish loading.
934       // note, If the texture is already uploaded synchronously during loading,
935       // we don't need to apply mask.
936       if(textureInfo.loadState != LoadState::UPLOADED &&
937          textureInfo.maskTextureId != INVALID_TEXTURE_ID)
938       {
939         if(textureInfo.loadState == LoadState::MASK_APPLYING)
940         {
941           textureInfo.loadState = LoadState::MASK_APPLIED;
942           UploadTexture(pixelBuffer, textureInfo);
943           NotifyObservers(textureInfo, true);
944         }
945         else
946         {
947           LoadState maskLoadState = mTextureCacheManager.GetTextureStateInternal(textureInfo.maskTextureId);
948           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
949           if(maskLoadState == LoadState::LOADING)
950           {
951             textureInfo.loadState = LoadState::WAITING_FOR_MASK;
952           }
953           else if(maskLoadState == LoadState::LOAD_FINISHED || maskLoadState == LoadState::UPLOADED)
954           {
955             // Send New Task to Thread
956             TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureInfo.maskTextureId);
957             if(maskCacheIndex != INVALID_CACHE_INDEX)
958             {
959               TextureInfo& maskTextureInfo(mTextureCacheManager[maskCacheIndex]);
960               if(maskTextureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER)
961               {
962                 // Send New Task to Thread
963                 ApplyMask(textureInfo, textureInfo.maskTextureId);
964               }
965               else if(maskTextureInfo.storageType == StorageType::KEEP_TEXTURE)
966               {
967                 // Upload image texture. textureInfo.loadState will be UPLOADED.
968                 UploadTexture(textureInfo.pixelBuffer, textureInfo);
969                 if(maskTextureInfo.textureSet.GetTextureCount() > 0u)
970                 {
971                   Texture maskTexture = maskTextureInfo.textureSet.GetTexture(0u);
972                   textureInfo.textureSet.SetTexture(1u, maskTexture);
973                 }
974                 // notify mask texture set.
975                 NotifyObservers(textureInfo, true);
976               }
977             }
978           }
979           else // maskLoadState == LoadState::LOAD_FAILED
980           {
981             // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
982             DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
983             UploadTexture(pixelBuffer, textureInfo);
984             NotifyObservers(textureInfo, true);
985           }
986         }
987       }
988       else
989       {
990         UploadTexture(pixelBuffer, textureInfo);
991         NotifyObservers(textureInfo, true);
992       }
993     }
994     else
995     {
996       textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
997       textureInfo.loadState   = LoadState::LOAD_FINISHED;
998
999       if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1000       {
1001         NotifyObservers(textureInfo, true);
1002       }
1003       else // for the StorageType::KEEP_PIXEL_BUFFER and StorageType::KEEP_TEXTURE
1004       {
1005         // Check if there was another texture waiting for this load to complete
1006         // (e.g. if this was an image mask, and its load is on a different thread)
1007         CheckForWaitingTexture(textureInfo);
1008       }
1009     }
1010   }
1011   else
1012   {
1013     textureInfo.loadState = LoadState::LOAD_FAILED;
1014     if(textureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER || textureInfo.storageType == StorageType::KEEP_TEXTURE)
1015     {
1016       // Check if there was another texture waiting for this load to complete
1017       // (e.g. if this was an image mask, and its load is on a different thread)
1018       CheckForWaitingTexture(textureInfo);
1019     }
1020     else
1021     {
1022       NotifyObservers(textureInfo, false);
1023     }
1024   }
1025 }
1026
1027 void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTextureInfo)
1028 {
1029   if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED &&
1030      maskTextureInfo.storageType == StorageType::KEEP_TEXTURE)
1031   {
1032     // Upload mask texture. textureInfo.loadState will be UPLOADED.
1033     UploadTexture(maskTextureInfo.pixelBuffer, maskTextureInfo);
1034   }
1035
1036   // Search the cache, checking if any texture has this texture id as a
1037   // maskTextureId:
1038   const std::size_t size = mTextureCacheManager.size();
1039
1040   // TODO : Refactorize here to not iterate whole cached image.
1041   for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
1042   {
1043     if(mTextureCacheManager[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
1044        mTextureCacheManager[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
1045     {
1046       TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
1047
1048       if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED)
1049       {
1050         if(maskTextureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER)
1051         {
1052           // Send New Task to Thread
1053           ApplyMask(textureInfo, maskTextureInfo.textureId);
1054         }
1055       }
1056       else if(maskTextureInfo.loadState == LoadState::UPLOADED)
1057       {
1058         if(maskTextureInfo.storageType == StorageType::KEEP_TEXTURE)
1059         {
1060           // Upload image texture. textureInfo.loadState will be UPLOADED.
1061           UploadTexture(textureInfo.pixelBuffer, textureInfo);
1062           if(maskTextureInfo.textureSet.GetTextureCount() > 0u)
1063           {
1064             Texture maskTexture = maskTextureInfo.textureSet.GetTexture(0u);
1065             textureInfo.textureSet.SetTexture(1u, maskTexture);
1066           }
1067           // notify mask texture set.
1068           NotifyObservers(textureInfo, true);
1069         }
1070       }
1071       else
1072       {
1073         // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
1074         DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
1075         UploadTexture(textureInfo.pixelBuffer, textureInfo);
1076         NotifyObservers(textureInfo, true);
1077       }
1078     }
1079   }
1080 }
1081
1082 void TextureManager::ApplyMask(TextureManager::TextureInfo& textureInfo, const TextureManager::TextureId& maskTextureId)
1083 {
1084   TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
1085   if(maskCacheIndex != INVALID_CACHE_INDEX)
1086   {
1087     Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
1088     Devel::PixelBuffer pixelBuffer     = textureInfo.pixelBuffer;
1089     textureInfo.pixelBuffer.Reset();
1090
1091     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
1092
1093     textureInfo.loadState   = LoadState::MASK_APPLYING;
1094     auto& loadersContainer  = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1095     auto  loadingHelperIt   = loadersContainer.GetNext();
1096     auto  premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1097     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1098     loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
1099   }
1100 }
1101
1102 void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureManager::TextureInfo& textureInfo)
1103 {
1104   if(textureInfo.loadState != LoadState::UPLOADED && textureInfo.useAtlas != UseAtlas::USE_ATLAS)
1105   {
1106     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "  TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
1107
1108     // Check if this pixelBuffer is premultiplied
1109     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1110
1111     auto& renderingAddOn = RenderingAddOn::Get();
1112     if(renderingAddOn.IsValid())
1113     {
1114       renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
1115     }
1116
1117     Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1118
1119     PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1120     texture.Upload(pixelData);
1121     if(!textureInfo.textureSet)
1122     {
1123       textureInfo.textureSet = TextureSet::New();
1124     }
1125     textureInfo.textureSet.SetTexture(0u, texture);
1126   }
1127
1128   // Update the load state.
1129   // Note: This is regardless of success as we care about whether a
1130   // load attempt is in progress or not.  If unsuccessful, a broken
1131   // image is still loaded.
1132   textureInfo.loadState = LoadState::UPLOADED;
1133 }
1134
1135 void TextureManager::NotifyObservers(TextureManager::TextureInfo& textureInfo, const bool& success)
1136 {
1137   TextureId textureId = textureInfo.textureId;
1138
1139   // If there is an observer: Notify the load is complete, whether successful or not,
1140   // and erase it from the list
1141   TextureInfo* info = &textureInfo;
1142
1143   if(info->animatedImageLoading)
1144   {
1145     // If loading failed, we don't need to get frameCount and frameInterval.
1146     if(success)
1147     {
1148       info->frameCount    = info->animatedImageLoading.GetImageCount();
1149       info->frameInterval = info->animatedImageLoading.GetFrameInterval(info->frameIndex);
1150     }
1151     info->animatedImageLoading.Reset();
1152   }
1153
1154   mQueueLoadFlag = true;
1155
1156   // Reverse observer list that we can pop_back the observer.
1157   std::reverse(info->observerList.Begin(), info->observerList.End());
1158
1159   while(info->observerList.Count())
1160   {
1161     TextureUploadObserver* observer = *(info->observerList.End() - 1u);
1162
1163     // During LoadComplete() a Control ResourceReady() signal is emitted.
1164     // During that signal the app may add remove /add Textures (e.g. via
1165     // ImageViews).
1166     // It is possible for observers to be removed from the observer list,
1167     // and it is also possible for the mTextureInfoContainer to be modified,
1168     // invalidating the reference to the textureInfo struct.
1169     // Texture load requests for the same URL are deferred until the end of this
1170     // method.
1171     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::NotifyObservers() textureId:%d url:%s loadState:%s\n", textureId, info->url.GetUrl().c_str(), GET_LOAD_STATE_STRING(info->loadState));
1172
1173     // It is possible for the observer to be deleted.
1174     // Disconnect and remove the observer first.
1175     observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1176
1177     info->observerList.Erase(info->observerList.End() - 1u);
1178
1179     EmitLoadComplete(observer, *info, success);
1180
1181     // Get the textureInfo from the container again as it may have been invalidated.
1182     TextureCacheIndex textureInfoIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1183     if(textureInfoIndex == INVALID_CACHE_INDEX)
1184     {
1185       break; // texture has been removed - can stop.
1186     }
1187     info = &mTextureCacheManager[textureInfoIndex];
1188   }
1189
1190   mQueueLoadFlag = false;
1191   ProcessLoadQueue();
1192   ProcessRemoveQueue();
1193
1194   if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1195   {
1196     Remove(info->textureId, nullptr);
1197   }
1198 }
1199
1200 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1201 {
1202   const std::size_t size = mTextureCacheManager.size();
1203   for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
1204   {
1205     TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
1206     for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1207         j != textureInfo.observerList.End();)
1208     {
1209       if(*j == observer)
1210       {
1211         j = textureInfo.observerList.Erase(j);
1212       }
1213       else
1214       {
1215         ++j;
1216       }
1217     }
1218   }
1219
1220   // Remove element from the LoadQueue
1221   for(auto&& element : mLoadQueue)
1222   {
1223     if(element.mObserver == observer)
1224     {
1225       element.mObserver = nullptr;
1226     }
1227   }
1228 }
1229
1230 Dali::Geometry TextureManager::GetRenderGeometry(const TextureManager::TextureId& textureId, std::uint32_t& frontElements, std::uint32_t& backElements)
1231 {
1232   return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1233 }
1234
1235 void TextureManager::EmitLoadComplete(TextureUploadObserver* observer, TextureManager::TextureInfo& textureInfo, const bool& success)
1236 {
1237   if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1238   {
1239     observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, textureInfo.pixelBuffer, textureInfo.url.GetUrl(), textureInfo.preMultiplied));
1240   }
1241   else if(textureInfo.isAnimatedImageFormat)
1242   {
1243     observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::ANIMATED_IMAGE_TEXTURE, textureInfo.textureId, textureInfo.frameCount, textureInfo.frameInterval));
1244   }
1245   else
1246   {
1247     observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureInfo.textureSet, (textureInfo.useAtlas == UseAtlas::USE_ATLAS) ? true : false, textureInfo.atlasRect, textureInfo.preMultiplied));
1248   }
1249 }
1250
1251 } // namespace Internal
1252
1253 } // namespace Toolkit
1254
1255 } // namespace Dali