Guard textureId during CheckForWaitingTexture
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / texture-manager / texture-manager-impl.cpp
index 223208a..33405be 100644 (file)
@@ -37,9 +37,12 @@ constexpr auto INITIAL_HASH_NUMBER                     = size_t{0u};
 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS  = size_t{4u};
 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
 
+constexpr auto TEXTURE_INDEX      = 0u; ///< The Index for texture
+constexpr auto MASK_TEXTURE_INDEX = 1u; ///< The Index for mask texture
+
 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV  = "DALI_TEXTURE_LOCAL_THREADS";
 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
-constexpr auto LOAD_IMAGE_YUV_PLANES_ENV           = "DALI_LOAD_IMAGE_YUV_PLANES_ENV";
+constexpr auto LOAD_IMAGE_YUV_PLANES_ENV           = "DALI_LOAD_IMAGE_YUV_PLANES";
 
 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
 {
@@ -133,7 +136,7 @@ TextureManager::TextureManager()
   mLifecycleObservers(),
   mLoadQueue(),
   mRemoveQueue(),
-  mQueueLoadFlag(false),
+  mLoadingQueueTextureId(INVALID_TEXTURE_ID),
   mLoadYuvPlanes(NeedToLoadYuvPlanes())
 {
   // Initialize the AddOn
@@ -155,8 +158,6 @@ TextureSet TextureManager::LoadAnimatedImageTexture(
   TextureManager::TextureId&      textureId,
   MaskingDataPointer&             maskInfo,
   const Dali::SamplingMode::Type& samplingMode,
-  const Dali::WrapMode::Type&     wrapModeU,
-  const Dali::WrapMode::Type&     wrapModeV,
   const bool&                     synchronousLoading,
   TextureUploadObserver*          textureObserver,
   TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
@@ -210,10 +211,10 @@ TextureSet TextureManager::LoadAnimatedImageTexture(
         Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
         texture.Upload(pixelData);
         textureSet = TextureSet::New();
-        textureSet.SetTexture(0u, texture);
+        textureSet.SetTexture(TEXTURE_INDEX, texture);
         if(maskTexture)
         {
-          textureSet.SetTexture(1u, maskTexture);
+          textureSet.SetTexture(MASK_TEXTURE_INDEX, maskTexture);
         }
       }
     }
@@ -244,13 +245,6 @@ TextureSet TextureManager::LoadAnimatedImageTexture(
     }
   }
 
-  if(textureSet)
-  {
-    Sampler sampler = Sampler::New();
-    sampler.SetWrapMode(wrapModeU, wrapModeV);
-    textureSet.SetSampler(0u, sampler);
-  }
-
   return textureSet;
 }
 
@@ -307,8 +301,6 @@ TextureSet TextureManager::LoadTexture(
   Dali::ImageDimensions&              textureRectSize,
   bool&                               atlasingStatus,
   bool&                               loadingStatus,
-  const Dali::WrapMode::Type&         wrapModeU,
-  const Dali::WrapMode::Type&         wrapModeV,
   TextureUploadObserver*              textureObserver,
   AtlasUploadObserver*                atlasObserver,
   ImageAtlasManagerPtr                imageAtlasManager,
@@ -444,7 +436,7 @@ TextureSet TextureManager::LoadTexture(
         if(loadState == TextureManager::LoadState::UPLOADED)
         {
           // LoadComplete has already been called - keep the same texture set
-          textureSet = mTextureCacheManager.GetTextureSet(textureId);
+          textureSet = GetTextureSet(textureId);
         }
 
         // If we are loading the texture, or waiting for the ready signal handler to complete, inform
@@ -454,7 +446,7 @@ TextureSet TextureManager::LoadTexture(
                          loadState == TextureManager::LoadState::MASK_APPLYING ||
                          loadState == TextureManager::LoadState::MASK_APPLIED ||
                          loadState == TextureManager::LoadState::NOT_STARTED ||
-                         mQueueLoadFlag);
+                         mLoadingQueueTextureId != INVALID_TEXTURE_ID);
       }
       else
       {
@@ -463,13 +455,6 @@ TextureSet TextureManager::LoadTexture(
     }
   }
 
