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