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(Dali::AnimatedImageLoading animatedImageLoading,
142 const uint32_t& frameIndex,
143 TextureManager::TextureId& textureId,
144 const Dali::SamplingMode::Type& samplingMode,
145 const Dali::WrapMode::Type& wrapModeU,
146 const Dali::WrapMode::Type& wrapModeV,
147 const bool& synchronousLoading,
148 const bool& useCache,
149 TextureUploadObserver* textureObserver)
151 TextureSet textureSet;
153 if(synchronousLoading)
155 Devel::PixelBuffer pixelBuffer;
156 if(animatedImageLoading)
158 pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
162 DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
166 PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
169 Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
170 texture.Upload(pixelData);
171 textureSet = TextureSet::New();
172 textureSet.SetTexture(0u, texture);
178 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
179 textureId = RequestLoadInternal(animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, UseAtlas::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex, false, useCache);
180 TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
181 if(loadState == TextureManager::LoadState::UPLOADED)
183 // LoadComplete has already been called - keep the same texture set
184 textureSet = GetTextureSet(textureId);
190 Sampler sampler = Sampler::New();
191 sampler.SetWrapMode(wrapModeU, wrapModeV);
192 textureSet.SetSampler(0u, sampler);
198 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
199 const VisualUrl& url,
200 const Dali::ImageDimensions& desiredSize,
201 const Dali::FittingMode::Type& fittingMode,
202 const Dali::SamplingMode::Type& samplingMode,
203 const bool& synchronousLoading,
204 TextureUploadObserver* textureObserver,
205 const bool& orientationCorrection,
206 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
208 Devel::PixelBuffer pixelBuffer;
209 if(synchronousLoading)
213 if(url.IsBufferResource())
215 const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
216 if(encodedImageBuffer)
218 pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
223 pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
225 if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
227 PreMultiply(pixelBuffer, preMultiplyOnLoad);
233 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);
239 TextureSet TextureManager::LoadTexture(
240 const VisualUrl& url,
241 const Dali::ImageDimensions& desiredSize,
242 const Dali::FittingMode::Type& fittingMode,
243 const Dali::SamplingMode::Type& samplingMode,
244 MaskingDataPointer& maskInfo,
245 const bool& synchronousLoading,
246 TextureManager::TextureId& textureId,
247 Vector4& textureRect,
248 Dali::ImageDimensions& textureRectSize,
249 bool& atlasingStatus,
251 const Dali::WrapMode::Type& wrapModeU,
252 const Dali::WrapMode::Type& wrapModeV,
253 TextureUploadObserver* textureObserver,
254 AtlasUploadObserver* atlasObserver,
255 ImageAtlasManagerPtr imageAtlasManager,
256 const bool& orientationCorrection,
257 const TextureManager::ReloadPolicy& reloadPolicy,
258 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
260 TextureSet textureSet;
262 loadingStatus = false;
263 textureRect = FULL_ATLAS_RECT;
265 if(VisualUrl::TEXTURE == url.GetProtocolType())
267 std::string location = url.GetLocation();
268 if(location.size() > 0u)
270 TextureId id = std::stoi(location);
271 textureSet = mTextureCacheManager.GetExternalTextureSet(id);
274 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
283 if(synchronousLoading && atlasingStatus && imageAtlasManager->CheckAtlasAvailable(url, desiredSize))
285 Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
287 if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
289 Devel::PixelBuffer maskPixelBuffer = LoadImageSynchronously(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
292 pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
299 PreMultiply(pixelBuffer, preMultiplyOnLoad);
300 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
304 textureSet = imageAtlasManager->Add(textureRect, data);
307 textureRectSize.SetWidth(data.GetWidth());
308 textureRectSize.SetHeight(data.GetHeight());
313 DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous Texture loading with atlasing is failed.\n");
318 atlasingStatus = false;
324 loadingStatus = true;
325 // Atlas manager can chage desired size when it is set by 0,0.
326 // We should store into textureRectSize only if atlasing successed.
327 // So copy inputed desiredSize, and replace value into textureRectSize only if atlasing success.
328 Dali::ImageDimensions atlasDesiredSize = desiredSize;
331 textureSet = imageAtlasManager->Add(textureRect, url.GetUrl(), atlasDesiredSize, fittingMode, true, atlasObserver);
333 if(!textureSet) // big image, no atlasing or atlasing failed
335 atlasingStatus = false;
336 if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
338 textureId = RequestLoad(
345 orientationCorrection,
352 maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl, synchronousLoading);
353 textureId = RequestLoad(
355 maskInfo->mAlphaMaskId,
356 maskInfo->mContentScaleFactor,
361 maskInfo->mCropToMask,
363 orientationCorrection,
369 TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
370 if(loadState == TextureManager::LoadState::UPLOADED)
372 // LoadComplete has already been called - keep the same texture set
373 textureSet = mTextureCacheManager.GetTextureSet(textureId);
376 // If we are loading the texture, or waiting for the ready signal handler to complete, inform
377 // caller that they need to wait.
378 loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
379 loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
380 loadState == TextureManager::LoadState::MASK_APPLYING ||
381 loadState == TextureManager::LoadState::MASK_APPLIED ||
382 loadState == TextureManager::LoadState::NOT_STARTED ||
387 textureRectSize = atlasDesiredSize;
392 if(!atlasingStatus && textureSet)
394 Sampler sampler = Sampler::New();
395 sampler.SetWrapMode(wrapModeU, wrapModeV);
396 textureSet.SetSampler(0u, sampler);
399 if(synchronousLoading)
401 loadingStatus = false;
407 TextureManager::TextureId TextureManager::RequestLoad(
408 const VisualUrl& url,
409 const ImageDimensions& desiredSize,
410 const Dali::FittingMode::Type& fittingMode,
411 const Dali::SamplingMode::Type& samplingMode,
412 const UseAtlas& useAtlas,
413 TextureUploadObserver* observer,
414 const bool& orientationCorrection,
415 const TextureManager::ReloadPolicy& reloadPolicy,
416 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
417 const bool& synchronousLoading)
419 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);
422 TextureManager::TextureId TextureManager::RequestLoad(
423 const VisualUrl& url,
424 const TextureManager::TextureId& maskTextureId,
425 const float& contentScale,
426 const Dali::ImageDimensions& desiredSize,
427 const Dali::FittingMode::Type& fittingMode,
428 const Dali::SamplingMode::Type& samplingMode,
429 const TextureManager::UseAtlas& useAtlas,
430 const bool& cropToMask,
431 TextureUploadObserver* observer,
432 const bool& orientationCorrection,
433 const TextureManager::ReloadPolicy& reloadPolicy,
434 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
435 const bool& synchronousLoading)
437 return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading, true);
440 TextureManager::TextureId TextureManager::RequestMaskLoad(
441 const VisualUrl& maskUrl,
442 const bool& synchronousLoading)
444 // Use the normal load procedure to get the alpha mask.
445 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
446 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);
449 TextureManager::TextureId TextureManager::RequestLoadInternal(
450 const VisualUrl& url,
451 const TextureManager::TextureId& maskTextureId,
452 const float& contentScale,
453 const Dali::ImageDimensions& desiredSize,
454 const Dali::FittingMode::Type& fittingMode,
455 const Dali::SamplingMode::Type& samplingMode,
456 const TextureManager::UseAtlas& useAtlas,
457 const bool& cropToMask,
458 const TextureManager::StorageType& storageType,
459 TextureUploadObserver* observer,
460 const bool& orientationCorrection,
461 const TextureManager::ReloadPolicy& reloadPolicy,
462 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
463 Dali::AnimatedImageLoading animatedImageLoading,
464 const std::uint32_t& frameIndex,
465 const bool& synchronousLoading,
466 const bool& useCache)
468 TextureHash textureHash = INITIAL_HASH_NUMBER;
469 TextureCacheIndex cacheIndex = INVALID_CACHE_INDEX;
470 if(storageType != StorageType::RETURN_PIXEL_BUFFER && useCache)
472 textureHash = mTextureCacheManager.GenerateHash(url, desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, cropToMask);
474 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
475 cacheIndex = mTextureCacheManager.FindCachedTexture(textureHash, url, desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, cropToMask, preMultiplyOnLoad, (animatedImageLoading) ? true : false);
478 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
479 // Check if the requested Texture exists in the cache.
480 if(cacheIndex != INVALID_CACHE_INDEX)
482 if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
484 // Mark this texture being used by another client resource. Forced reload would replace the current texture
485 // without the need for incrementing the reference count.
486 ++(mTextureCacheManager[cacheIndex].referenceCount);
488 textureId = mTextureCacheManager[cacheIndex].textureId;
490 // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
491 preMultiplyOnLoad = mTextureCacheManager[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
493 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);
496 if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
498 textureId = mTextureCacheManager.GenerateTextureId();
500 bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
502 // Cache new texutre, and get cacheIndex.
503 cacheIndex = mTextureCacheManager.AppendCache(TextureInfo(textureId, maskTextureId, url, desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
505 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);
508 // The below code path is common whether we are using the cache or not.
509 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
510 // or a new TextureInfo just created.
511 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
512 textureInfo.maskTextureId = maskTextureId;
513 textureInfo.storageType = storageType;
514 textureInfo.orientationCorrection = orientationCorrection;
516 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
518 // Force reloading of texture by setting loadState unless already loading or cancelled.
519 if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
520 TextureManager::LoadState::LOADING != textureInfo.loadState &&
521 TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
522 TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
523 TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
524 TextureManager::LoadState::CANCELLED != textureInfo.loadState)
526 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);
528 textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
531 if(!synchronousLoading)
533 // Check if we should add the observer.
534 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
535 switch(textureInfo.loadState)
537 case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
538 case TextureManager::LoadState::NOT_STARTED:
540 LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
543 case TextureManager::LoadState::LOADING:
544 case TextureManager::LoadState::WAITING_FOR_MASK:
545 case TextureManager::LoadState::MASK_APPLYING:
546 case TextureManager::LoadState::MASK_APPLIED:
548 ObserveTexture(textureInfo, observer);
551 case TextureManager::LoadState::UPLOADED:
555 LoadOrQueueTexture(textureInfo, observer);
559 case TextureManager::LoadState::CANCELLED:
561 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
562 // (it's ref count has already been incremented, above)
563 textureInfo.loadState = TextureManager::LoadState::LOADING;
564 ObserveTexture(textureInfo, observer);
567 case TextureManager::LoadState::LOAD_FINISHED:
569 // Loading has already completed.
570 if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
572 LoadOrQueueTexture(textureInfo, observer);
580 // If the image is already finished to load, use cached texture.
581 // We don't need to consider Observer because this is synchronous loading.
582 if(!(textureInfo.loadState == TextureManager::LoadState::UPLOADED ||
583 textureInfo.loadState == TextureManager::LoadState::LOAD_FINISHED))
585 Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
589 // If pixelBuffer loading is failed in synchronously, call Remove() method.
590 Remove(textureId, nullptr);
591 return INVALID_TEXTURE_ID;
594 if(storageType == StorageType::KEEP_PIXEL_BUFFER) // For the mask image loading.
596 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
597 textureInfo.loadState = LoadState::LOAD_FINISHED;
599 else // For the image loading.
601 if(maskTextureId != INVALID_TEXTURE_ID)
603 TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
604 if(maskCacheIndex != INVALID_CACHE_INDEX)
606 Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
609 pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask);
613 DALI_LOG_ERROR("Mask image cached invalid pixel buffer!\n");
618 DALI_LOG_ERROR("Mask image is not stored in cache.\n");
621 PreMultiply(pixelBuffer, preMultiplyOnLoad);
624 UploadTexture(pixelBuffer, textureInfo);
631 void TextureManager::Remove(const TextureManager::TextureId& textureId, TextureUploadObserver* observer)
633 if(textureId != INVALID_TEXTURE_ID)
637 // Remove textureId after NotifyObserver finished
638 mRemoveQueue.PushBack(textureId);
642 // Remove textureId in CacheManager.
643 mTextureCacheManager.RemoveCache(textureId);
648 // Remove element from the LoadQueue
649 for(auto&& element : mLoadQueue)
651 if(element.mObserver == observer)
653 // Do not erase the item. We will clear it later in ProcessLoadQueue().
654 element.mObserver = nullptr;
662 Devel::PixelBuffer TextureManager::LoadImageSynchronously(
663 const VisualUrl& url,
664 const Dali::ImageDimensions& desiredSize,
665 const Dali::FittingMode::Type& fittingMode,
666 const Dali::SamplingMode::Type& samplingMode,
667 const bool& orientationCorrection)
669 Devel::PixelBuffer pixelBuffer;
670 if(url.IsBufferResource())
672 const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url);
673 if(encodedImageBuffer)
675 pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
680 pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
685 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
687 // make sure an observer doesn't observe the same object twice
688 // otherwise it will get multiple calls to ObjectDestroyed()
689 DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
690 mLifecycleObservers.PushBack(&observer);
693 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
695 // Find the observer...
696 auto endIter = mLifecycleObservers.End();
697 for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
699 if((*iter) == &observer)
701 mLifecycleObservers.Erase(iter);
705 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
708 void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
710 switch(textureInfo.loadState)
712 case LoadState::NOT_STARTED:
713 case LoadState::LOAD_FAILED:
717 QueueLoadTexture(textureInfo, observer);
721 LoadTexture(textureInfo, observer);
725 case LoadState::UPLOADED:
729 QueueLoadTexture(textureInfo, observer);
733 // The Texture has already loaded. The other observers have already been notified.
734 // We need to send a "late" loaded notification for this observer.
735 EmitLoadComplete(observer, textureInfo, true);
739 case LoadState::LOADING:
740 case LoadState::CANCELLED:
741 case LoadState::LOAD_FINISHED:
742 case LoadState::WAITING_FOR_MASK:
743 case LoadState::MASK_APPLYING:
744 case LoadState::MASK_APPLIED:
751 void TextureManager::QueueLoadTexture(const TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
753 const auto& textureId = textureInfo.textureId;
754 mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
756 observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
759 void TextureManager::LoadTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
761 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
763 textureInfo.loadState = LoadState::LOADING;
764 if(!textureInfo.loadSynchronously)
766 auto& loadersContainer = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
767 auto loadingHelperIt = loadersContainer.GetNext();
768 auto premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
769 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
770 if(textureInfo.animatedImageLoading)
772 loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex);
776 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
779 ObserveTexture(textureInfo, observer);
782 void TextureManager::ProcessLoadQueue()
784 for(auto&& element : mLoadQueue)
786 if(!element.mObserver)
791 TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(element.mTextureId);
792 if(cacheIndex != INVALID_CACHE_INDEX)
794 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
795 if((textureInfo.loadState == LoadState::UPLOADED) || (textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER))
797 EmitLoadComplete(element.mObserver, textureInfo, true);
801 LoadTexture(textureInfo, element.mObserver);
808 void TextureManager::ProcessRemoveQueue()
810 for(const auto& textureId : mRemoveQueue)
812 mTextureCacheManager.RemoveCache(textureId);
814 mRemoveQueue.Clear();
817 void TextureManager::ObserveTexture(TextureManager::TextureInfo& textureInfo,
818 TextureUploadObserver* observer)
820 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
824 textureInfo.observerList.PushBack(observer);
825 observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
829 void TextureManager::AsyncLoadComplete(const TextureManager::TextureId& textureId, Devel::PixelBuffer pixelBuffer)
831 TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
832 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( textureId:%d CacheIndex:%d )\n", textureId, cacheIndex.GetIndex());
833 if(cacheIndex != INVALID_CACHE_INDEX)
835 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
837 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));
839 if(textureInfo.loadState != LoadState::CANCELLED)
841 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
842 PostLoad(textureInfo, pixelBuffer);
846 Remove(textureInfo.textureId, nullptr);
851 void TextureManager::PostLoad(TextureManager::TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
853 // Was the load successful?
854 if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
856 // No atlas support for now
857 textureInfo.useAtlas = UseAtlas::NO_ATLAS;
858 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
860 if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
862 // If there is a mask texture ID associated with this texture, then apply the mask
863 // if it's already loaded. If it hasn't, and the mask is still loading,
864 // wait for the mask to finish loading.
865 // note, If the texture is already uploaded synchronously during loading,
866 // we don't need to apply mask.
867 if(textureInfo.loadState != LoadState::UPLOADED &&
868 textureInfo.maskTextureId != INVALID_TEXTURE_ID)
870 if(textureInfo.loadState == LoadState::MASK_APPLYING)
872 textureInfo.loadState = LoadState::MASK_APPLIED;
873 UploadTexture(pixelBuffer, textureInfo);
874 NotifyObservers(textureInfo, true);
878 LoadState maskLoadState = mTextureCacheManager.GetTextureStateInternal(textureInfo.maskTextureId);
879 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
880 if(maskLoadState == LoadState::LOADING)
882 textureInfo.loadState = LoadState::WAITING_FOR_MASK;
884 else if(maskLoadState == LoadState::LOAD_FINISHED)
886 // Send New Task to Thread
887 ApplyMask(textureInfo, textureInfo.maskTextureId);
889 else // maskLoadState == LoadState::LOAD_FAILED
891 // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
892 DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
893 UploadTexture(pixelBuffer, textureInfo);
894 NotifyObservers(textureInfo, true);
900 UploadTexture(pixelBuffer, textureInfo);
901 NotifyObservers(textureInfo, true);
906 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
907 textureInfo.loadState = LoadState::LOAD_FINISHED;
909 if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
911 NotifyObservers(textureInfo, true);
915 // Check if there was another texture waiting for this load to complete
916 // (e.g. if this was an image mask, and its load is on a different thread)
917 CheckForWaitingTexture(textureInfo);
923 textureInfo.loadState = LoadState::LOAD_FAILED;
924 if(textureInfo.storageType != StorageType::KEEP_PIXEL_BUFFER)
926 NotifyObservers(textureInfo, false);
928 else // if(textureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER) // image mask case
930 // Check if there was another texture waiting for this load to complete
931 // (e.g. if this was an image mask, and its load is on a different thread)
932 CheckForWaitingTexture(textureInfo);
937 void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTextureInfo)
939 // Search the cache, checking if any texture has this texture id as a
941 const std::size_t size = mTextureCacheManager.size();
943 const bool maskLoadSuccess = maskTextureInfo.loadState == LoadState::LOAD_FINISHED ? true : false;
945 // TODO : Refactorize here to not iterate whole cached image.
946 for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
948 if(mTextureCacheManager[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
949 mTextureCacheManager[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
951 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
955 // Send New Task to Thread
956 ApplyMask(textureInfo, maskTextureInfo.textureId);
960 // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
961 DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
962 UploadTexture(textureInfo.pixelBuffer, textureInfo);
963 NotifyObservers(textureInfo, true);
969 void TextureManager::ApplyMask(TextureManager::TextureInfo& textureInfo, const TextureManager::TextureId& maskTextureId)
971 TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
972 if(maskCacheIndex != INVALID_CACHE_INDEX)
974 Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
975 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
976 textureInfo.pixelBuffer.Reset();
978 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
980 textureInfo.loadState = LoadState::MASK_APPLYING;
981 auto& loadersContainer = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
982 auto loadingHelperIt = loadersContainer.GetNext();
983 auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
984 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
985 loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
989 void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureManager::TextureInfo& textureInfo)
991 if(textureInfo.loadState != LoadState::UPLOADED && textureInfo.useAtlas != UseAtlas::USE_ATLAS)
993 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
995 // Check if this pixelBuffer is premultiplied
996 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
998 auto& renderingAddOn = RenderingAddOn::Get();
999 if(renderingAddOn.IsValid())
1001 renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
1004 Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1006 PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1007 texture.Upload(pixelData);
1008 if(!textureInfo.textureSet)
1010 textureInfo.textureSet = TextureSet::New();
1012 textureInfo.textureSet.SetTexture(0u, texture);
1015 // Update the load state.
1016 // Note: This is regardless of success as we care about whether a
1017 // load attempt is in progress or not. If unsuccessful, a broken
1018 // image is still loaded.
1019 textureInfo.loadState = LoadState::UPLOADED;
1022 void TextureManager::NotifyObservers(TextureManager::TextureInfo& textureInfo, const bool& success)
1024 TextureId textureId = textureInfo.textureId;
1026 // If there is an observer: Notify the load is complete, whether successful or not,
1027 // and erase it from the list
1028 TextureInfo* info = &textureInfo;
1030 if(info->animatedImageLoading)
1032 // If loading failed, we don't need to get frameCount and frameInterval.
1035 info->frameCount = info->animatedImageLoading.GetImageCount();
1036 info->frameInterval = info->animatedImageLoading.GetFrameInterval(info->frameIndex);
1038 info->animatedImageLoading.Reset();
1041 mQueueLoadFlag = true;
1043 while(info->observerList.Count())
1045 TextureUploadObserver* observer = info->observerList[0];
1047 // During LoadComplete() a Control ResourceReady() signal is emitted.
1048 // During that signal the app may add remove /add Textures (e.g. via
1050 // It is possible for observers to be removed from the observer list,
1051 // and it is also possible for the mTextureInfoContainer to be modified,
1052 // invalidating the reference to the textureInfo struct.
1053 // Texture load requests for the same URL are deferred until the end of this
1055 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));
1057 // It is possible for the observer to be deleted.
1058 // Disconnect and remove the observer first.
1059 observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1061 info->observerList.Erase(info->observerList.Begin());
1063 EmitLoadComplete(observer, *info, success);
1065 // Get the textureInfo from the container again as it may have been invalidated.
1066 TextureCacheIndex textureInfoIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1067 if(textureInfoIndex == INVALID_CACHE_INDEX)
1069 break; // texture has been removed - can stop.
1071 info = &mTextureCacheManager[textureInfoIndex];
1074 mQueueLoadFlag = false;
1076 ProcessRemoveQueue();
1078 if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1080 Remove(info->textureId, nullptr);
1084 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1086 const std::size_t size = mTextureCacheManager.size();
1087 for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
1089 TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
1090 for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1091 j != textureInfo.observerList.End();)
1095 j = textureInfo.observerList.Erase(j);
1104 // Remove element from the LoadQueue
1105 for(auto&& element : mLoadQueue)
1107 if(element.mObserver == observer)
1109 element.mObserver = nullptr;
1114 Dali::Geometry TextureManager::GetRenderGeometry(const TextureManager::TextureId& textureId, std::uint32_t& frontElements, std::uint32_t& backElements)
1116 return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1119 void TextureManager::EmitLoadComplete(TextureUploadObserver* observer, TextureManager::TextureInfo& textureInfo, const bool& success)
1121 if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1123 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, textureInfo.pixelBuffer, textureInfo.url.GetUrl(), textureInfo.preMultiplied));
1125 else if(textureInfo.isAnimatedImageFormat)
1127 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::ANIMATED_IMAGE_TEXTURE, textureInfo.textureId, textureInfo.frameCount, textureInfo.frameInterval));
1131 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureInfo.textureSet, (textureInfo.useAtlas == UseAtlas::USE_ATLAS) ? true : false, textureInfo.atlasRect, textureInfo.preMultiplied));
1135 } // namespace Internal
1137 } // namespace Toolkit