-  if(!atlasingStatus && textureSet)
-  {
-    Sampler sampler = Sampler::New();
-    sampler.SetWrapMode(wrapModeU, wrapModeV);
-    textureSet.SetSampler(0u, sampler);
-  }
-
   if(synchronousLoading)
   {
     loadingStatus = false;
@@ -683,10 +668,9 @@ TextureManager::TextureId TextureManager::RequestLoadInternal(
           {
             if(mTextureCacheManager[maskCacheIndex].storageType == StorageType::KEEP_TEXTURE)
             {
-              TextureSet maskTextures = mTextureCacheManager[maskCacheIndex].textureSet;
-              if(maskTextures && maskTextures.GetTextureCount())
+              if(!mTextureCacheManager[maskCacheIndex].textures.empty())
               {
-                maskTexture = maskTextures.GetTexture(0u);
+                maskTexture = mTextureCacheManager[maskCacheIndex].textures[0];
               }
             }
             else if(mTextureCacheManager[maskCacheIndex].storageType == StorageType::KEEP_PIXEL_BUFFER)
@@ -711,13 +695,10 @@ TextureManager::TextureId TextureManager::RequestLoadInternal(
 
         // Upload texture
         UploadTextures(pixelBuffers, textureInfo);
-        if(maskTexture && textureInfo.textureSet)
-        {
-          textureInfo.textureSet.SetTexture(1u, maskTexture);
-        }
       }
     }
   }
+
   return textureId;
 }
 
