Merge "Remove mask internally in texture manager" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / animated-image / rolling-animated-image-cache.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 // CLASS HEADER
18 #include "rolling-animated-image-cache.h"
19
20 // INTERNAL HEADERS
21 #include <dali-toolkit/devel-api/image-loader/texture-manager.h>
22 #include <dali-toolkit/internal/visuals/image-atlas-manager.h> // For ImageAtlasManagerPtr
23 #include <dali/integration-api/debug.h>
24
25 namespace
26 {
27 #if defined(DEBUG_ENABLED)
28 Debug::Filter* gAnimImgLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ANIMATED_IMAGE");
29
30 #define LOG_CACHE                                                                                                       \
31   if(gAnimImgLogFilter->IsEnabledFor(Debug::Concise))                                                                   \
32   {                                                                                                                     \
33     std::ostringstream oss;                                                                                             \
34     oss << "Size:" << mQueue.Count() << " [ ";                                                                          \
35     for(std::size_t _i = 0; _i < mQueue.Count(); ++_i)                                                                  \
36     {                                                                                                                   \
37       oss << _i << "={ frm#: " << mQueue[_i].mFrameNumber << " tex: " << mTextureIds[mQueue[_i].mFrameNumber] << "}, "; \
38     }                                                                                                                   \
39     oss << " ]" << std::endl;                                                                                           \
40     DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "%s", oss.str().c_str());                                          \
41   }
42
43 #else
44 #define LOG_CACHE
45 #endif
46
47 static constexpr bool ENABLE_ORIENTATION_CORRECTION(true);
48
49 } // namespace
50
51 namespace Dali
52 {
53 namespace Toolkit
54 {
55 namespace Internal
56 {
57 namespace
58 {
59 static constexpr uint32_t SINGLE_IMAGE_COUNT = 1u;
60 static constexpr uint32_t FIRST_FRAME_INDEX  = 0u;
61 } // namespace
62
63 RollingAnimatedImageCache::RollingAnimatedImageCache(TextureManager&                     textureManager,
64                                                      AnimatedImageLoading&               animatedImageLoading,
65                                                      TextureManager::MaskingDataPointer& maskingData,
66                                                      ImageCache::FrameReadyObserver&     observer,
67                                                      uint16_t                            cacheSize,
68                                                      uint16_t                            batchSize,
69                                                      const Dali::WrapMode::Type&         wrapModeU,
70                                                      const Dali::WrapMode::Type&         wrapModeV,
71                                                      bool                                isSynchronousLoading,
72                                                      bool                                preMultiplyOnLoad)
73 : ImageCache(textureManager, maskingData, observer, batchSize, 0u),
74   mImageUrl(animatedImageLoading.GetUrl()),
75   mAnimatedImageLoading(animatedImageLoading),
76   mFrameCount(SINGLE_IMAGE_COUNT),
77   mFrameIndex(FIRST_FRAME_INDEX),
78   mCacheSize(cacheSize),
79   mQueue(cacheSize),
80   mWrapModeU(wrapModeU),
81   mWrapModeV(wrapModeV),
82   mIsSynchronousLoading(isSynchronousLoading),
83   mPreMultiplyOnLoad(preMultiplyOnLoad)
84 {
85   mTextureIds.resize(mFrameCount);
86   mIntervals.assign(mFrameCount, 0);
87 }
88
89 RollingAnimatedImageCache::~RollingAnimatedImageCache()
90 {
91   ClearCache();
92   mAnimatedImageLoading.Reset();
93 }
94
95 TextureSet RollingAnimatedImageCache::Frame(uint32_t frameIndex)
96 {
97   bool popExist = false;
98   while(!mQueue.IsEmpty() && mQueue.Front().mFrameNumber != frameIndex)
99   {
100     PopFrontCache();
101     popExist = true;
102   }
103
104   TextureSet textureSet;
105   uint32_t   batchFrameIndex = frameIndex;
106   // If we need to load new frame that are not stored in queue.
107   // Load the frame synchronously.
108   bool synchronouslyLoaded = false;
109   if(mIsSynchronousLoading && mQueue.IsEmpty())
110   {
111     textureSet        = RequestFrameLoading(frameIndex, true);
112     batchFrameIndex   = (frameIndex + 1) % mFrameCount;
113     uint32_t interval = 0u;
114     if(textureSet)
115     {
116       synchronouslyLoaded = true;
117       interval            = mAnimatedImageLoading.GetFrameInterval(mQueue.Back().mFrameNumber);
118     }
119     MakeFrameReady(synchronouslyLoaded, textureSet, interval);
120   }
121
122   if(popExist || mQueue.IsEmpty() || synchronouslyLoaded)
123   {
124     // If the frame of frameIndex was already loaded, load batch from the last frame of queue
125     if(!mQueue.IsEmpty())
126     {
127       if(!mLoadWaitingQueue.empty())
128       {
129         batchFrameIndex = (mLoadWaitingQueue.back() + 1) % mFrameCount;
130       }
131       else
132       {
133         batchFrameIndex = (mQueue.Back().mFrameNumber + 1) % mFrameCount;
134       }
135     }
136     else
137     {
138       // If the request is for the first frame or a jumped frame(JUMP_TO) remove current waiting queue.
139       mLoadWaitingQueue.clear();
140       // If the queue is empty, and the frame of frameIndex is not loaded synchronously. load batch from the frame of frameIndex
141       if(!textureSet)
142       {
143         batchFrameIndex = frameIndex;
144       }
145     }
146     LoadBatch(batchFrameIndex);
147   }
148
149   if(!textureSet && mLoadState != TextureManager::LoadState::LOAD_FAILED && IsFrontReady() == true)
150   {
151     textureSet = GetFrontTextureSet();
152   }
153
154   return textureSet;
155 }
156
157 TextureSet RollingAnimatedImageCache::FirstFrame()
158 {
159   TextureSet textureSet = Frame(FIRST_FRAME_INDEX);
160   return textureSet;
161 }
162
163 uint32_t RollingAnimatedImageCache::GetFrameInterval(uint32_t frameIndex) const
164 {
165   if(frameIndex >= mIntervals.size())
166   {
167     return 0u;
168   }
169   return mIntervals[frameIndex];
170 }
171
172 int32_t RollingAnimatedImageCache::GetCurrentFrameIndex() const
173 {
174   if(mQueue.IsEmpty())
175   {
176     return -1;
177   }
178   return mQueue.Front().mFrameNumber;
179 }
180
181 int32_t RollingAnimatedImageCache::GetTotalFrameCount() const
182 {
183   return mFrameCount;
184 }
185
186 bool RollingAnimatedImageCache::IsFrontReady() const
187 {
188   return (!mQueue.IsEmpty() && mQueue.Front().mReady);
189 }
190
191 TextureSet RollingAnimatedImageCache::RequestFrameLoading(uint32_t frameIndex, bool synchronousLoading)
192 {
193   ImageFrame imageFrame;
194   imageFrame.mFrameNumber = frameIndex;
195   imageFrame.mReady       = false;
196
197   mQueue.PushBack(imageFrame);
198
199   mLoadState = TextureManager::LoadState::LOADING;
200
201   auto preMultiplyOnLoading = mPreMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD
202                                                  : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
203
204   TextureManager::TextureId loadTextureId = TextureManager::INVALID_TEXTURE_ID;
205   TextureSet                textureSet    = mTextureManager.LoadAnimatedImageTexture(mImageUrl,
206                                                                    mAnimatedImageLoading,
207                                                                    frameIndex,
208                                                                    loadTextureId,
209                                                                    mMaskingData,
210                                                                    SamplingMode::BOX_THEN_LINEAR,
211                                                                    synchronousLoading,
212                                                                    this,
213                                                                    preMultiplyOnLoading);
214   if(textureSet)
215   {
216     Sampler sampler = Sampler::New();
217     sampler.SetWrapMode(mWrapModeU, mWrapModeV);
218     textureSet.SetSampler(0u, sampler);
219   }
220
221   mTextureIds[frameIndex] = loadTextureId;
222
223   return textureSet;
224 }
225
226 void RollingAnimatedImageCache::LoadBatch(uint32_t frameIndex)
227 {
228   // Try and load up to mBatchSize images, until the cache is filled.
229   // Once the cache is filled, as frames progress, the old frame is
230   // removed, and another frame is loaded
231   uint32_t minimumSize = std::min(mCacheSize, mFrameCount);
232   for(uint32_t i = 0; i < mBatchSize && (mQueue.Count() + mLoadWaitingQueue.size()) < minimumSize; ++i)
233   {
234     if(mLoadState != TextureManager::LoadState::LOADING)
235     {
236       RequestFrameLoading(frameIndex, false);
237     }
238     else
239     {
240       mLoadWaitingQueue.push_back(frameIndex);
241     }
242
243     frameIndex++;
244     frameIndex %= mFrameCount;
245   }
246
247   LOG_CACHE;
248 }
249
250 void RollingAnimatedImageCache::SetImageFrameReady(TextureManager::TextureId textureId)
251 {
252   for(std::size_t i = 0; i < mQueue.Count(); ++i)
253   {
254     if(GetCachedTextureId(i) == textureId)
255     {
256       mQueue[i].mReady = true;
257       break;
258     }
259   }
260 }
261
262 TextureSet RollingAnimatedImageCache::GetFrontTextureSet() const
263 {
264   DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "RollingAnimatedImageCache::GetFrontTextureSet() FrameNumber:%d\n", mQueue[0].mFrameNumber);
265
266   TextureManager::TextureId textureId = GetCachedTextureId(0);
267   TextureSet textureSet = mTextureManager.GetTextureSet(textureId);
268   if(textureSet)
269   {
270     Sampler sampler = Sampler::New();
271     sampler.SetWrapMode(mWrapModeU, mWrapModeV);
272     textureSet.SetSampler(0u, sampler);
273   }
274   return textureSet;
275 }
276
277 TextureManager::TextureId RollingAnimatedImageCache::GetCachedTextureId(int index) const
278 {
279   return mTextureIds[mQueue[index].mFrameNumber];
280 }
281
282 void RollingAnimatedImageCache::PopFrontCache()
283 {
284   ImageFrame imageFrame = mQueue.PopFront();
285   mTextureManager.Remove(mTextureIds[imageFrame.mFrameNumber], this);
286   mTextureIds[imageFrame.mFrameNumber] = TextureManager::INVALID_TEXTURE_ID;
287
288   if(mMaskingData && mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID)
289   {
290     if(mQueue.IsEmpty())
291     {
292       mMaskingData->mAlphaMaskId = TextureManager::INVALID_TEXTURE_ID;
293     }
294   }
295 }
296
297 void RollingAnimatedImageCache::ClearCache()
298 {
299   while(mTextureManagerAlive && !mQueue.IsEmpty())
300   {
301     PopFrontCache();
302   }
303   mLoadWaitingQueue.clear();
304   mLoadState = TextureManager::LoadState::NOT_STARTED;
305 }
306
307 void RollingAnimatedImageCache::MakeFrameReady(bool loadSuccess, TextureSet textureSet, uint32_t interval)
308 {
309   if(!loadSuccess)
310   {
311     mLoadState = TextureManager::LoadState::LOAD_FAILED;
312     mObserver.FrameReady(TextureSet(), 0);
313   }
314   else
315   {
316     mLoadState = TextureManager::LoadState::LOAD_FINISHED;
317
318     // Reset size of Queue according to the real frame count.
319     if(mFrameCount != mAnimatedImageLoading.GetImageCount())
320     {
321       mFrameCount = mAnimatedImageLoading.GetImageCount();
322       mTextureIds.resize(mFrameCount);
323       mIntervals.assign(mFrameCount, 0u);
324     }
325
326     bool frontFrameReady = IsFrontReady();
327     // Because only one frame is on loading and the others are in mLoadWaitingQueue,
328     // mQueue.Back() is always the frame currently loaded.
329     mQueue.Back().mReady                   = true;
330     mIntervals[mQueue.Back().mFrameNumber] = interval;
331     // Check whether currently loaded frame is front of queue or not.
332     // If it is, notify frame ready to observer.
333     if(frontFrameReady == false && IsFrontReady())
334     {
335       mObserver.FrameReady(textureSet, interval);
336     }
337   }
338 }
339
340 void RollingAnimatedImageCache::LoadComplete(bool loadSuccess, TextureInformation textureInformation)
341 {
342   DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::LoadComplete(textureId:%d) start\n", textureInformation.textureId);
343   LOG_CACHE;
344
345   if(textureInformation.textureSet)
346   {
347     Sampler sampler = Sampler::New();
348     sampler.SetWrapMode(mWrapModeU, mWrapModeV);
349     textureInformation.textureSet.SetSampler(0u, sampler);
350   }
351
352   MakeFrameReady(loadSuccess, textureInformation.textureSet, textureInformation.interval);
353
354   if(loadSuccess)
355   {
356     // The frames of a single animated image can not be loaded parallelly.
357     // Therefore, a frame is now loading, other orders are waiting.
358     // And, after the frame is loaded, requests load of next order.
359     if(!mLoadWaitingQueue.empty())
360     {
361       uint32_t loadingIndex = mLoadWaitingQueue.front();
362       mLoadWaitingQueue.erase(mLoadWaitingQueue.begin());
363       RequestFrameLoading(loadingIndex, false);
364     }
365     else if(mQueue.Count() == 1u && textureInformation.frameCount > SINGLE_IMAGE_COUNT)
366     {
367       // There is only an image in queue and no waiting queue.
368       // Request to load batch once again.
369       uint32_t batchFrameIndex = 0u;
370       if(!mLoadWaitingQueue.empty())
371       {
372         batchFrameIndex = (mLoadWaitingQueue.back() + 1) % mFrameCount;
373       }
374       else
375       {
376         batchFrameIndex = (mQueue.Back().mFrameNumber + 1) % mFrameCount;
377       }
378       LoadBatch(batchFrameIndex);
379     }
380   }
381
382   LOG_CACHE;
383 }
384
385 } //namespace Internal
386 } //namespace Toolkit
387 } //namespace Dali