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 TextureUploadObserver* textureObserver)
152 TextureSet textureSet;
154 if(synchronousLoading)
156 Devel::PixelBuffer pixelBuffer;
157 if(animatedImageLoading)
159 pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
163 DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
167 if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
169 Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
172 pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
176 DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous mask image loading is failed\n");
179 PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
182 Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
183 texture.Upload(pixelData);
184 textureSet = TextureSet::New();
185 textureSet.SetTexture(0u, texture);
191 TextureId alphaMaskId = INVALID_TEXTURE_ID;
192 float contentScaleFactor = 1.0f;
193 bool cropToMask = false;
194 if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
196 maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl);
197 alphaMaskId = maskInfo->mAlphaMaskId;
198 contentScaleFactor = maskInfo->mContentScaleFactor;
199 cropToMask = maskInfo->mCropToMask;
202 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
203 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);
205 TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
206 if(loadState == TextureManager::LoadState::UPLOADED)
208 // LoadComplete has already been called - keep the same texture set
209 textureSet = GetTextureSet(textureId);
215 Sampler sampler = Sampler::New();
216 sampler.SetWrapMode(wrapModeU, wrapModeV);
217 textureSet.SetSampler(0u, sampler);
223 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
224 const VisualUrl& url,
225 const Dali::ImageDimensions& desiredSize,
226 const Dali::FittingMode::Type& fittingMode,
227 const Dali::SamplingMode::Type& samplingMode,
228 const bool& synchronousLoading,
229 TextureUploadObserver* textureObserver,
230 const bool& orientationCorrection,
231 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
233 Devel::PixelBuffer pixelBuffer;
234 if(synchronousLoading)
238 if(url.IsBufferResource())
240 const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
241 if(encodedImageBuffer)
243 pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
248 pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
250 if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
252 PreMultiply(pixelBuffer, preMultiplyOnLoad);
258 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);
264 TextureSet TextureManager::LoadTexture(
265 const VisualUrl& url,
266 const Dali::ImageDimensions& desiredSize,
267 const Dali::FittingMode::Type& fittingMode,
268 const Dali::SamplingMode::Type& samplingMode,
269 MaskingDataPointer& maskInfo,
270 const bool& synchronousLoading,
271 TextureManager::TextureId& textureId,
272 Vector4& textureRect,
273 Dali::ImageDimensions& textureRectSize,
274 bool& atlasingStatus,
276 const Dali::WrapMode::Type& wrapModeU,
277 const Dali::WrapMode::Type& wrapModeV,
278 TextureUploadObserver* textureObserver,
279 AtlasUploadObserver* atlasObserver,
280 ImageAtlasManagerPtr imageAtlasManager,
281 const bool& orientationCorrection,
282 const TextureManager::ReloadPolicy& reloadPolicy,
283 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
285 TextureSet textureSet;
287 loadingStatus = false;
288 textureRect = FULL_ATLAS_RECT;
290 if(VisualUrl::TEXTURE == url.GetProtocolType())
292 std::string location = url.GetLocation();
293 if(location.size() > 0u)
295 TextureId id = std::stoi(location);
296 textureSet = mTextureCacheManager.GetExternalTextureSet(id);
299 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
308 if(synchronousLoading && atlasingStatus)
310 const bool synchronousAtlasAvaliable = (desiredSize != ImageDimensions() || url.IsLocalResource()) ? imageAtlasManager->CheckAtlasAvailable(url, desiredSize)
312 if(synchronousAtlasAvaliable)
314 Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
316 if(pixelBuffer && maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
318 Devel::PixelBuffer maskPixelBuffer = LoadImageSynchronously(maskInfo->mAlphaMaskUrl, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
321 pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
328 PreMultiply(pixelBuffer, preMultiplyOnLoad);
329 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
333 textureSet = imageAtlasManager->Add(textureRect, data);
336 textureRectSize.SetWidth(data.GetWidth());
337 textureRectSize.SetHeight(data.GetHeight());
342 DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous Texture loading with atlasing is failed.\n");
347 atlasingStatus = false;
354 loadingStatus = true;
355 // Atlas manager can chage desired size when it is set by 0,0.
356 // We should store into textureRectSize only if atlasing successed.
357 // So copy inputed desiredSize, and replace value into textureRectSize only if atlasing success.
358 Dali::ImageDimensions atlasDesiredSize = desiredSize;
361 if(url.IsBufferResource())
363 const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(url.GetUrl());
364 if(encodedImageBuffer)
366 textureSet = imageAtlasManager->Add(textureRect, encodedImageBuffer, desiredSize, fittingMode, true, atlasObserver);
371 textureSet = imageAtlasManager->Add(textureRect, url, atlasDesiredSize, fittingMode, true, atlasObserver);
374 if(!textureSet) // big image, no atlasing or atlasing failed
376 atlasingStatus = false;
377 if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
379 textureId = RequestLoad(
386 orientationCorrection,
393 maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl, synchronousLoading);
394 textureId = RequestLoad(
396 maskInfo->mAlphaMaskId,
397 maskInfo->mContentScaleFactor,
402 maskInfo->mCropToMask,
404 orientationCorrection,
410 TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
411 if(loadState == TextureManager::LoadState::UPLOADED)
413 // LoadComplete has already been called - keep the same texture set
414 textureSet = mTextureCacheManager.GetTextureSet(textureId);
417 // If we are loading the texture, or waiting for the ready signal handler to complete, inform
418 // caller that they need to wait.
419 loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
420 loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
421 loadState == TextureManager::LoadState::MASK_APPLYING ||
422 loadState == TextureManager::LoadState::MASK_APPLIED ||
423 loadState == TextureManager::LoadState::NOT_STARTED ||
428 textureRectSize = atlasDesiredSize;
433 if(!atlasingStatus && textureSet)
435 Sampler sampler = Sampler::New();
436 sampler.SetWrapMode(wrapModeU, wrapModeV);
437 textureSet.SetSampler(0u, sampler);
440 if(synchronousLoading)
442 loadingStatus = false;
448 TextureManager::TextureId TextureManager::RequestLoad(
449 const VisualUrl& url,
450 const ImageDimensions& desiredSize,
451 const Dali::FittingMode::Type& fittingMode,
452 const Dali::SamplingMode::Type& samplingMode,
453 const UseAtlas& useAtlas,
454 TextureUploadObserver* observer,
455 const bool& orientationCorrection,
456 const TextureManager::ReloadPolicy& reloadPolicy,
457 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
458 const bool& synchronousLoading)
460 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);
463 TextureManager::TextureId TextureManager::RequestLoad(
464 const VisualUrl& url,
465 const TextureManager::TextureId& maskTextureId,
466 const float& contentScale,
467 const Dali::ImageDimensions& desiredSize,
468 const Dali::FittingMode::Type& fittingMode,
469 const Dali::SamplingMode::Type& samplingMode,
470 const TextureManager::UseAtlas& useAtlas,
471 const bool& cropToMask,
472 TextureUploadObserver* observer,
473 const bool& orientationCorrection,
474 const TextureManager::ReloadPolicy& reloadPolicy,
475 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
476 const bool& synchronousLoading)
478 return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading);
481 TextureManager::TextureId TextureManager::RequestMaskLoad(
482 const VisualUrl& maskUrl,
483 const bool& synchronousLoading)
485 // Use the normal load procedure to get the alpha mask.
486 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
487 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);
490 TextureManager::TextureId TextureManager::RequestLoadInternal(
491 const VisualUrl& url,
492 const TextureManager::TextureId& maskTextureId,
493 const float& contentScale,
494 const Dali::ImageDimensions& desiredSize,
495 const Dali::FittingMode::Type& fittingMode,
496 const Dali::SamplingMode::Type& samplingMode,
497 const TextureManager::UseAtlas& useAtlas,
498 const bool& cropToMask,
499 const TextureManager::StorageType& storageType,
500 TextureUploadObserver* observer,
501 const bool& orientationCorrection,
502 const TextureManager::ReloadPolicy& reloadPolicy,
503 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
504 Dali::AnimatedImageLoading animatedImageLoading,
505 const std::uint32_t& frameIndex,
506 const bool& synchronousLoading)
508 TextureHash textureHash = INITIAL_HASH_NUMBER;
509 TextureCacheIndex cacheIndex = INVALID_CACHE_INDEX;
510 if(storageType != StorageType::RETURN_PIXEL_BUFFER)
512 textureHash = mTextureCacheManager.GenerateHash(url, desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, cropToMask, frameIndex);
514 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
515 cacheIndex = mTextureCacheManager.FindCachedTexture(textureHash, url, desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, cropToMask, preMultiplyOnLoad, (animatedImageLoading) ? true : false, frameIndex);
518 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
519 // Check if the requested Texture exists in the cache.
520 if(cacheIndex != INVALID_CACHE_INDEX)
522 if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
524 // Mark this texture being used by another client resource. Forced reload would replace the current texture
525 // without the need for incrementing the reference count.
526 ++(mTextureCacheManager[cacheIndex].referenceCount);
528 textureId = mTextureCacheManager[cacheIndex].textureId;
530 // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
531 preMultiplyOnLoad = mTextureCacheManager[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
533 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d, frameindex=%d, premultiplied=%d\n", url.GetUrl().c_str(), observer, cacheIndex.GetIndex(), textureId, frameIndex, mTextureCacheManager[cacheIndex].preMultiplied ? 1 : 0);
536 if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
538 textureId = mTextureCacheManager.GenerateTextureId();
540 bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
542 // Cache new texutre, and get cacheIndex.
543 cacheIndex = mTextureCacheManager.AppendCache(TextureInfo(textureId, maskTextureId, url, desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
545 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d, frameindex=%d\n", url.GetUrl().c_str(), observer, cacheIndex.GetIndex(), textureId, frameIndex);
548 // The below code path is common whether we are using the cache or not.
549 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
550 // or a new TextureInfo just created.
551 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
552 textureInfo.maskTextureId = maskTextureId;
553 textureInfo.storageType = storageType;
554 textureInfo.orientationCorrection = orientationCorrection;
556 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
558 // Force reloading of texture by setting loadState unless already loading or cancelled.
559 if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
560 TextureManager::LoadState::LOADING != textureInfo.loadState &&
561 TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
562 TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
563 TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
564 TextureManager::LoadState::CANCELLED != textureInfo.loadState)
566 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);
568 textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
571 if(!synchronousLoading)
573 // Check if we should add the observer.
574 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
575 switch(textureInfo.loadState)
577 case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
578 case TextureManager::LoadState::NOT_STARTED:
580 LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
583 case TextureManager::LoadState::LOADING:
584 case TextureManager::LoadState::WAITING_FOR_MASK:
585 case TextureManager::LoadState::MASK_APPLYING:
586 case TextureManager::LoadState::MASK_APPLIED:
588 ObserveTexture(textureInfo, observer);
591 case TextureManager::LoadState::UPLOADED:
595 LoadOrQueueTexture(textureInfo, observer);
599 case TextureManager::LoadState::CANCELLED:
601 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
602 // (it's ref count has already been incremented, above)
603 textureInfo.loadState = TextureManager::LoadState::LOADING;
604 ObserveTexture(textureInfo, observer);
607 case TextureManager::LoadState::LOAD_FINISHED:
609 // Loading has already completed.
610 if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
612 LoadOrQueueTexture(textureInfo, observer);
620 // If the image is already finished to load, use cached texture.
621 // We don't need to consider Observer because this is synchronous loading.
622 if(!(textureInfo.loadState == TextureManager::LoadState::UPLOADED ||
623 textureInfo.loadState == TextureManager::LoadState::LOAD_FINISHED))
625 Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
629 // If pixelBuffer loading is failed in synchronously, call Remove() method.
630 Remove(textureId, nullptr);
631 return INVALID_TEXTURE_ID;
634 if(storageType == StorageType::KEEP_PIXEL_BUFFER) // For the mask image loading.
636 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
637 textureInfo.loadState = LoadState::LOAD_FINISHED;
639 else // For the image loading.
641 if(maskTextureId != INVALID_TEXTURE_ID)
643 TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
644 if(maskCacheIndex != INVALID_CACHE_INDEX)
646 Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
649 pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask);
653 DALI_LOG_ERROR("Mask image cached invalid pixel buffer!\n");
658 DALI_LOG_ERROR("Mask image is not stored in cache.\n");
661 PreMultiply(pixelBuffer, preMultiplyOnLoad);
664 UploadTexture(pixelBuffer, textureInfo);
671 void TextureManager::Remove(const TextureManager::TextureId& textureId, TextureUploadObserver* observer)
673 if(textureId != INVALID_TEXTURE_ID)
677 // Remove textureId after NotifyObserver finished
678 mRemoveQueue.PushBack(textureId);
682 // Remove textureId in CacheManager.
683 mTextureCacheManager.RemoveCache(textureId);
688 // Remove element from the LoadQueue
689 for(auto&& element : mLoadQueue)
691 if(element.mObserver == observer)
693 // Do not erase the item. We will clear it later in ProcessLoadQueue().
694 element.mObserver = nullptr;
702 Devel::PixelBuffer TextureManager::LoadImageSynchronously(
703 const VisualUrl& url,
704 const Dali::ImageDimensions& desiredSize,
705 const Dali::FittingMode::Type& fittingMode,
706 const Dali::SamplingMode::Type& samplingMode,
707 const bool& orientationCorrection)
709 Devel::PixelBuffer pixelBuffer;
710 if(url.IsBufferResource())
712 const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
713 if(encodedImageBuffer)
715 pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
720 pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
725 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
727 // make sure an observer doesn't observe the same object twice
728 // otherwise it will get multiple calls to ObjectDestroyed()
729 DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
730 mLifecycleObservers.PushBack(&observer);
733 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
735 // Find the observer...
736 auto endIter = mLifecycleObservers.End();
737 for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
739 if((*iter) == &observer)
741 mLifecycleObservers.Erase(iter);
745 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
748 void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
750 switch(textureInfo.loadState)
752 case LoadState::NOT_STARTED:
753 case LoadState::LOAD_FAILED:
757 QueueLoadTexture(textureInfo, observer);
761 LoadTexture(textureInfo, observer);
765 case LoadState::UPLOADED:
769 QueueLoadTexture(textureInfo, observer);
773 // The Texture has already loaded. The other observers have already been notified.
774 // We need to send a "late" loaded notification for this observer.
775 EmitLoadComplete(observer, textureInfo, true);
779 case LoadState::LOADING:
780 case LoadState::CANCELLED:
781 case LoadState::LOAD_FINISHED:
782 case LoadState::WAITING_FOR_MASK:
783 case LoadState::MASK_APPLYING:
784 case LoadState::MASK_APPLIED:
791 void TextureManager::QueueLoadTexture(const TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
793 const auto& textureId = textureInfo.textureId;
794 mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
796 observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
799 void TextureManager::LoadTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
801 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
803 textureInfo.loadState = LoadState::LOADING;
804 if(!textureInfo.loadSynchronously)
806 auto& loadersContainer = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
807 auto loadingHelperIt = loadersContainer.GetNext();
808 auto premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
809 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
810 if(textureInfo.animatedImageLoading)
812 loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex);
816 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
819 ObserveTexture(textureInfo, observer);
822 void TextureManager::ProcessLoadQueue()
824 for(auto&& element : mLoadQueue)
826 if(!element.mObserver)
831 TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(element.mTextureId);
832 if(cacheIndex != INVALID_CACHE_INDEX)
834 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
835 if((textureInfo.loadState == LoadState::UPLOADED) || (textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER))
837 EmitLoadComplete(element.mObserver, textureInfo, true);
841 LoadTexture(textureInfo, element.mObserver);
848 void TextureManager::ProcessRemoveQueue()
850 for(const auto& textureId : mRemoveQueue)
852 mTextureCacheManager.RemoveCache(textureId);
854 mRemoveQueue.Clear();
857 void TextureManager::ObserveTexture(TextureManager::TextureInfo& textureInfo,
858 TextureUploadObserver* observer)
860 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
864 textureInfo.observerList.PushBack(observer);
865 observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
869 void TextureManager::AsyncLoadComplete(const TextureManager::TextureId& textureId, Devel::PixelBuffer pixelBuffer)
871 TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
872 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( textureId:%d CacheIndex:%d )\n", textureId, cacheIndex.GetIndex());
873 if(cacheIndex != INVALID_CACHE_INDEX)
875 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
877 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));
879 if(textureInfo.loadState != LoadState::CANCELLED)
881 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
882 PostLoad(textureInfo, pixelBuffer);
886 Remove(textureInfo.textureId, nullptr);
891 void TextureManager::PostLoad(TextureManager::TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
893 // Was the load successful?
894 if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
896 // No atlas support for now
897 textureInfo.useAtlas = UseAtlas::NO_ATLAS;
898 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
900 if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
902 // If there is a mask texture ID associated with this texture, then apply the mask
903 // if it's already loaded. If it hasn't, and the mask is still loading,
904 // wait for the mask to finish loading.
905 // note, If the texture is already uploaded synchronously during loading,
906 // we don't need to apply mask.
907 if(textureInfo.loadState != LoadState::UPLOADED &&
908 textureInfo.maskTextureId != INVALID_TEXTURE_ID)
910 if(textureInfo.loadState == LoadState::MASK_APPLYING)
912 textureInfo.loadState = LoadState::MASK_APPLIED;
913 UploadTexture(pixelBuffer, textureInfo);
914 NotifyObservers(textureInfo, true);
918 LoadState maskLoadState = mTextureCacheManager.GetTextureStateInternal(textureInfo.maskTextureId);
919 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
920 if(maskLoadState == LoadState::LOADING)
922 textureInfo.loadState = LoadState::WAITING_FOR_MASK;
924 else if(maskLoadState == LoadState::LOAD_FINISHED)
926 // Send New Task to Thread
927 ApplyMask(textureInfo, textureInfo.maskTextureId);
929 else // maskLoadState == LoadState::LOAD_FAILED
931 // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
932 DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
933 UploadTexture(pixelBuffer, textureInfo);
934 NotifyObservers(textureInfo, true);
940 UploadTexture(pixelBuffer, textureInfo);
941 NotifyObservers(textureInfo, true);
946 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
947 textureInfo.loadState = LoadState::LOAD_FINISHED;
949 if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
951 NotifyObservers(textureInfo, true);
955 // Check if there was another texture waiting for this load to complete
956 // (e.g. if this was an image mask, and its load is on a different thread)
957 CheckForWaitingTexture(textureInfo);
963 textureInfo.loadState = LoadState::LOAD_FAILED;
964 if(textureInfo.storageType != StorageType::KEEP_PIXEL_BUFFER)
966 NotifyObservers(textureInfo, false);
968 else // if(textureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER) // image mask case
970 // Check if there was another texture waiting for this load to complete
971 // (e.g. if this was an image mask, and its load is on a different thread)
972 CheckForWaitingTexture(textureInfo);
977 void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTextureInfo)
979 // Search the cache, checking if any texture has this texture id as a
981 const std::size_t size = mTextureCacheManager.size();
983 const bool maskLoadSuccess = maskTextureInfo.loadState == LoadState::LOAD_FINISHED ? true : false;
985 // TODO : Refactorize here to not iterate whole cached image.
986 for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
988 if(mTextureCacheManager[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
989 mTextureCacheManager[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
991 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
995 // Send New Task to Thread
996 ApplyMask(textureInfo, maskTextureInfo.textureId);
1000 // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
1001 DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
1002 UploadTexture(textureInfo.pixelBuffer, textureInfo);
1003 NotifyObservers(textureInfo, true);
1009 void TextureManager::ApplyMask(TextureManager::TextureInfo& textureInfo, const TextureManager::TextureId& maskTextureId)
1011 TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
1012 if(maskCacheIndex != INVALID_CACHE_INDEX)
1014 Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
1015 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
1016 textureInfo.pixelBuffer.Reset();
1018 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
1020 textureInfo.loadState = LoadState::MASK_APPLYING;
1021 auto& loadersContainer = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1022 auto loadingHelperIt = loadersContainer.GetNext();
1023 auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1024 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1025 loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
1029 void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureManager::TextureInfo& textureInfo)
1031 if(textureInfo.loadState != LoadState::UPLOADED && textureInfo.useAtlas != UseAtlas::USE_ATLAS)
1033 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
1035 // Check if this pixelBuffer is premultiplied
1036 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1038 auto& renderingAddOn = RenderingAddOn::Get();
1039 if(renderingAddOn.IsValid())
1041 renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
1044 Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1046 PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1047 texture.Upload(pixelData);
1048 if(!textureInfo.textureSet)
1050 textureInfo.textureSet = TextureSet::New();
1052 textureInfo.textureSet.SetTexture(0u, texture);
1055 // Update the load state.
1056 // Note: This is regardless of success as we care about whether a
1057 // load attempt is in progress or not. If unsuccessful, a broken
1058 // image is still loaded.
1059 textureInfo.loadState = LoadState::UPLOADED;
1062 void TextureManager::NotifyObservers(TextureManager::TextureInfo& textureInfo, const bool& success)
1064 TextureId textureId = textureInfo.textureId;
1066 // If there is an observer: Notify the load is complete, whether successful or not,
1067 // and erase it from the list
1068 TextureInfo* info = &textureInfo;
1070 if(info->animatedImageLoading)
1072 // If loading failed, we don't need to get frameCount and frameInterval.
1075 info->frameCount = info->animatedImageLoading.GetImageCount();
1076 info->frameInterval = info->animatedImageLoading.GetFrameInterval(info->frameIndex);
1078 info->animatedImageLoading.Reset();
1081 mQueueLoadFlag = true;
1083 // Reverse observer list that we can pop_back the observer.
1084 std::reverse(info->observerList.Begin(), info->observerList.End());
1086 while(info->observerList.Count())
1088 TextureUploadObserver* observer = *(info->observerList.End() - 1u);
1090 // During LoadComplete() a Control ResourceReady() signal is emitted.
1091 // During that signal the app may add remove /add Textures (e.g. via
1093 // It is possible for observers to be removed from the observer list,
1094 // and it is also possible for the mTextureInfoContainer to be modified,
1095 // invalidating the reference to the textureInfo struct.
1096 // Texture load requests for the same URL are deferred until the end of this
1098 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));
1100 // It is possible for the observer to be deleted.
1101 // Disconnect and remove the observer first.
1102 observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1104 info->observerList.Erase(info->observerList.End() - 1u);
1106 EmitLoadComplete(observer, *info, success);
1108 // Get the textureInfo from the container again as it may have been invalidated.
1109 TextureCacheIndex textureInfoIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1110 if(textureInfoIndex == INVALID_CACHE_INDEX)
1112 break; // texture has been removed - can stop.
1114 info = &mTextureCacheManager[textureInfoIndex];
1117 mQueueLoadFlag = false;
1119 ProcessRemoveQueue();
1121 if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1123 Remove(info->textureId, nullptr);
1127 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1129 const std::size_t size = mTextureCacheManager.size();
1130 for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
1132 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
1133 for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1134 j != textureInfo.observerList.End();)
1138 j = textureInfo.observerList.Erase(j);
1147 // Remove element from the LoadQueue
1148 for(auto&& element : mLoadQueue)
1150 if(element.mObserver == observer)
1152 element.mObserver = nullptr;
1157 Dali::Geometry TextureManager::GetRenderGeometry(const TextureManager::TextureId& textureId, std::uint32_t& frontElements, std::uint32_t& backElements)
1159 return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1162 void TextureManager::EmitLoadComplete(TextureUploadObserver* observer, TextureManager::TextureInfo& textureInfo, const bool& success)
1164 if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1166 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, textureInfo.pixelBuffer, textureInfo.url.GetUrl(), textureInfo.preMultiplied));
1168 else if(textureInfo.isAnimatedImageFormat)
1170 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::ANIMATED_IMAGE_TEXTURE, textureInfo.textureId, textureInfo.frameCount, textureInfo.frameInterval));
1174 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureInfo.textureSet, (textureInfo.useAtlas == UseAtlas::USE_ATLAS) ? true : false, textureInfo.atlasRect, textureInfo.preMultiplied));
1178 } // namespace Internal
1180 } // namespace Toolkit