2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "texture-manager-impl.h"
22 #include <dali/devel-api/adaptor-framework/environment-variable.h>
23 #include <dali/devel-api/adaptor-framework/image-loading.h>
24 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/public-api/rendering/geometry.h>
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>
36 constexpr auto INITIAL_HASH_NUMBER = size_t{0u};
37 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
38 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
40 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
41 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
43 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
45 using Dali::EnvironmentVariable::GetEnvironmentVariable;
46 auto numberString = GetEnvironmentVariable(environmentVariable);
47 auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
48 constexpr auto MAX_NUMBER_OF_THREADS = 100u;
49 DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS);
50 return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
53 size_t GetNumberOfLocalLoaderThreads()
55 return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
58 size_t GetNumberOfRemoteLoaderThreads()
60 return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
72 // Define logfilter Internal namespace level so other files (e.g. texture-cache-manager.cpp) can also use this filter.
73 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXTURE_MANAGER");
76 #define GET_LOAD_STATE_STRING(loadState) \
77 loadState == TextureManagerType::LoadState::NOT_STARTED ? "NOT_STARTED" : \
78 loadState == TextureManagerType::LoadState::LOADING ? "LOADING" : \
79 loadState == TextureManagerType::LoadState::LOAD_FINISHED ? "LOAD_FINISHED" : \
80 loadState == TextureManagerType::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" : \
81 loadState == TextureManagerType::LoadState::MASK_APPLYING ? "MASK_APPLYING" : \
82 loadState == TextureManagerType::LoadState::MASK_APPLIED ? "MASK_APPLIED" : \
83 loadState == TextureManagerType::LoadState::UPLOADED ? "UPLOADED" : \
84 loadState == TextureManagerType::LoadState::CANCELLED ? "CANCELLED" : \
85 loadState == TextureManagerType::LoadState::LOAD_FAILED ? "LOAD_FAILED" : \
92 const uint32_t DEFAULT_ATLAS_SIZE(1024u); ///< This size can fit 8 by 8 images of average size 128 * 128
93 const Vector4 FULL_ATLAS_RECT(0.0f, 0.0f, 1.0f, 1.0f); ///< UV Rectangle that covers the full Texture
95 void PreMultiply(Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
97 if(Pixel::HasAlpha(pixelBuffer.GetPixelFormat()))
99 if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
101 pixelBuffer.MultiplyColorByAlpha();
106 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
110 } // Anonymous namespace
112 TextureManager::MaskingData::MaskingData()
114 mAlphaMaskId(INVALID_TEXTURE_ID),
115 mContentScaleFactor(1.0f),
120 TextureManager::TextureManager()
121 : mTextureCacheManager(),
122 mAsyncLocalLoaders(GetNumberOfLocalLoaderThreads(), [&]() { return TextureAsyncLoadingHelper(*this); }),
123 mAsyncRemoteLoaders(GetNumberOfRemoteLoaderThreads(), [&]() { return TextureAsyncLoadingHelper(*this); }),
124 mLifecycleObservers(),
127 mQueueLoadFlag(false)
129 // Initialize the AddOn
130 RenderingAddOn::Get();
133 TextureManager::~TextureManager()
135 for(auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
137 (*iter)->TextureManagerDestroyed();
141 TextureSet TextureManager::LoadAnimatedImageTexture(
142 Dali::AnimatedImageLoading animatedImageLoading,
143 const uint32_t& frameIndex,
144 TextureManager::TextureId& textureId,
145 MaskingDataPointer& maskInfo,
146 const Dali::SamplingMode::Type& samplingMode,
147 const Dali::WrapMode::Type& wrapModeU,
148 const Dali::WrapMode::Type& wrapModeV,
149 const bool& synchronousLoading,
150 const bool& useCache,
151 TextureUploadObserver* textureObserver)
153 TextureSet textureSet;
155 if(synchronousLoading)
157 Devel::PixelBuffer pixelBuffer;
158 if(animatedImageLoading)
160 pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
164 DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
168 if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
170 Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
173 pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
177 DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous mask image loading is failed\n");
180 PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
183 Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
184 texture.Upload(pixelData);
185 textureSet = TextureSet::New();
186 textureSet.SetTexture(0u, texture);
192 TextureId alphaMaskId = INVALID_TEXTURE_ID;
193 float contentScaleFactor = 1.0f;
194 bool cropToMask = false;
195 if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
197 maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl);
198 alphaMaskId = maskInfo->mAlphaMaskId;
199 contentScaleFactor = maskInfo->mContentScaleFactor;
200 cropToMask = maskInfo->mCropToMask;
203 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
204 textureId = RequestLoadInternal(animatedImageLoading.GetUrl(), alphaMaskId, contentScaleFactor, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, UseAtlas::NO_ATLAS, cropToMask, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex, false, useCache);
206 TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
207 if(loadState == TextureManager::LoadState::UPLOADED)
209 // LoadComplete has already been called - keep the same texture set
210 textureSet = GetTextureSet(textureId);
216 Sampler sampler = Sampler::New();
217 sampler.SetWrapMode(wrapModeU, wrapModeV);
218 textureSet.SetSampler(0u, sampler);
224 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
225 const VisualUrl& url,
226 const Dali::ImageDimensions& desiredSize,
227 const Dali::FittingMode::Type& fittingMode,
228 const Dali::SamplingMode::Type& samplingMode,
229 const bool& synchronousLoading,
230 TextureUploadObserver* textureObserver,
231 const bool& orientationCorrection,
232 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
234 Devel::PixelBuffer pixelBuffer;
235 if(synchronousLoading)
239 if(url.IsBufferResource())
241 const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
242 if(encodedImageBuffer)
244 pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
249 pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
251 if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
253 PreMultiply(pixelBuffer, preMultiplyOnLoad);
259 RequestLoadInternal(url, 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, false);
265 TextureSet TextureManager::LoadTexture(
266 const VisualUrl& url,
267 const Dali::ImageDimensions& desiredSize,
268 const Dali::FittingMode::Type& fittingMode,
269 const Dali::SamplingMode::Type& samplingMode,
270 MaskingDataPointer& maskInfo,
271 const bool& synchronousLoading,
272 TextureManager::TextureId& textureId,
273 Vector4& textureRect,
274 Dali::ImageDimensions& textureRectSize,
275 bool& atlasingStatus,
277 const Dali::WrapMode::Type& wrapModeU,
278 const Dali::WrapMode::Type& wrapModeV,
279 TextureUploadObserver* textureObserver,
280 AtlasUploadObserver* atlasObserver,
281 ImageAtlasManagerPtr imageAtlasManager,
282 const bool& orientationCorrection,
283 const TextureManager::ReloadPolicy& reloadPolicy,
284 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
286 TextureSet textureSet;
288 loadingStatus = false;
289 textureRect = FULL_ATLAS_RECT;
291 if(VisualUrl::TEXTURE == url.GetProtocolType())
293 std::string location = url.GetLocation();
294 if(location.size() > 0u)
296 TextureId id = std::stoi(location);
297 textureSet = mTextureCacheManager.GetExternalTextureSet(id);
300 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
309 if(synchronousLoading && atlasingStatus)
311 const bool synchronousAtlasAvaliable = (desiredSize != ImageDimensions() || url.IsLocalResource()) ? imageAtlasManager->CheckAtlasAvailable(url, desiredSize)
313 if(synchronousAtlasAvaliable)
315 Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
317 if(pixelBuffer && maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
319 Devel::PixelBuffer maskPixelBuffer = LoadImageSynchronously(maskInfo->mAlphaMaskUrl, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
322 pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
329 PreMultiply(pixelBuffer, preMultiplyOnLoad);
330 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
334 textureSet = imageAtlasManager->Add(textureRect, data);
337 textureRectSize.SetWidth(data.GetWidth());
338 textureRectSize.SetHeight(data.GetHeight());
343 DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous Texture loading with atlasing is failed.\n");
348 atlasingStatus = false;
355 loadingStatus = true;
356 // Atlas manager can chage desired size when it is set by 0,0.
357 // We should store into textureRectSize only if atlasing successed.
358 // So copy inputed desiredSize, and replace value into textureRectSize only if atlasing success.
359 Dali::ImageDimensions atlasDesiredSize = desiredSize;
362 if(url.IsBufferResource())
364 const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(url.GetUrl());
365 if(encodedImageBuffer)
367 textureSet = imageAtlasManager->Add(textureRect, encodedImageBuffer, desiredSize, fittingMode, true, atlasObserver);
372 textureSet = imageAtlasManager->Add(textureRect, url, atlasDesiredSize, fittingMode, true, atlasObserver);
375 if(!textureSet) // big image, no atlasing or atlasing failed
377 atlasingStatus = false;
378 if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
380 textureId = RequestLoad(
387 orientationCorrection,
394 maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl, synchronousLoading);
395 textureId = RequestLoad(
397 maskInfo->mAlphaMaskId,
398 maskInfo->mContentScaleFactor,
403 maskInfo->mCropToMask,
405 orientationCorrection,
411 TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
412 if(loadState == TextureManager::LoadState::UPLOADED)
414 // LoadComplete has already been called - keep the same texture set
415 textureSet = mTextureCacheManager.GetTextureSet(textureId);
418 // If we are loading the texture, or waiting for the ready signal handler to complete, inform
419 // caller that they need to wait.
420 loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
421 loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
422 loadState == TextureManager::LoadState::MASK_APPLYING ||
423 loadState == TextureManager::LoadState::MASK_APPLIED ||
424 loadState == TextureManager::LoadState::NOT_STARTED ||
429 textureRectSize = atlasDesiredSize;
434 if(!atlasingStatus && textureSet)
436 Sampler sampler = Sampler::New();
437 sampler.SetWrapMode(wrapModeU, wrapModeV);
438 textureSet.SetSampler(0u, sampler);
441 if(synchronousLoading)
443 loadingStatus = false;
449 TextureManager::TextureId TextureManager::RequestLoad(
450 const VisualUrl& url,
451 const ImageDimensions& desiredSize,
452 const Dali::FittingMode::Type& fittingMode,
453 const Dali::SamplingMode::Type& samplingMode,
454 const UseAtlas& useAtlas,
455 TextureUploadObserver* observer,
456 const bool& orientationCorrection,
457 const TextureManager::ReloadPolicy& reloadPolicy,
458 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
459 const bool& synchronousLoading)
461 return RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas, false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading, true);
464 TextureManager::TextureId TextureManager::RequestLoad(
465 const VisualUrl& url,
466 const TextureManager::TextureId& maskTextureId,
467 const float& contentScale,
468 const Dali::ImageDimensions& desiredSize,
469 const Dali::FittingMode::Type& fittingMode,
470 const Dali::SamplingMode::Type& samplingMode,
471 const TextureManager::UseAtlas& useAtlas,
472 const bool& cropToMask,
473 TextureUploadObserver* observer,
474 const bool& orientationCorrection,
475 const TextureManager::ReloadPolicy& reloadPolicy,
476 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
477 const bool& synchronousLoading)
479 return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading, true);
482 TextureManager::TextureId TextureManager::RequestMaskLoad(
483 const VisualUrl& maskUrl,
484 const bool& synchronousLoading)
486 // Use the normal load procedure to get the alpha mask.
487 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
488 return RequestLoadInternal(maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, UseAtlas::NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true, TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u, synchronousLoading, true);
491 TextureManager::TextureId TextureManager::RequestLoadInternal(
492 const VisualUrl& url,
493 const TextureManager::TextureId& maskTextureId,
494 const float& contentScale,
495 const Dali::ImageDimensions& desiredSize,
496 const Dali::FittingMode::Type& fittingMode,
497 const Dali::SamplingMode::Type& samplingMode,
498 const TextureManager::UseAtlas& useAtlas,
499 const bool& cropToMask,
500 const TextureManager::StorageType& storageType,
501 TextureUploadObserver* observer,
502 const bool& orientationCorrection,
503 const TextureManager::ReloadPolicy& reloadPolicy,
504 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
505 Dali::AnimatedImageLoading animatedImageLoading,
506 const std::uint32_t& frameIndex,
507 const bool& synchronousLoading,
508 const bool& useCache)
510 TextureHash textureHash = INITIAL_HASH_NUMBER;
511 TextureCacheIndex cacheIndex = INVALID_CACHE_INDEX;
512 if(storageType != StorageType::RETURN_PIXEL_BUFFER && useCache)
514 textureHash = mTextureCacheManager.GenerateHash(url, desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, cropToMask);
516 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
517 cacheIndex = mTextureCacheManager.FindCachedTexture(textureHash, url, desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, cropToMask, preMultiplyOnLoad, (animatedImageLoading) ? true : false);
520 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
521 // Check if the requested Texture exists in the cache.
522 if(cacheIndex != INVALID_CACHE_INDEX)
524 if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
526 // Mark this texture being used by another client resource. Forced reload would replace the current texture
527 // without the need for incrementing the reference count.
528 ++(mTextureCacheManager[cacheIndex].referenceCount);
530 textureId = mTextureCacheManager[cacheIndex].textureId;
532 // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
533 preMultiplyOnLoad = mTextureCacheManager[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
535 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d premultiplied=%d\n", url.GetUrl().c_str(), observer, cacheIndex.GetIndex(), textureId, mTextureCacheManager[cacheIndex].preMultiplied ? 1 : 0);
538 if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
540 textureId = mTextureCacheManager.GenerateTextureId();
542 bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
544 // Cache new texutre, and get cacheIndex.
545 cacheIndex = mTextureCacheManager.AppendCache(TextureInfo(textureId, maskTextureId, url, desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
547 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex.GetIndex(), textureId);
550 // The below code path is common whether we are using the cache or not.
551 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
552 // or a new TextureInfo just created.
553 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
554 textureInfo.maskTextureId = maskTextureId;
555 textureInfo.storageType = storageType;
556 textureInfo.orientationCorrection = orientationCorrection;
558 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
560 // Force reloading of texture by setting loadState unless already loading or cancelled.
561 if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
562 TextureManager::LoadState::LOADING != textureInfo.loadState &&
563 TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
564 TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
565 TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
566 TextureManager::LoadState::CANCELLED != textureInfo.loadState)
568 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex.GetIndex(), textureId);
570 textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
573 if(!synchronousLoading)
575 // Check if we should add the observer.
576 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
577 switch(textureInfo.loadState)
579 case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
580 case TextureManager::LoadState::NOT_STARTED:
582 LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
585 case TextureManager::LoadState::LOADING:
586 case TextureManager::LoadState::WAITING_FOR_MASK:
587 case TextureManager::LoadState::MASK_APPLYING:
588 case TextureManager::LoadState::MASK_APPLIED:
590 ObserveTexture(textureInfo, observer);
593 case TextureManager::LoadState::UPLOADED:
597 LoadOrQueueTexture(textureInfo, observer);
601 case TextureManager::LoadState::CANCELLED:
603 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
604 // (it's ref count has already been incremented, above)
605 textureInfo.loadState = TextureManager::LoadState::LOADING;
606 ObserveTexture(textureInfo, observer);
609 case TextureManager::LoadState::LOAD_FINISHED:
611 // Loading has already completed.
612 if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
614 LoadOrQueueTexture(textureInfo, observer);
622 // If the image is already finished to load, use cached texture.
623 // We don't need to consider Observer because this is synchronous loading.
624 if(!(textureInfo.loadState == TextureManager::LoadState::UPLOADED ||
625 textureInfo.loadState == TextureManager::LoadState::LOAD_FINISHED))
627 Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
631 // If pixelBuffer loading is failed in synchronously, call Remove() method.
632 Remove(textureId, nullptr);
633 return INVALID_TEXTURE_ID;
636 if(storageType == StorageType::KEEP_PIXEL_BUFFER) // For the mask image loading.
638 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
639 textureInfo.loadState = LoadState::LOAD_FINISHED;
641 else // For the image loading.
643 if(maskTextureId != INVALID_TEXTURE_ID)
645 TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
646 if(maskCacheIndex != INVALID_CACHE_INDEX)
648 Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
651 pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask);
655 DALI_LOG_ERROR("Mask image cached invalid pixel buffer!\n");
660 DALI_LOG_ERROR("Mask image is not stored in cache.\n");
663 PreMultiply(pixelBuffer, preMultiplyOnLoad);
666 UploadTexture(pixelBuffer, textureInfo);
673 void TextureManager::Remove(const TextureManager::TextureId& textureId, TextureUploadObserver* observer)
675 if(textureId != INVALID_TEXTURE_ID)
679 // Remove textureId after NotifyObserver finished
680 mRemoveQueue.PushBack(textureId);
684 // Remove textureId in CacheManager.
685 mTextureCacheManager.RemoveCache(textureId);
690 // Remove element from the LoadQueue
691 for(auto&& element : mLoadQueue)
693 if(element.mObserver == observer)
695 // Do not erase the item. We will clear it later in ProcessLoadQueue().
696 element.mObserver = nullptr;
704 Devel::PixelBuffer TextureManager::LoadImageSynchronously(
705 const VisualUrl& url,
706 const Dali::ImageDimensions& desiredSize,
707 const Dali::FittingMode::Type& fittingMode,
708 const Dali::SamplingMode::Type& samplingMode,
709 const bool& orientationCorrection)
711 Devel::PixelBuffer pixelBuffer;
712 if(url.IsBufferResource())
714 const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
715 if(encodedImageBuffer)
717 pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
722 pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
727 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
729 // make sure an observer doesn't observe the same object twice
730 // otherwise it will get multiple calls to ObjectDestroyed()
731 DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
732 mLifecycleObservers.PushBack(&observer);
735 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
737 // Find the observer...
738 auto endIter = mLifecycleObservers.End();
739 for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
741 if((*iter) == &observer)
743 mLifecycleObservers.Erase(iter);
747 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
750 void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
752 switch(textureInfo.loadState)
754 case LoadState::NOT_STARTED:
755 case LoadState::LOAD_FAILED:
759 QueueLoadTexture(textureInfo, observer);
763 LoadTexture(textureInfo, observer);
767 case LoadState::UPLOADED:
771 QueueLoadTexture(textureInfo, observer);
775 // The Texture has already loaded. The other observers have already been notified.
776 // We need to send a "late" loaded notification for this observer.
777 EmitLoadComplete(observer, textureInfo, true);
781 case LoadState::LOADING:
782 case LoadState::CANCELLED:
783 case LoadState::LOAD_FINISHED:
784 case LoadState::WAITING_FOR_MASK:
785 case LoadState::MASK_APPLYING:
786 case LoadState::MASK_APPLIED:
793 void TextureManager::QueueLoadTexture(const TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
795 const auto& textureId = textureInfo.textureId;
796 mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
798 observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
801 void TextureManager::LoadTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
803 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
805 textureInfo.loadState = LoadState::LOADING;
806 if(!textureInfo.loadSynchronously)
808 auto& loadersContainer = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
809 auto loadingHelperIt = loadersContainer.GetNext();
810 auto premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
811 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
812 if(textureInfo.animatedImageLoading)
814 loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex);
818 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
821 ObserveTexture(textureInfo, observer);
824 void TextureManager::ProcessLoadQueue()
826 for(auto&& element : mLoadQueue)
828 if(!element.mObserver)
833 TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(element.mTextureId);
834 if(cacheIndex != INVALID_CACHE_INDEX)
836 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
837 if((textureInfo.loadState == LoadState::UPLOADED) || (textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER))
839 EmitLoadComplete(element.mObserver, textureInfo, true);
843 LoadTexture(textureInfo, element.mObserver);
850 void TextureManager::ProcessRemoveQueue()
852 for(const auto& textureId : mRemoveQueue)
854 mTextureCacheManager.RemoveCache(textureId);
856 mRemoveQueue.Clear();
859 void TextureManager::ObserveTexture(TextureManager::TextureInfo& textureInfo,
860 TextureUploadObserver* observer)
862 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
866 textureInfo.observerList.PushBack(observer);
867 observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
871 void TextureManager::AsyncLoadComplete(const TextureManager::TextureId& textureId, Devel::PixelBuffer pixelBuffer)
873 TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
874 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( textureId:%d CacheIndex:%d )\n", textureId, cacheIndex.GetIndex());
875 if(cacheIndex != INVALID_CACHE_INDEX)
877 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
879 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));
881 if(textureInfo.loadState != LoadState::CANCELLED)
883 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
884 PostLoad(textureInfo, pixelBuffer);
888 Remove(textureInfo.textureId, nullptr);
893 void TextureManager::PostLoad(TextureManager::TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
895 // Was the load successful?
896 if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
898 // No atlas support for now
899 textureInfo.useAtlas = UseAtlas::NO_ATLAS;
900 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
902 if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
904 // If there is a mask texture ID associated with this texture, then apply the mask
905 // if it's already loaded. If it hasn't, and the mask is still loading,
906 // wait for the mask to finish loading.
907 // note, If the texture is already uploaded synchronously during loading,
908 // we don't need to apply mask.
909 if(textureInfo.loadState != LoadState::UPLOADED &&
910 textureInfo.maskTextureId != INVALID_TEXTURE_ID)
912 if(textureInfo.loadState == LoadState::MASK_APPLYING)
914 textureInfo.loadState = LoadState::MASK_APPLIED;
915 UploadTexture(pixelBuffer, textureInfo);
916 NotifyObservers(textureInfo, true);
920 LoadState maskLoadState = mTextureCacheManager.GetTextureStateInternal(textureInfo.maskTextureId);
921 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
922 if(maskLoadState == LoadState::LOADING)
924 textureInfo.loadState = LoadState::WAITING_FOR_MASK;
926 else if(maskLoadState == LoadState::LOAD_FINISHED)
928 // Send New Task to Thread
929 ApplyMask(textureInfo, textureInfo.maskTextureId);
931 else // maskLoadState == LoadState::LOAD_FAILED
933 // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
934 DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
935 UploadTexture(pixelBuffer, textureInfo);
936 NotifyObservers(textureInfo, true);
942 UploadTexture(pixelBuffer, textureInfo);
943 NotifyObservers(textureInfo, true);
948 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
949 textureInfo.loadState = LoadState::LOAD_FINISHED;
951 if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
953 NotifyObservers(textureInfo, true);
957 // Check if there was another texture waiting for this load to complete
958 // (e.g. if this was an image mask, and its load is on a different thread)
959 CheckForWaitingTexture(textureInfo);
965 textureInfo.loadState = LoadState::LOAD_FAILED;
966 if(textureInfo.storageType != StorageType::KEEP_PIXEL_BUFFER)
968 NotifyObservers(textureInfo, false);
970 else // if(textureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER) // image mask case
972 // Check if there was another texture waiting for this load to complete
973 // (e.g. if this was an image mask, and its load is on a different thread)
974 CheckForWaitingTexture(textureInfo);
979 void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTextureInfo)
981 // Search the cache, checking if any texture has this texture id as a
983 const std::size_t size = mTextureCacheManager.size();
985 const bool maskLoadSuccess = maskTextureInfo.loadState == LoadState::LOAD_FINISHED ? true : false;
987 // TODO : Refactorize here to not iterate whole cached image.
988 for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
990 if(mTextureCacheManager[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
991 mTextureCacheManager[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
993 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
997 // Send New Task to Thread
998 ApplyMask(textureInfo, maskTextureInfo.textureId);
1002 // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
1003 DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
1004 UploadTexture(textureInfo.pixelBuffer, textureInfo);
1005 NotifyObservers(textureInfo, true);
1011 void TextureManager::ApplyMask(TextureManager::TextureInfo& textureInfo, const TextureManager::TextureId& maskTextureId)
1013 TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
1014 if(maskCacheIndex != INVALID_CACHE_INDEX)
1016 Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
1017 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
1018 textureInfo.pixelBuffer.Reset();
1020 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
1022 textureInfo.loadState = LoadState::MASK_APPLYING;
1023 auto& loadersContainer = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1024 auto loadingHelperIt = loadersContainer.GetNext();
1025 auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1026 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1027 loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
1031 void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureManager::TextureInfo& textureInfo)
1033 if(textureInfo.loadState != LoadState::UPLOADED && textureInfo.useAtlas != UseAtlas::USE_ATLAS)
1035 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
1037 // Check if this pixelBuffer is premultiplied
1038 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1040 auto& renderingAddOn = RenderingAddOn::Get();
1041 if(renderingAddOn.IsValid())
1043 renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
1046 Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1048 PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1049 texture.Upload(pixelData);
1050 if(!textureInfo.textureSet)
1052 textureInfo.textureSet = TextureSet::New();
1054 textureInfo.textureSet.SetTexture(0u, texture);
1057 // Update the load state.
1058 // Note: This is regardless of success as we care about whether a
1059 // load attempt is in progress or not. If unsuccessful, a broken
1060 // image is still loaded.
1061 textureInfo.loadState = LoadState::UPLOADED;
1064 void TextureManager::NotifyObservers(TextureManager::TextureInfo& textureInfo, const bool& success)
1066 TextureId textureId = textureInfo.textureId;
1068 // If there is an observer: Notify the load is complete, whether successful or not,
1069 // and erase it from the list
1070 TextureInfo* info = &textureInfo;
1072 if(info->animatedImageLoading)
1074 // If loading failed, we don't need to get frameCount and frameInterval.
1077 info->frameCount = info->animatedImageLoading.GetImageCount();
1078 info->frameInterval = info->animatedImageLoading.GetFrameInterval(info->frameIndex);
1080 info->animatedImageLoading.Reset();
1083 mQueueLoadFlag = true;
1085 while(info->observerList.Count())
1087 TextureUploadObserver* observer = info->observerList[0];
1089 // During LoadComplete() a Control ResourceReady() signal is emitted.
1090 // During that signal the app may add remove /add Textures (e.g. via
1092 // It is possible for observers to be removed from the observer list,
1093 // and it is also possible for the mTextureInfoContainer to be modified,
1094 // invalidating the reference to the textureInfo struct.
1095 // Texture load requests for the same URL are deferred until the end of this
1097 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::NotifyObservers() textureId:%d url:%s loadState:%s\n", textureId, info->url.GetUrl().c_str(), GET_LOAD_STATE_STRING(info->loadState));
1099 // It is possible for the observer to be deleted.
1100 // Disconnect and remove the observer first.
1101 observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1103 info->observerList.Erase(info->observerList.Begin());
1105 EmitLoadComplete(observer, *info, success);
1107 // Get the textureInfo from the container again as it may have been invalidated.
1108 TextureCacheIndex textureInfoIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1109 if(textureInfoIndex == INVALID_CACHE_INDEX)
1111 break; // texture has been removed - can stop.
1113 info = &mTextureCacheManager[textureInfoIndex];
1116 mQueueLoadFlag = false;
1118 ProcessRemoveQueue();
1120 if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1122 Remove(info->textureId, nullptr);
1126 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1128 const std::size_t size = mTextureCacheManager.size();
1129 for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
1131 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
1132 for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1133 j != textureInfo.observerList.End();)
1137 j = textureInfo.observerList.Erase(j);
1146 // Remove element from the LoadQueue
1147 for(auto&& element : mLoadQueue)
1149 if(element.mObserver == observer)
1151 element.mObserver = nullptr;
1156 Dali::Geometry TextureManager::GetRenderGeometry(const TextureManager::TextureId& textureId, std::uint32_t& frontElements, std::uint32_t& backElements)
1158 return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1161 void TextureManager::EmitLoadComplete(TextureUploadObserver* observer, TextureManager::TextureInfo& textureInfo, const bool& success)
1163 if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1165 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, textureInfo.pixelBuffer, textureInfo.url.GetUrl(), textureInfo.preMultiplied));
1167 else if(textureInfo.isAnimatedImageFormat)
1169 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::ANIMATED_IMAGE_TEXTURE, textureInfo.textureId, textureInfo.frameCount, textureInfo.frameInterval));
1173 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureInfo.textureSet, (textureInfo.useAtlas == UseAtlas::USE_ATLAS) ? true : false, textureInfo.atlasRect, textureInfo.preMultiplied));
1177 } // namespace Internal
1179 } // namespace Toolkit