Merge "Remove useless iteration when debug mode" 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                                                      bool                                isSynchronousLoading,
70                                                      bool                                preMultiplyOnLoad)
71 : ImageCache(textureManager, maskingData, observer, batchSize, 0u),
72   mImageUrl(animatedImageLoading.GetUrl()),
73   mAnimatedImageLoading(animatedImageLoading),
74   mFrameCount(SINGLE_IMAGE_COUNT),
75   mFrameIndex(FIRST_FRAME_INDEX),
76   mCacheSize(cacheSize),
77   mQueue(cacheSize),
78   mIsSynchronousLoading(isSynchronousLoading),
79   mPreMultiplyOnLoad(preMultiplyOnLoad)
80 {
81   mTextureIds.resize(mFrameCount);
82   mIntervals.assign(mFrameCount, 0);
83 }
84
85 RollingAnimatedImageCache::~RollingAnimatedImageCache()
86 {
87   ClearCache();
88   mAnimatedImageLoading.Reset();
89 }
90
91 TextureSet RollingAnimatedImageCache::Frame(uint32_t frameIndex)
92 {
93   bool popExist = false;
94   while(!mQueue.IsEmpty() && mQueue.Front().mFrameNumber != frameIndex)
95   {
96     PopFrontCache();
97     popExist = true;
98   }
99
100   TextureSet textureSet;
101   uint32_t   batchFrameIndex = frameIndex;
102   // If we need to load new frame that are not stored in queue.
103   // Load the frame synchronously.
104   bool synchronouslyLoaded = false;
105   if(mIsSynchronousLoading && mQueue.IsEmpty())
106   {
107     textureSet        = RequestFrameLoading(frameIndex, true);
108     batchFrameIndex   = (frameIndex + 1) % mFrameCount;
109     uint32_t interval = 0u;
110     if(textureSet)
111     {
112       synchronouslyLoaded = true;
113       interval            = mAnimatedImageLoading.GetFrameInterval(mQueue.Back().mFrameNumber);
114     }
115     MakeFrameReady(synchronouslyLoaded, textureSet, interval);
116   }
117
118   if(popExist || mQueue.IsEmpty() || synchronouslyLoaded)
119   {
120     // If the frame of frameIndex was already loaded, load batch from the last frame of queue
121     if(!mQueue.IsEmpty())
122     {
123       if(!mLoadWaitingQueue.empty())
124       {
125         batchFrameIndex = (mLoadWaitingQueue.back() + 1) % mFrameCount;
126       }
127       else
128       {
129         batchFrameIndex = (mQueue.Back().mFrameNumber + 1) % mFrameCount;
130       }
131     }
132     else
133     {
134       // If the request is for the first frame or a jumped frame(JUMP_TO) remove current waiting queue.
135       mLoadWaitingQueue.clear();
136       // If the queue is empty, and the frame of frameIndex is not loaded synchronously. load batch from the frame of frameIndex
137       if(!textureSet)
138       {
139         batchFrameIndex = frameIndex;
140       }
141     }
142     LoadBatch(batchFrameIndex);
143   }
144
145   if(!textureSet && mLoadState != TextureManager::LoadState::LOAD_FAILED && IsFrontReady() == true)
146   {
147     textureSet = GetFrontTextureSet();
148   }
149
150   return textureSet;
151 }
152
153 TextureSet RollingAnimatedImageCache::FirstFrame()
154 {
155   TextureSet textureSet = Frame(FIRST_FRAME_INDEX);
156   return textureSet;
157 }
158
159 uint32_t RollingAnimatedImageCache::GetFrameInterval(uint32_t frameIndex) const
160 {
161   if(frameIndex >= mIntervals.size())
162   {
163     return 0u;
164   }
165   return mIntervals[frameIndex];
166 }
167
168 int32_t RollingAnimatedImageCache::GetCurrentFrameIndex() const
169 {
170   if(mQueue.IsEmpty())
171   {
172     return -1;
173   }
174   return mQueue.Front().mFrameNumber;
175 }
176
177 int32_t RollingAnimatedImageCache::GetTotalFrameCount() const
178 {
179   return mFrameCount;
180 }
181
182 bool RollingAnimatedImageCache::IsFrontReady() const
183 {
184   return (!mQueue.IsEmpty() && mQueue.Front().mReady);
185 }
186
187 TextureSet RollingAnimatedImageCache::RequestFrameLoading(uint32_t frameIndex, bool synchronousLoading)
188 {
189   ImageFrame imageFrame;
190   imageFrame.mFrameNumber = frameIndex;
191   imageFrame.mReady       = false;
192
193   mQueue.PushBack(imageFrame);
194
195   mLoadState = TextureManager::LoadState::LOADING;
196
197   auto preMultiplyOnLoading = mPreMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD
198                                                  : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
199
200   TextureManager::TextureId loadTextureId = TextureManager::INVALID_TEXTURE_ID;
201   TextureSet                textureSet    = mTextureManager.LoadAnimatedImageTexture(mImageUrl,
202                                                                    mAnimatedImageLoading,
203                                                                    frameIndex,
204                                                                    loadTextureId,
205                                                                    mMaskingData,
206                                                                    SamplingMode::BOX_THEN_LINEAR,
207                                                                    Dali::WrapMode::Type::DEFAULT,
208                                                                    Dali::WrapMode::Type::DEFAULT,
209                                                                    synchronousLoading,
210                                                                    this,
211                                                                    preMultiplyOnLoading);
212
213   mTextureIds[frameIndex] = loadTextureId;
214
215   return textureSet;
216 }
217
218 void RollingAnimatedImageCache::LoadBatch(uint32_t frameIndex)
219 {
220   // Try and load up to mBatchSize images, until the cache is filled.
221   // Once the cache is filled, as frames progress, the old frame is
222   // removed, and another frame is loaded
223   uint32_t minimumSize = std::min(mCacheSize, mFrameCount);
224   for(uint32_t i = 0; i < mBatchSize && (mQueue.Count() + mLoadWaitingQueue.size()) < minimumSize; ++i)
225   {
226     if(mLoadState != TextureManager::LoadState::LOADING)
227     {
228       RequestFrameLoading(frameIndex, false);
229     }
230     else
231     {
232       mLoadWaitingQueue.push_back(frameIndex);
233     }
234
235     frameIndex++;
236     frameIndex %= mFrameCount;
237   }
238
239   LOG_CACHE;
240 }
241
242 void RollingAnimatedImageCache::SetImageFrameReady(TextureManager::TextureId textureId)
243 {
244   for(std::size_t i = 0; i < mQueue.Count(); ++i)
245   {
246     if(GetCachedTextureId(i) == textureId)
247     {
248       mQueue[i].mReady = true;
249       break;
250     }
251   }
252 }
253
254 TextureSet RollingAnimatedImageCache::GetFrontTextureSet() const
255 {
256   DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "RollingAnimatedImageCache::GetFrontTextureSet() FrameNumber:%d\n", mQueue[0].mFrameNumber);
257
258   TextureManager::TextureId textureId = GetCachedTextureId(0);
259   return mTextureManager.GetTextureSet(textureId);
260 }
261
262 TextureManager::TextureId RollingAnimatedImageCache::GetCachedTextureId(int index) const
263 {
264   return mTextureIds[mQueue[index].mFrameNumber];
265 }
266
267 void RollingAnimatedImageCache::PopFrontCache()
268 {
269   ImageFrame imageFrame = mQueue.PopFront();
270   mTextureManager.Remove(mTextureIds[imageFrame.mFrameNumber], this);
271   mTextureIds[imageFrame.mFrameNumber] = TextureManager::INVALID_TEXTURE_ID;
272
273   if(mMaskingData && mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID)
274   {
275     mTextureManager.Remove(mMaskingData->mAlphaMaskId, this);
276     if(mQueue.IsEmpty())
277     {
278       mMaskingData->mAlphaMaskId = TextureManager::INVALID_TEXTURE_ID;
279     }
280   }
281 }
282
283 void RollingAnimatedImageCache::ClearCache()
284 {
285   while(mTextureManagerAlive && !mQueue.IsEmpty())
286   {
287     PopFrontCache();
288   }
289   mLoadWaitingQueue.clear();
290   mLoadState = TextureManager::LoadState::NOT_STARTED;
291 }
292
293 void RollingAnimatedImageCache::MakeFrameReady(bool loadSuccess, TextureSet textureSet, uint32_t interval)
294 {
295   if(!loadSuccess)
296   {
297     mLoadState = TextureManager::LoadState::LOAD_FAILED;
298     mObserver.FrameReady(TextureSet(), 0);
299   }
300   else
301   {
302     mLoadState = TextureManager::LoadState::LOAD_FINISHED;
303
304     // Reset size of Queue according to the real frame count.
305     if(mFrameCount != mAnimatedImageLoading.GetImageCount())
306     {
307       mFrameCount = mAnimatedImageLoading.GetImageCount();
308       mTextureIds.resize(mFrameCount);
309       mIntervals.assign(mFrameCount, 0u);
310     }
311
312     bool frontFrameReady = IsFrontReady();
313     // Because only one frame is on loading and the others are in mLoadWaitingQueue,
314     // mQueue.Back() is always the frame currently loaded.
315     mQueue.Back().mReady                   = true;
316     mIntervals[mQueue.Back().mFrameNumber] = interval;
317     // Check whether currently loaded frame is front of queue or not.
318     // If it is, notify frame ready to observer.
319     if(frontFrameReady == false && IsFrontReady())
320     {
321       mObserver.FrameReady(textureSet, interval);
322     }
323   }
324 }
325
326 void RollingAnimatedImageCache::LoadComplete(bool loadSuccess, TextureInformation textureInformation)
327 {
328   DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::LoadComplete(textureId:%d) start\n", textureInformation.textureId);
329   LOG_CACHE;
330
331   MakeFrameReady(loadSuccess, mTextureManager.GetTextureSet(textureInformation.textureId), textureInformation.interval);
332
333   if(loadSuccess)
334   {
335     // The frames of a single animated image can not be loaded parallelly.
336     // Therefore, a frame is now loading, other orders are waiting.
337     // And, after the frame is loaded, requests load of next order.
338     if(!mLoadWaitingQueue.empty())
339     {
340       uint32_t loadingIndex = mLoadWaitingQueue.front();
341       mLoadWaitingQueue.erase(mLoadWaitingQueue.begin());
342       RequestFrameLoading(loadingIndex, false);
343     }
344     else if(mQueue.Count() == 1u && textureInformation.frameCount > SINGLE_IMAGE_COUNT)
345     {
346       // There is only an image in queue and no waiting queue.
347       // Request to load batch once again.
348       uint32_t batchFrameIndex = 0u;
349       if(!mLoadWaitingQueue.empty())
350       {
351         batchFrameIndex = (mLoadWaitingQueue.back() + 1) % mFrameCount;
352       }
353       else
354       {
355         batchFrameIndex = (mQueue.Back().mFrameNumber + 1) % mFrameCount;
356       }
357       LoadBatch(batchFrameIndex);
358     }
359   }
360
361   LOG_CACHE;
362 }
363
364 } //namespace Internal
365 } //namespace Toolkit
366 } //namespace Dali