@@ -725,27 +706,63 @@ void TextureManager::Remove(const TextureManager::TextureId& textureId, TextureU
 {
   if(textureId != INVALID_TEXTURE_ID)
   {
-    if(mQueueLoadFlag)
+    TextureCacheIndex textureCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
+    if(textureCacheIndex != INVALID_CACHE_INDEX)
     {
-      // Remove textureId after NotifyObserver finished
-      mRemoveQueue.PushBack(textureId);
-    }
-    else
-    {
-      // Remove textureId in CacheManager.
-      mTextureCacheManager.RemoveCache(textureId);
-    }
+      TextureManager::TextureId maskTextureId = INVALID_TEXTURE_ID;
+      TextureInfo&              textureInfo(mTextureCacheManager[textureCacheIndex]);
+      // We only need to consider maskTextureId when texture's loadState is not CANCELLED. Because it is already deleted.
+      if(textureInfo.loadState != LoadState::CANCELLED)
+      {
+        if(textureInfo.maskTextureId != INVALID_TEXTURE_ID)
+        {
+          maskTextureId = textureInfo.maskTextureId;
+        }
+      }
 
-    if(observer)
-    {
-      // Remove element from the LoadQueue
-      for(auto&& element : mLoadQueue)
+      // the case that LoadingQueue is working.
+      if(mLoadingQueueTextureId != INVALID_TEXTURE_ID)
+      {
+        // If textureId is not same, this observer need to delete when ProcessRemoveQueue() is called.
+        // If textureId is same, we should not call RemoveTextureObserver.
+        // Because ObserverDestroyed signal already disconnected in NotifyObservers
+        TextureUploadObserver* queueObserver = observer;
+        if(mLoadingQueueTextureId == textureId)
+        {
+          queueObserver = nullptr;
+        }
+
+        // Remove element from the mLoadQueue
+        for(auto&& element : mLoadQueue)
+        {
+          if(element.mTextureId == textureId && element.mObserver == observer)
+          {
+            // Do not erase the item. We will clear it later in ProcessLoadQueue().
+            element.mTextureId = INVALID_TEXTURE_ID;
+            element.mObserver  = nullptr;
+            break;
+          }
+        }
+
+        mRemoveQueue.PushBack(QueueElement(textureId, queueObserver));
+      }
+      else
       {
-        if(element.mObserver == observer)
+        // Remove its observer
+        RemoveTextureObserver(textureInfo, observer);
+
+        // Remove textureId in CacheManager. Now, textureInfo is invalidate.
+        mTextureCacheManager.RemoveCache(textureInfo);
+
+        // Remove maskTextureId in CacheManager
+        if(maskTextureId != INVALID_TEXTURE_ID)
         {
-          // Do not erase the item. We will clear it later in ProcessLoadQueue().
-          element.mObserver = nullptr;
-          break;
+          TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
+          if(maskCacheIndex != INVALID_CACHE_INDEX)
+          {
+            TextureInfo& maskTextureInfo(mTextureCacheManager[maskCacheIndex]);
+            mTextureCacheManager.RemoveCache(maskTextureInfo);
+          }
         }
       }
     }
@@ -818,7 +835,7 @@ void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo
     case LoadState::NOT_STARTED:
     case LoadState::LOAD_FAILED:
     {
-      if(mQueueLoadFlag)
+      if(mLoadingQueueTextureId != INVALID_TEXTURE_ID)
       {
         QueueLoadTexture(textureInfo, observer);
       }
@@ -830,7 +847,7 @@ void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo
     }
     case LoadState::UPLOADED:
     {
-      if(mQueueLoadFlag)
+      if(mLoadingQueueTextureId != INVALID_TEXTURE_ID)
       {
         QueueLoadTexture(textureInfo, observer);
       }
@@ -857,9 +874,12 @@ void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo
 void TextureManager::QueueLoadTexture(const TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
 {
   const auto& textureId = textureInfo.textureId;
-  mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
+  mLoadQueue.PushBack(QueueElement(textureId, observer));
 
-  observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
+  if(observer)
+  {
+    observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
+  }
 }
 
 void TextureManager::LoadTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
@@ -889,7 +909,7 @@ void TextureManager::ProcessLoadQueue()
 {
   for(auto&& element : mLoadQueue)
   {
-    if(!element.mObserver)
+    if(element.mTextureId == INVALID_TEXTURE_ID)
     {
       continue;
     }
@@ -900,7 +920,10 @@ void TextureManager::ProcessLoadQueue()
       TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
       if((textureInfo.loadState == LoadState::UPLOADED) || (textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER))
       {
-        EmitLoadComplete(element.mObserver, textureInfo, true);
+        if(element.mObserver)
+        {
+          EmitLoadComplete(element.mObserver, textureInfo, true);
+        }
       }
       else if(textureInfo.loadState == LoadState::LOADING)
       {
@@ -919,9 +942,12 @@ void TextureManager::ProcessLoadQueue()
 
 void TextureManager::ProcessRemoveQueue()
 {
-  for(const auto& textureId : mRemoveQueue)
+  for(auto&& element : mRemoveQueue)
   {
-    mTextureCacheManager.RemoveCache(textureId);
+    if(element.mTextureId != INVALID_TEXTURE_ID)
+    {
+      Remove(element.mTextureId, element.mObserver);
+    }
   }
   mRemoveQueue.Clear();
 }
@@ -1014,11 +1040,7 @@ void TextureManager::PostLoad(TextureManager::TextureInfo& textureInfo, std::vec
                   {
                     // Upload image texture. textureInfo.loadState will be UPLOADED.
                     UploadTextures(pixelBuffers, textureInfo);
-                    if(maskTextureInfo.textureSet.GetTextureCount() > 0u)
-                    {
-                      Texture maskTexture = maskTextureInfo.textureSet.GetTexture(0u);
-                      textureInfo.textureSet.SetTexture(1u, maskTexture);
-                    }
+
                     // notify mask texture set.
                     NotifyObservers(textureInfo, true);
                   }
@@ -1095,10 +1117,13 @@ void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTex
     UploadTextures(pixelBuffers, maskTextureInfo);
   }
 
-  // Search the cache, checking if any texture has this texture id as a
-  // maskTextureId:
+  // Search the cache, checking if any texture has this texture id as a maskTextureId
   const std::size_t size = mTextureCacheManager.size();
 
+  // Keep notify observer required textureIds.
+  // Note : NotifyObservers can change mTextureCacheManager cache struct. We should check id's validation before notify.
+  std::vector<TextureId> notifyRequiredTextureIds;
+
   // TODO : Refactorize here to not iterate whole cached image.
   for(TextureCacheIndex cacheIndex = TextureCacheIndex(TextureManagerType::TEXTURE_CACHE_INDEX_TYPE_LOCAL, 0u); cacheIndex.GetIndex() < size; ++cacheIndex.detailValue.index)
   {
@@ -1123,13 +1148,14 @@ void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTex
           std::vector<Devel::PixelBuffer> pixelBuffers;
           pixelBuffers.push_back(textureInfo.pixelBuffer);
           UploadTextures(pixelBuffers, textureInfo);
-          if(maskTextureInfo.textureSet.GetTextureCount() > 0u)
-          {
-            Texture maskTexture = maskTextureInfo.textureSet.GetTexture(0u);
-            textureInfo.textureSet.SetTexture(1u, maskTexture);
-          }
-          // notify mask texture set.
-          NotifyObservers(textureInfo, true);
+
+          // Increase reference counts for notify required textureId.
+          // Now we can assume that we don't remove & re-assign this textureId
+          // during NotifyObserver signal emit.
+          maskTextureInfo.referenceCount++;
+          textureInfo.referenceCount++;
+
+          notifyRequiredTextureIds.push_back(textureInfo.textureId);
         }
       }
       else
@@ -1139,10 +1165,34 @@ void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTex
         std::vector<Devel::PixelBuffer> pixelBuffers;
         pixelBuffers.push_back(textureInfo.pixelBuffer);
         UploadTextures(pixelBuffers, textureInfo);
-        NotifyObservers(textureInfo, true);
+
+        // Increase reference counts for notify required textureId.
+        // Now we can assume that we don't remove & re-assign this textureId
+        // during NotifyObserver signal emit.
+        maskTextureInfo.referenceCount++;
+        textureInfo.referenceCount++;
+
+        notifyRequiredTextureIds.push_back(textureInfo.textureId);
       }
     }
   }
+
+  // Notify textures are masked
+  for(const auto textureId : notifyRequiredTextureIds)
+  {
+    TextureCacheIndex textureCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
+    if(textureCacheIndex != INVALID_CACHE_INDEX)
+    {
+      TextureInfo& textureInfo(mTextureCacheManager[textureCacheIndex]);
+      NotifyObservers(textureInfo, true);
+    }
+  }
+
+  // Decrease reference count
+  for(const auto textureId : notifyRequiredTextureIds)
+  {
+    Remove(textureId, nullptr);
+  }
 }
 
 void TextureManager::ApplyMask(TextureManager::TextureInfo& textureInfo, const TextureManager::TextureId& maskTextureId)
@@ -1180,19 +1230,15 @@ void TextureManager::UploadTextures(std::vector<Devel::PixelBuffer>& pixelBuffer
       renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffers[0]);
     }
 
-    if(!textureInfo.textureSet)
-    {
-      textureInfo.textureSet = TextureSet::New();
-    }
+    // Remove previous textures and insert new textures
+    textureInfo.textures.clear();
 
-    uint32_t index = 0;
     for(auto&& pixelBuffer : pixelBuffers)
     {
-      Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
-
+      Texture   texture   = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
       PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
       texture.Upload(pixelData);
-      textureInfo.textureSet.SetTexture(index++, texture);
+      textureInfo.textures.push_back(texture);
     }
   }
 
@@ -1222,7 +1268,7 @@ void TextureManager::NotifyObservers(TextureManager::TextureInfo& textureInfo, c
     info->animatedImageLoading.Reset();
   }
 
-  mQueueLoadFlag = true;
+  mLoadingQueueTextureId = textureId;
 
   // Reverse observer list that we can pop_back the observer.
   std::reverse(info->observerList.Begin(), info->observerList.End());
@@ -1258,7 +1304,7 @@ void TextureManager::NotifyObservers(TextureManager::TextureInfo& textureInfo, c
     info = &mTextureCacheManager[textureInfoIndex];
   }
 
-  mQueueLoadFlag = false;
+  mLoadingQueueTextureId = INVALID_TEXTURE_ID;
   ProcessLoadQueue();
   ProcessRemoveQueue();
 
@@ -1293,7 +1339,8 @@ void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
   {
     if(element.mObserver == observer)
     {
-      element.mObserver = nullptr;
+      element.mTextureId = INVALID_TEXTURE_ID;
+      element.mObserver  = nullptr;
     }
   }
 }
