[dali_2.2.44] Merge branch 'devel/master'
[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.loadState = TextureManager::LoadState::WAITING_FOR_MASK;
588     }
589   }
590
591   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
592
593   // Force reloading of texture by setting loadState unless already loading or cancelled.
594   if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
595      TextureManager::LoadState::LOADING != textureInfo.loadState &&
596      TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
597      TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
598      TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
599      TextureManager::LoadState::CANCELLED != textureInfo.loadState &&
600      TextureManager::LoadState::MASK_CANCELLED != textureInfo.loadState)
601   {
602     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);
603     textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
604   }
605
606   if(!synchronousLoading)
607   {
608     // Check if we should add the observer.
609     // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
610     switch(textureInfo.loadState)
611     {
612       case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
613       case TextureManager::LoadState::NOT_STARTED:
614       {
615         LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
616         break;
617       }
618       case TextureManager::LoadState::LOADING:
619       case TextureManager::LoadState::WAITING_FOR_MASK:
620       case TextureManager::LoadState::MASK_APPLYING:
621       case TextureManager::LoadState::MASK_APPLIED:
622       {
623         // Do not observe even we reload forced when texture is already loading state.
624         if(TextureManager::ReloadPolicy::CACHED == reloadPolicy || TextureManager::INVALID_TEXTURE_ID == previousTextureId)
625         {
626           ObserveTexture(textureInfo, observer);
627         }
628         break;
629       }
630       case TextureManager::LoadState::UPLOADED:
631       {
632         if(observer)
633         {
634           LoadOrQueueTexture(textureInfo, observer);
635         }
636         break;
637       }
638       case TextureManager::LoadState::CANCELLED:
639       {
640         // A cancelled texture hasn't finished loading yet. Treat as a loading texture
641         // (it's ref count has already been incremented, above)
642         textureInfo.loadState = TextureManager::LoadState::LOADING;
643         ObserveTexture(textureInfo, observer);
644         break;
645       }
646       case TextureManager::LoadState::MASK_CANCELLED:
647       {
648         // A cancelled texture hasn't finished mask applying yet. Treat as a mask applying texture
649         // (it's ref count has already been incremented, above)
650         textureInfo.loadState = TextureManager::LoadState::MASK_APPLYING;
651         ObserveTexture(textureInfo, observer);
652         break;
653       }
654       case TextureManager::LoadState::LOAD_FINISHED:
655       {
656         // Loading has already completed.
657         if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
658         {
659           LoadOrQueueTexture(textureInfo, observer);
660         }
661         break;
662       }
663     }
664   }
665   else
666   {
667     // If the image is already finished to load, use cached texture.
668     // We don't need to consider Observer because this is synchronous loading.
669     if(!(textureInfo.loadState == TextureManager::LoadState::UPLOADED ||
670          textureInfo.loadState == TextureManager::LoadState::LOAD_FINISHED))
671     {
672       if(url.GetProtocolType() == VisualUrl::TEXTURE)
673       {
674         // Get external textureSet from cacheManager.
675         std::string location = textureInfo.url.GetLocation();
676         if(!location.empty())
677         {
678           TextureId id                  = std::stoi(location);
679           auto      externalTextureInfo = mTextureCacheManager.GetExternalTextureInfo(id);
680           textureInfo.textures.push_back(externalTextureInfo.textureSet.GetTexture(0));
681           textureInfo.loadState = LoadState::UPLOADED;
682         }
683       }
684       else
685       {
686         std::vector<Devel::PixelBuffer> pixelBuffers;
687         LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection, loadYuvPlanes, pixelBuffers);
688
689         if(pixelBuffers.empty())
690         {
691           // If pixelBuffer loading is failed in synchronously, call RequestRemove() method.
692           RequestRemove(textureId, nullptr);
693           return INVALID_TEXTURE_ID;
694         }
695
696         if(storageType == StorageType::KEEP_PIXEL_BUFFER) // For the mask image loading.
697         {
698           textureInfo.pixelBuffer = pixelBuffers[0]; // Store the pixel data
699           textureInfo.loadState   = LoadState::LOAD_FINISHED;
700         }
701         else // For the image loading.
702         {
703           Texture maskTexture;
704           if(maskTextureId != INVALID_TEXTURE_ID)
705           {
706             TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
707             if(maskCacheIndex != INVALID_CACHE_INDEX)
708             {
709               if(mTextureCacheManager[maskCacheIndex].storageType == StorageType::KEEP_PIXEL_BUFFER)
710               {
711                 Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
712                 if(maskPixelBuffer)
713                 {
714                   pixelBuffers[0].ApplyMask(maskPixelBuffer, contentScale, cropToMask);
715                 }
716                 else
717                 {
718                   DALI_LOG_ERROR("Mask image cached invalid pixel buffer!\n");
719                 }
720               }
721             }
722             else
723             {
724               DALI_LOG_ERROR("Mask image is not stored in cache.\n");
725             }
726           }
727           PreMultiply(pixelBuffers[0], preMultiplyOnLoad);
728
729           // Upload texture
730           UploadTextures(pixelBuffers, textureInfo);
731         }
732       }
733     }
734   }
735
736   return textureId;
737 }
738
739 void TextureManager::RequestRemove(const TextureManager::TextureId& textureId, TextureUploadObserver* observer)
740 {
741   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestRemove( textureId=%d observer=%p )\n", textureId, observer);
742
743   // Queue to remove.
744   if(textureId != INVALID_TEXTURE_ID)
745   {
746     TextureCacheIndex textureCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
747     if(textureCacheIndex != INVALID_CACHE_INDEX)
748     {
749       if(observer)
750       {
751         // Remove observer from cached texture info
752         TextureInfo& textureInfo(mTextureCacheManager[textureCacheIndex]);
753         RemoveTextureObserver(textureInfo, observer);
754       }
755
756       mRemoveQueue.PushBack(textureId);
757
758       if(!mRemoveProcessorRegistered && Adaptor::IsAvailable())
759       {
760         mRemoveProcessorRegistered = true;
761         Adaptor::Get().RegisterProcessor(*this, true);
762       }
763     }
764   }
765 }
766
767 void TextureManager::Remove(const TextureManager::TextureId& textureId)
768 {
769   if(textureId != INVALID_TEXTURE_ID)
770   {
771     TextureCacheIndex textureCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
772     if(textureCacheIndex != INVALID_CACHE_INDEX)
773     {
774       TextureManager::TextureId maskTextureId = INVALID_TEXTURE_ID;
775       TextureInfo&              textureInfo(mTextureCacheManager[textureCacheIndex]);
776       // We only need to consider maskTextureId when texture's loadState is not cancelled. Because it is already deleted.
777       if(textureInfo.loadState != LoadState::CANCELLED && textureInfo.loadState != LoadState::MASK_CANCELLED)
778       {
779         if(textureInfo.maskTextureId != INVALID_TEXTURE_ID)
780         {
781           maskTextureId = textureInfo.maskTextureId;
782         }
783       }
784
785       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));
786
787       // Remove textureId in CacheManager. Now, textureInfo is invalidate.
788       mTextureCacheManager.RemoveCache(textureInfo);
789
790       // Remove maskTextureId in CacheManager
791       if(maskTextureId != INVALID_TEXTURE_ID)
792       {
793         TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
794         if(maskCacheIndex != INVALID_CACHE_INDEX)
795         {
796           TextureInfo& maskTextureInfo(mTextureCacheManager[maskCacheIndex]);
797
798           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));
799
800           mTextureCacheManager.RemoveCache(maskTextureInfo);
801         }
802       }
803     }
804   }
805 }
806
807 void TextureManager::ProcessRemoveQueue()
808 {
809   // Note that RemoveQueue is not be changed during Remove().
810   for(auto&& textureId : mRemoveQueue)
811   {
812     if(textureId != INVALID_TEXTURE_ID)
813     {
814       Remove(textureId);
815     }
816   }
817   mRemoveQueue.Clear();
818 }
819
820 void TextureManager::Process(bool postProcessor)
821 {
822   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::Process()\n");
823
824   ProcessRemoveQueue();
825
826   if(Adaptor::IsAvailable())
827   {
828     Adaptor::Get().UnregisterProcessor(*this, true);
829     mRemoveProcessorRegistered = false;
830   }
831 }
832
833 void TextureManager::LoadImageSynchronously(
834   const VisualUrl&                 url,
835   const Dali::ImageDimensions&     desiredSize,
836   const Dali::FittingMode::Type&   fittingMode,
837   const Dali::SamplingMode::Type&  samplingMode,
838   const bool&                      orientationCorrection,
839   const bool&                      loadYuvPlanes,
840   std::vector<Devel::PixelBuffer>& pixelBuffers)
841 {
842   Devel::PixelBuffer pixelBuffer;
843   if(url.IsBufferResource())
844   {
845     const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
846     if(encodedImageBuffer)
847     {
848       pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
849     }
850   }
851   else
852   {
853     if(loadYuvPlanes)
854     {
855       Dali::LoadImagePlanesFromFile(url.GetUrl(), pixelBuffers, desiredSize, fittingMode, samplingMode, orientationCorrection);
856     }
857     else
858     {
859       pixelBuffer = Dali::LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
860     }
861   }
862
863   if(pixelBuffer)
864   {
865     pixelBuffers.push_back(pixelBuffer);
866   }
867 }
868
869 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
870 {
871   // make sure an observer doesn't observe the same object twice
872   // otherwise it will get multiple calls to ObjectDestroyed()
873   DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
874   mLifecycleObservers.PushBack(&observer);
875 }
876
877 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
878 {
879   // Find the observer...
880   auto endIter = mLifecycleObservers.End();
881   for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
882   {
883     if((*iter) == &observer)
884     {
885       mLifecycleObservers.Erase(iter);
886       break;
887     }
888   }
889   DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
890 }
891
892 void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
893 {
894   switch(textureInfo.loadState)
895   {
896     case LoadState::NOT_STARTED:
897     case LoadState::LOAD_FAILED:
898     {
899       if(mLoadingQueueTextureId != INVALID_TEXTURE_ID)
900       {
901         QueueLoadTexture(textureInfo, observer);
902       }
903       else
904       {
905         LoadTexture(textureInfo, observer);
906       }
907       break;
908     }
909     case LoadState::UPLOADED:
910     {
911       if(mLoadingQueueTextureId != INVALID_TEXTURE_ID)
912       {
913         QueueLoadTexture(textureInfo, observer);
914       }
915       else
916       {
917         // The Texture has already loaded. The other observers have already been notified.
918         // We need to send a "late" loaded notification for this observer.
919         if(observer)
920         {
921           EmitLoadComplete(observer, textureInfo, true);
922         }
923       }
924       break;
925     }
926     case LoadState::LOADING:
927     case LoadState::CANCELLED:
928     case LoadState::MASK_CANCELLED:
929     case LoadState::LOAD_FINISHED:
930     case LoadState::WAITING_FOR_MASK:
931     case LoadState::MASK_APPLYING:
932     case LoadState::MASK_APPLIED:
933     {
934       break;
935     }
936   }
937 }
938
939 void TextureManager::QueueLoadTexture(const TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
940 {
941   const auto& textureId = textureInfo.textureId;
942   mLoadQueue.PushBack(QueueElement(textureId, observer));
943
944   if(observer)
945   {
946     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "  Connect DestructionSignal to observer:%p\n", observer);
947     observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
948   }
949 }
950
951 void TextureManager::LoadTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
952 {
953   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
954   textureInfo.loadState = LoadState::LOADING;
955   if(!textureInfo.loadSynchronously)
956   {
957     auto premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
958     if(textureInfo.animatedImageLoading)
959     {
960       mAsyncLoader->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, premultiplyOnLoad);
961     }
962     else
963     {
964       mAsyncLoader->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad, textureInfo.loadYuvPlanes);
965     }
966   }
967   ObserveTexture(textureInfo, observer);
968 }
969
970 void TextureManager::ProcessLoadQueue()
971 {
972   for(auto&& element : mLoadQueue)
973   {
974     if(element.mTextureId == INVALID_TEXTURE_ID)
975     {
976       continue;
977     }
978
979     TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(element.mTextureId);
980     if(cacheIndex != INVALID_CACHE_INDEX)
981     {
982       TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
983
984       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));
985
986       if((textureInfo.loadState == LoadState::UPLOADED) || (textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER))
987       {
988         if(element.mObserver)
989         {
990           EmitLoadComplete(element.mObserver, textureInfo, true);
991         }
992       }
993       else if(textureInfo.loadState == LoadState::LOADING)
994       {
995         // Note : LOADING state texture cannot be queue.
996         // This case be occured when same texture id are queue in mLoadQueue.
997         ObserveTexture(textureInfo, element.mObserver);
998       }
999       else
1000       {
1001         LoadTexture(textureInfo, element.mObserver);
1002       }
1003     }
1004   }
1005   mLoadQueue.Clear();
1006 }
1007
1008 void TextureManager::ObserveTexture(TextureManager::TextureInfo& textureInfo,
1009                                     TextureUploadObserver*       observer)
1010 {
1011   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
1012
1013   if(observer)
1014   {
1015     textureInfo.observerList.PushBack(observer);
1016
1017     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "  Connect DestructionSignal to observer:%p\n", observer);
1018     observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
1019   }
1020 }
1021
1022 void TextureManager::AsyncLoadComplete(const TextureManager::TextureId& textureId, std::vector<Devel::PixelBuffer>& pixelBuffers)
1023 {
1024   TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1025   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( textureId:%d CacheIndex:%d )\n", textureId, cacheIndex.GetIndex());
1026   if(cacheIndex != INVALID_CACHE_INDEX)
1027   {
1028     TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
1029
1030     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));
1031     if(textureInfo.loadState != LoadState::CANCELLED && textureInfo.loadState != LoadState::MASK_CANCELLED)
1032     {
1033       // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
1034       PostLoad(textureInfo, pixelBuffers);
1035     }
1036     else
1037     {
1038       Remove(textureInfo.textureId);
1039     }
1040   }
1041 }
1042
1043 void TextureManager::PostLoad(TextureManager::TextureInfo& textureInfo, std::vector<Devel::PixelBuffer>& pixelBuffers)
1044 {
1045   // Was the load successful?
1046   if(!pixelBuffers.empty())
1047   {
1048     if(pixelBuffers.size() == 1)
1049     {
1050       Devel::PixelBuffer pixelBuffer = pixelBuffers[0];
1051       if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
1052       {
1053         // No atlas support for now
1054         textureInfo.useAtlas      = UseAtlas::NO_ATLAS;
1055         textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1056
1057         if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
1058         {
1059           // If there is a mask texture ID associated with this texture, then apply the mask
1060           // if it's already loaded. If it hasn't, and the mask is still loading,
1061           // wait for the mask to finish loading.
1062           // note, If the texture is already uploaded synchronously during loading,
1063           // we don't need to apply mask.
1064           if(textureInfo.loadState != LoadState::UPLOADED &&
1065              textureInfo.maskTextureId != INVALID_TEXTURE_ID)
1066           {
1067             if(textureInfo.loadState == LoadState::MASK_APPLYING)
1068             {
1069               textureInfo.loadState = LoadState::MASK_APPLIED;
1070               UploadTextures(pixelBuffers, textureInfo);
1071               NotifyObservers(textureInfo, true);
1072             }
1073             else
1074             {
1075               LoadState maskLoadState = mTextureCacheManager.GetTextureStateInternal(textureInfo.maskTextureId);
1076               textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
1077               if(maskLoadState == LoadState::LOADING)
1078               {
1079                 textureInfo.loadState = LoadState::WAITING_FOR_MASK;
1080               }
1081               else if(maskLoadState == LoadState::LOAD_FINISHED || maskLoadState == LoadState::UPLOADED)
1082               {
1083                 // Send New Task to Thread
1084                 TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureInfo.maskTextureId);
1085                 if(maskCacheIndex != INVALID_CACHE_INDEX)
1086                 {
1087                   TextureInfo& maskTextureInfo(mTextureCacheManager[maskCacheIndex]);
1088                   if(maskTextureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER)
1089                   {
1090                     // Send New Task to Thread
1091                     ApplyMask(textureInfo, textureInfo.maskTextureId);
1092                   }
1093                   else if(maskTextureInfo.storageType == StorageType::KEEP_TEXTURE)
1094                   {
1095                     // Upload image texture. textureInfo.loadState will be UPLOADED.
1096                     UploadTextures(pixelBuffers, textureInfo);
1097
1098                     // notify mask texture set.
1099                     NotifyObservers(textureInfo, true);
1100                   }
1101                 }
1102               }
1103               else // maskLoadState == LoadState::LOAD_FAILED
1104               {
1105                 // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
1106                 DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
1107                 UploadTextures(pixelBuffers, textureInfo);
1108                 NotifyObservers(textureInfo, true);
1109               }
1110             }
1111           }
1112           else
1113           {
1114             UploadTextures(pixelBuffers, textureInfo);
1115             NotifyObservers(textureInfo, true);
1116           }
1117         }
1118         else
1119         {
1120           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
1121           textureInfo.loadState   = LoadState::LOAD_FINISHED;
1122
1123           if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1124           {
1125             NotifyObservers(textureInfo, true);
1126           }
1127           else // for the StorageType::KEEP_PIXEL_BUFFER and StorageType::KEEP_TEXTURE
1128           {
1129             // Check if there was another texture waiting for this load to complete
1130             // (e.g. if this was an image mask, and its load is on a different thread)
1131             CheckForWaitingTexture(textureInfo);
1132           }
1133         }
1134       }
1135     }
1136     else
1137     {
1138       // YUV case
1139       // No atlas support for now
1140       textureInfo.useAtlas      = UseAtlas::NO_ATLAS;
1141       textureInfo.preMultiplied = false;
1142
1143       UploadTextures(pixelBuffers, textureInfo);
1144       NotifyObservers(textureInfo, true);
1145     }
1146   }
1147   else
1148   {
1149     textureInfo.loadState = LoadState::LOAD_FAILED;
1150     if(textureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER || textureInfo.storageType == StorageType::KEEP_TEXTURE)
1151     {
1152       // Check if there was another texture waiting for this load to complete
1153       // (e.g. if this was an image mask, and its load is on a different thread)
1154       CheckForWaitingTexture(textureInfo);
1155     }
1156     else
1157     {
1158       NotifyObservers(textureInfo, false);
1159     }
1160   }
1161 }
1162
1163 void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTextureInfo)
1164 {
1165   if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED &&
1166      maskTextureInfo.storageType == StorageType::KEEP_TEXTURE)
1167   {
1168     // Upload mask texture. textureInfo.loadState will be UPLOADED.
1169     std::vector<Devel::PixelBuffer> pixelBuffers;
1170     pixelBuffers.push_back(maskTextureInfo.pixelBuffer);
1171     UploadTextures(pixelBuffers, maskTextureInfo);
1172   }
1173
1174   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::CheckForWaitingTexture(): maskTextureId=%d, maskTextureUrl=%s\n", maskTextureInfo.textureId, maskTextureInfo.url.GetUrl().c_str());
1175
1176   // Search the cache, checking if any texture has this texture id as a maskTextureId
1177   const std::size_t size = mTextureCacheManager.size();
1178
1179   // Keep notify observer required textureIds.
1180   // Note : NotifyObservers can change mTextureCacheManager cache struct. We should check id's validation before notify.
1181   std::vector<TextureId> notifyRequiredTextureIds;
1182
1183   // TODO : Refactorize here to not iterate whole cached image.
1184   for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
1185   {
1186     if(mTextureCacheManager[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
1187        mTextureCacheManager[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
1188     {
1189       TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
1190
1191       if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED)
1192       {
1193         if(maskTextureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER)
1194         {
1195           // Send New Task to Thread
1196           ApplyMask(textureInfo, maskTextureInfo.textureId);
1197         }
1198       }
1199       else if(maskTextureInfo.loadState == LoadState::UPLOADED)
1200       {
1201         if(maskTextureInfo.storageType == StorageType::KEEP_TEXTURE)
1202         {
1203           if(textureInfo.url.GetProtocolType() == VisualUrl::TEXTURE)
1204           {
1205             // Get external textureSet from cacheManager.
1206             std::string location = textureInfo.url.GetLocation();
1207             if(!location.empty())
1208             {
1209               TextureId id                  = std::stoi(location);
1210               auto      externalTextureInfo = mTextureCacheManager.GetExternalTextureInfo(id);
1211               textureInfo.textures.push_back(externalTextureInfo.textureSet.GetTexture(0));
1212               textureInfo.loadState = LoadState::UPLOADED;
1213             }
1214           }
1215           else
1216           {
1217             // Upload image texture. textureInfo.loadState will be UPLOADED.
1218             std::vector<Devel::PixelBuffer> pixelBuffers;
1219             pixelBuffers.push_back(textureInfo.pixelBuffer);
1220             UploadTextures(pixelBuffers, textureInfo);
1221           }
1222
1223           // Increase reference counts for notify required textureId.
1224           // Now we can assume that we don't remove & re-assign this textureId
1225           // during NotifyObserver signal emit.
1226           maskTextureInfo.referenceCount++;
1227           textureInfo.referenceCount++;
1228
1229           DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::CheckForWaitingTexture(): Ready to notify textureId=%d\n", textureInfo.textureId);
1230
1231           notifyRequiredTextureIds.push_back(textureInfo.textureId);
1232         }
1233       }
1234       else // maskTextureInfo.loadState == LoadState::LOAD_FAILED
1235       {
1236         // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
1237         DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
1238         std::vector<Devel::PixelBuffer> pixelBuffers;
1239         pixelBuffers.push_back(textureInfo.pixelBuffer);
1240         UploadTextures(pixelBuffers, textureInfo);
1241
1242         // Increase reference counts for notify required textureId.
1243         // Now we can assume that we don't remove & re-assign this textureId
1244         // during NotifyObserver signal emit.
1245         maskTextureInfo.referenceCount++;
1246         textureInfo.referenceCount++;
1247
1248         DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::CheckForWaitingTexture(): Ready to notify textureId=%d\n", textureInfo.textureId);
1249
1250         notifyRequiredTextureIds.push_back(textureInfo.textureId);
1251       }
1252     }
1253   }
1254
1255   // Notify textures are masked
1256   for(const auto textureId : notifyRequiredTextureIds)
1257   {
1258     TextureCacheIndex textureCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1259     if(textureCacheIndex != INVALID_CACHE_INDEX)
1260     {
1261       TextureInfo& textureInfo(mTextureCacheManager[textureCacheIndex]);
1262       NotifyObservers(textureInfo, true);
1263     }
1264   }
1265
1266   // Decrease reference count
1267   for(const auto textureId : notifyRequiredTextureIds)
1268   {
1269     RequestRemove(textureId, nullptr);
1270   }
1271 }
1272
1273 void TextureManager::ApplyMask(TextureManager::TextureInfo& textureInfo, const TextureManager::TextureId& maskTextureId)
1274 {
1275   TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
1276   if(maskCacheIndex != INVALID_CACHE_INDEX)
1277   {
1278     Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
1279     Devel::PixelBuffer pixelBuffer     = textureInfo.pixelBuffer;
1280     textureInfo.pixelBuffer.Reset();
1281
1282     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
1283
1284     textureInfo.loadState  = LoadState::MASK_APPLYING;
1285     auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1286     mAsyncLoader->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
1287   }
1288 }
1289
1290 void TextureManager::UploadTextures(std::vector<Devel::PixelBuffer>& pixelBuffers, TextureManager::TextureInfo& textureInfo)
1291 {
1292   if(!pixelBuffers.empty() && textureInfo.loadState != LoadState::UPLOADED && textureInfo.useAtlas != UseAtlas::USE_ATLAS)
1293   {
1294     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "  TextureManager::UploadTextures() New Texture for textureId:%d\n", textureInfo.textureId);
1295
1296     // Check if this pixelBuffer is premultiplied
1297     textureInfo.preMultiplied = pixelBuffers[0].IsAlphaPreMultiplied();
1298
1299     auto& renderingAddOn = RenderingAddOn::Get();
1300     if(renderingAddOn.IsValid())
1301     {
1302       renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffers[0]);
1303     }
1304
1305     // Remove previous textures and insert new textures
1306     textureInfo.textures.clear();
1307
1308     for(auto&& pixelBuffer : pixelBuffers)
1309     {
1310       Texture   texture   = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1311       PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1312       texture.Upload(pixelData);
1313       textureInfo.textures.push_back(texture);
1314     }
1315   }
1316
1317   // Update the load state.
1318   // Note: This is regardless of success as we care about whether a
1319   // load attempt is in progress or not.  If unsuccessful, a broken
1320   // image is still loaded.
1321   textureInfo.loadState = LoadState::UPLOADED;
1322 }
1323
1324 void TextureManager::NotifyObservers(TextureManager::TextureInfo& textureInfo, const bool& success)
1325 {
1326   TextureId textureId = textureInfo.textureId;
1327
1328   // If there is an observer: Notify the load is complete, whether successful or not,
1329   // and erase it from the list
1330   TextureInfo* info = &textureInfo;
1331
1332   if(info->animatedImageLoading)
1333   {
1334     // If loading failed, we don't need to get frameCount and frameInterval.
1335     if(success)
1336     {
1337       info->frameCount    = info->animatedImageLoading.GetImageCount();
1338       info->frameInterval = info->animatedImageLoading.GetFrameInterval(info->frameIndex);
1339     }
1340     info->animatedImageLoading.Reset();
1341   }
1342
1343   mLoadingQueueTextureId = textureId;
1344
1345   // Reverse observer list that we can pop_back the observer.
1346   std::reverse(info->observerList.Begin(), info->observerList.End());
1347
1348   while(info->observerList.Count())
1349   {
1350     TextureUploadObserver* observer = *(info->observerList.End() - 1u);
1351
1352     // During LoadComplete() a Control ResourceReady() signal is emitted.
1353     // During that signal the app may add remove /add Textures (e.g. via
1354     // ImageViews).
1355     // It is possible for observers to be removed from the observer list,
1356     // and it is also possible for the mTextureInfoContainer to be modified,
1357     // invalidating the reference to the textureInfo struct.
1358     // Texture load requests for the same URL are deferred until the end of this
1359     // method.
1360     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));
1361     // It is possible for the observer to be deleted.
1362     // Disconnect and remove the observer first.
1363     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "  Disconnect DestructionSignal to observer:%p\n", observer);
1364     observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1365
1366     info->observerList.Erase(info->observerList.End() - 1u);
1367
1368     EmitLoadComplete(observer, *info, success);
1369
1370     // Get the textureInfo from the container again as it may have been invalidated.
1371     TextureCacheIndex textureInfoIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1372     if(textureInfoIndex == INVALID_CACHE_INDEX)
1373     {
1374       break; // texture has been removed - can stop.
1375     }
1376     info = &mTextureCacheManager[textureInfoIndex];
1377   }
1378
1379   mLoadingQueueTextureId = INVALID_TEXTURE_ID;
1380   ProcessLoadQueue();
1381
1382   if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1383   {
1384     RequestRemove(info->textureId, nullptr);
1385   }
1386 }
1387
1388 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1389 {
1390   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "TextureManager::ObserverDestroyed() observer:%p\n", observer);
1391
1392   const std::size_t size = mTextureCacheManager.size();
1393   for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
1394   {
1395     TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
1396     for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1397         j != textureInfo.observerList.End();)
1398     {
1399       if(*j == observer)
1400       {
1401         j = textureInfo.observerList.Erase(j);
1402       }
1403       else
1404       {
1405         ++j;
1406       }
1407     }
1408   }
1409
1410   // Remove element from the LoadQueue
1411   for(auto&& element : mLoadQueue)
1412   {
1413     if(element.mObserver == observer)
1414     {
1415       element.mTextureId = INVALID_TEXTURE_ID;
1416       element.mObserver  = nullptr;
1417     }
1418   }
1419 }
1420
1421 Dali::Geometry TextureManager::GetRenderGeometry(const TextureManager::TextureId& textureId, std::uint32_t& frontElements, std::uint32_t& backElements)
1422 {
1423   return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1424 }
1425
1426 void TextureManager::EmitLoadComplete(TextureUploadObserver* observer, TextureManager::TextureInfo& textureInfo, const bool& success)
1427 {
1428   if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1429   {
1430     observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, textureInfo.pixelBuffer, textureInfo.url.GetUrl(), textureInfo.preMultiplied));
1431   }
1432   else
1433   {
1434     TextureSet textureSet = GetTextureSet(textureInfo);
1435     if(textureInfo.isAnimatedImageFormat)
1436     {
1437       observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::ANIMATED_IMAGE_TEXTURE, textureInfo.textureId, textureSet, textureInfo.frameCount, textureInfo.frameInterval));
1438     }
1439     else
1440     {
1441       observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureSet, (textureInfo.useAtlas == UseAtlas::USE_ATLAS) ? true : false, textureInfo.atlasRect, textureInfo.preMultiplied));
1442     }
1443   }
1444 }
1445
1446 TextureSet TextureManager::GetTextureSet(const TextureManager::TextureId& textureId)
1447 {
1448   TextureSet                textureSet;
1449   TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
1450   if(loadState == TextureManager::LoadState::UPLOADED)
1451   {
1452     // LoadComplete has already been called - keep the same texture set
1453     TextureCacheIndex textureCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1454     if(textureCacheIndex != INVALID_CACHE_INDEX)
1455     {
1456       TextureInfo& textureInfo(mTextureCacheManager[textureCacheIndex]);
1457       textureSet = GetTextureSet(textureInfo);
1458     }
1459   }
1460   else
1461   {
1462     DALI_LOG_ERROR("GetTextureSet is failed. texture is not uploaded \n");
1463   }
1464   return textureSet;
1465 }
1466
1467 TextureSet TextureManager::GetTextureSet(const TextureManager::TextureInfo& textureInfo)
1468 {
1469   TextureSet textureSet;
1470
1471   // LoadComplete has already been called - keep the same texture set
1472   textureSet = TextureSet::New();
1473   if(!textureInfo.textures.empty())
1474   {
1475     if(textureInfo.textures.size() > 1) // For YUV case
1476     {
1477       uint32_t index = 0u;
1478       for(auto&& texture : textureInfo.textures)
1479       {
1480         textureSet.SetTexture(index++, texture);
1481       }
1482     }
1483     else
1484     {
1485       textureSet.SetTexture(TEXTURE_INDEX, textureInfo.textures[0]);
1486       TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureInfo.maskTextureId);
1487       if(maskCacheIndex != INVALID_CACHE_INDEX)
1488       {
1489         TextureInfo& maskTextureInfo(mTextureCacheManager[maskCacheIndex]);
1490         if(maskTextureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE || maskTextureInfo.storageType == StorageType::KEEP_TEXTURE)
1491         {
1492           if(!maskTextureInfo.textures.empty())
1493           {
1494             textureSet.SetTexture(MASK_TEXTURE_INDEX, maskTextureInfo.textures[0]);
1495           }
1496         }
1497       }
1498     }
1499   }
1500   return textureSet;
1501 }
1502
1503 void TextureManager::RemoveTextureObserver(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
1504 {
1505   // Remove its observer
1506   if(observer)
1507   {
1508     const auto iterEnd = textureInfo.observerList.End();
1509     const auto iter    = std::find(textureInfo.observerList.Begin(), iterEnd, observer);
1510     if(iter != iterEnd)
1511     {
1512       // Disconnect and remove the observer.
1513       DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "  Disconnect DestructionSignal to observer:%p\n", observer);
1514       observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1515       textureInfo.observerList.Erase(iter);
1516     }
1517   }
1518 }
1519
1520 } // namespace Internal
1521
1522 } // namespace Toolkit
1523
1524 } // namespace Dali