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