1 /* 2 * Copyright (c) 2021-2021 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 HISTREAMER_PIPELINE_FILTER_FACTORY_H 17 #define HISTREAMER_PIPELINE_FILTER_FACTORY_H 18 19 #include <functional> 20 #include <memory> 21 #include <string> 22 #include <unordered_map> 23 24 #include "pipeline/core/filter.h" 25 26 namespace OHOS { 27 namespace Media { 28 using InstanceGenerator = std::function<std::shared_ptr<Pipeline::Filter>(const std::string&)>; 29 30 class FilterFactory { 31 public: 32 ~FilterFactory() = default; 33 34 FilterFactory(const FilterFactory&) = delete; 35 36 FilterFactory operator=(const FilterFactory&) = delete; 37 38 static FilterFactory& Instance(); 39 40 void Init(); 41 42 void RegisterGenerator(const std::string& name, const InstanceGenerator& generator); 43 44 std::shared_ptr<Pipeline::Filter> CreateFilter(const std::string& filterName, const std::string& aliasName); 45 46 template <typename T> CreateFilterWithType(const std::string & filterName,const std::string & aliasName)47 std::shared_ptr<T> CreateFilterWithType(const std::string& filterName, const std::string& aliasName) 48 { 49 auto filter = CreateFilter(filterName, aliasName); 50 auto typedFilter = std::dynamic_pointer_cast<T>(filter); 51 return typedFilter; 52 } 53 54 template <typename T> RegisterFilter(const std::string & name)55 void RegisterFilter(const std::string& name) 56 { 57 RegisterGenerator(name, [](const std::string& aliaName) { return std::make_shared<T>(aliaName); }); 58 } 59 60 private: 61 FilterFactory() = default; 62 63 std::unordered_map<std::string, InstanceGenerator> generators; 64 }; 65 66 template <typename T> 67 class AutoRegisterFilter { 68 public: AutoRegisterFilter(const std::string & name)69 explicit AutoRegisterFilter(const std::string& name) 70 { 71 FilterFactory::Instance().RegisterFilter<T>(name); 72 } 73 AutoRegisterFilter(const std::string & name,const InstanceGenerator & generator)74 AutoRegisterFilter(const std::string& name, const InstanceGenerator& generator) 75 { 76 FilterFactory::Instance().RegisterGenerator(name, generator); 77 } 78 79 ~AutoRegisterFilter() = default; 80 }; 81 } // namespace Media 82 } // namespace OHOS 83 #endif // HISTREAMER_PIPELINE_FILTER_FACTORY_H 84