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