1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_SHADER_CACHE_H 17 #define OHOS_SHADER_CACHE_H 18 #include "image/gpu_context.h" 19 #include <mutex> 20 #include <memory> 21 #include <string> 22 #include <vector> 23 #include "cache_data.h" 24 25 namespace OHOS { 26 namespace Rosen { 27 class ShaderCache : public Drawing::GPUContextOptions::PersistentCache { 28 public: 29 static ShaderCache& Instance(); 30 31 struct OptionalLockGuard { OptionalLockGuardOptionalLockGuard32 explicit OptionalLockGuard(std::mutex& m): mtx(m), status(m.try_lock()) {} 33 ~OptionalLockGuardOptionalLockGuard34 ~OptionalLockGuard() 35 { 36 if (status) { 37 mtx.unlock(); 38 } 39 } 40 41 OptionalLockGuard(const OptionalLockGuard&) = delete; 42 OptionalLockGuard& operator=(const OptionalLockGuard&) = delete; 43 44 std::mutex& mtx; 45 bool status = false; 46 }; 47 48 virtual void InitShaderCache(const char *identity, const size_t size, bool isUni); InitShaderCache()49 virtual void InitShaderCache() 50 { 51 InitShaderCache(nullptr, 0, false); 52 } 53 54 virtual void SetFilePath(const std::string& filename); 55 56 std::shared_ptr<Drawing::Data> Load(const Drawing::Data &key) override; 57 void Store(const Drawing::Data &key, const Drawing::Data &data) override; 58 IfInitialized()59 bool IfInitialized() const 60 { 61 return initialized_; 62 } 63 64 size_t QuerryShaderSize() const; 65 66 size_t QuerryShaderNum() const; 67 68 void CleanAllShaders() const; 69 70 private: 71 ShaderCache() = default; 72 ~ShaderCache(); 73 ShaderCache(const ShaderCache &) = delete; 74 void operator=(const ShaderCache &) = delete; 75 76 void WriteToDisk(); 77 78 bool initialized_ = false; 79 std::unique_ptr<CacheData> cacheData_; 80 std::string filePath_; 81 std::vector<uint8_t> idHash_; 82 mutable std::mutex mutex_; 83 84 bool savePending_ = false; 85 unsigned int saveDelaySeconds_ = 3; 86 87 size_t bufferSize_ = 16 * 1024; 88 bool cacheDirty_ = false; 89 90 static constexpr uint8_t ID_KEY = 0; 91 92 static constexpr size_t MAX_KEY_SIZE = 1024; 93 static constexpr size_t MAX_VALUE_SIZE = MAX_KEY_SIZE * 1024; 94 static constexpr size_t MAX_TOTAL_SIZE = MAX_VALUE_SIZE * 4; 95 static constexpr size_t MAX_UNIRENDER_SIZE = MAX_VALUE_SIZE * 10; 96 }; 97 } // namespace Rosen 98 } // namespace OHOS 99 #endif // OHOS_SHADER_CACHE_H 100