@@ -1309,13 +1356,90 @@ void TextureManager::EmitLoadComplete(TextureUploadObserver* observer, TextureMa
   {
     observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, textureInfo.pixelBuffer, textureInfo.url.GetUrl(), textureInfo.preMultiplied));
   }
-  else if(textureInfo.isAnimatedImageFormat)
+  else
   {
-    observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::ANIMATED_IMAGE_TEXTURE, textureInfo.textureId, textureInfo.frameCount, textureInfo.frameInterval));
+    TextureSet textureSet = GetTextureSet(textureInfo);
+    if(textureInfo.isAnimatedImageFormat)
+    {
+      observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::ANIMATED_IMAGE_TEXTURE, textureInfo.textureId, textureSet, textureInfo.frameCount, textureInfo.frameInterval));
+    }
+    else
+    {
+      observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureSet, (textureInfo.useAtlas == UseAtlas::USE_ATLAS) ? true : false, textureInfo.atlasRect, textureInfo.preMultiplied));
+    }
+  }
+}
+
+TextureSet TextureManager::GetTextureSet(const TextureManager::TextureId& textureId)
+{
+  TextureSet                textureSet;
+  TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
+  if(loadState == TextureManager::LoadState::UPLOADED)
+  {
+    // LoadComplete has already been called - keep the same texture set
+    TextureCacheIndex textureCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
+    if(textureCacheIndex != INVALID_CACHE_INDEX)
+    {
+      TextureInfo& textureInfo(mTextureCacheManager[textureCacheIndex]);
+      textureSet = GetTextureSet(textureInfo);
+    }
   }
   else
   {
-    observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureInfo.textureSet, (textureInfo.useAtlas == UseAtlas::USE_ATLAS) ? true : false, textureInfo.atlasRect, textureInfo.preMultiplied));
+    DALI_LOG_ERROR("GetTextureSet is failed. texture is not uploaded \n");
+  }
+  return textureSet;
+}
+
+TextureSet TextureManager::GetTextureSet(const TextureManager::TextureInfo& textureInfo)
+{
+  TextureSet textureSet;
+
+  // LoadComplete has already been called - keep the same texture set
+  textureSet = TextureSet::New();
+  if(!textureInfo.textures.empty())
+  {
+    if(textureInfo.textures.size() > 1) // For YUV case
+    {
+      uint32_t index = 0u;
+      for(auto&& texture : textureInfo.textures)
+      {
+        textureSet.SetTexture(index++, texture);
+      }
+    }
+    else
+    {
+      textureSet.SetTexture(TEXTURE_INDEX, textureInfo.textures[0]);
+      TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureInfo.maskTextureId);
+      if(maskCacheIndex != INVALID_CACHE_INDEX)
+      {
+        TextureInfo& maskTextureInfo(mTextureCacheManager[maskCacheIndex]);
+        if(maskTextureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE || maskTextureInfo.storageType == StorageType::KEEP_TEXTURE)
+        {
+          if(!maskTextureInfo.textures.empty())
+          {
+            textureSet.SetTexture(MASK_TEXTURE_INDEX, maskTextureInfo.textures[0]);
+          }
+        }
+      }
+    }
+  }
+  return textureSet;
+}
+
+void TextureManager::RemoveTextureObserver(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
+{
+  // Remove its observer
+  if(observer)
+  {
+    const auto iterEnd = textureInfo.observerList.End();
+    const auto iter    = std::find(textureInfo.observerList.Begin(), iterEnd, observer);
+    if(iter != iterEnd)
+    {
+      // Disconnect and remove the observer.
+      observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
+      textureInfo.observerList.Erase(iter);
+    }
   }
 }