1 /*
2  * Copyright (c) 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 HOS_BUFFER_ALLOCATOR_FACTORY_H
17 #define HOS_BUFFER_ALLOCATOR_FACTORY_H
18 
19 #include "camera.h"
20 #include "ibuffer_allocator.h"
21 #include <functional>
22 #include <map>
23 #include <memory>
24 #include <mutex>
25 
26 namespace OHOS::Camera {
27 #define REGISTER_BUFFER_ALLOCATOR(C, type, ...) \
28     static BufferAllocatorFactory::BufferAllocatorRegister<C> g_reg##C(type, ##__VA_ARGS__)
29 
30 class BufferAllocatorFactory {
31 public:
32     static BufferAllocatorFactory* GetInstance();
33     std::shared_ptr<IBufferAllocator> GetBufferAllocator(const int32_t type);
34 
35     template<typename C> class BufferAllocatorRegister {
36     public:
BufferAllocatorRegister(int32_t type,Args...args)37         template<typename ...Args> BufferAllocatorRegister(int32_t type, Args... args)
38         {
39             BufferAllocatorFactory* factory = BufferAllocatorFactory::GetInstance();
40             if (factory != nullptr) {
41                 factory->allocatorRegisterMap_.emplace(type, [&args...] { return new C(std::forward<Args>(args)...); });
42             }
43         }
44     };
45 
46 private:
47     std::shared_ptr<IBufferAllocator> CreateBufferAllocator(const int32_t type);
48 
49 private:
50     BufferAllocatorFactory() = default;
51     BufferAllocatorFactory(const BufferAllocatorFactory&);
52     BufferAllocatorFactory& operator=(const BufferAllocatorFactory&);
53     BufferAllocatorFactory(BufferAllocatorFactory&&);
54     BufferAllocatorFactory& operator=(BufferAllocatorFactory&&);
55 
56     ~BufferAllocatorFactory() = default;
57 
58     std::mutex lock_;
59     std::map<int32_t, std::weak_ptr<IBufferAllocator>> bufferAllocatorMap_ = {};
60     std::map<int32_t, std::function<IBufferAllocator*()>> allocatorRegisterMap_ = {};
61 };
62 } // namespace OHOS::Camera
63 #endif
64