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  #include "buffer_manager.h"
17  #include <sys/time.h>
18  #include <cinttypes>
19  #include "buffer_pool.h"
20  
21  namespace OHOS::Camera {
GetInstance()22  BufferManager* BufferManager::GetInstance()
23  {
24      static BufferManager manager;
25      return &manager;
26  }
27  
GenerateBufferPoolId()28  uint64_t BufferManager::GenerateBufferPoolId()
29  {
30      std::lock_guard<std::mutex> l(lock_);
31  
32      struct timeval tv;
33      gettimeofday(&tv, NULL);
34      uint64_t id = static_cast<uint64_t>(tv.tv_sec) * 1000 * 1000 + tv.tv_usec; // 1000:usec
35  
36      std::shared_ptr<IBufferPool> bufferPool = nullptr;
37      bufferPoolMap_[id] = bufferPool;
38  
39      return id;
40  }
41  
GetBufferPool(uint64_t id)42  std::shared_ptr<IBufferPool> BufferManager::GetBufferPool(uint64_t id)
43  {
44      std::lock_guard<std::mutex> l(lock_);
45  
46      if (bufferPoolMap_.find(id) == bufferPoolMap_.end()) {
47          return nullptr;
48      }
49  
50      if (bufferPoolMap_[id].expired()) {
51          std::shared_ptr<IBufferPool> bufferPool = std::make_shared<BufferPool>();
52          if (bufferPool == nullptr) {
53              CAMERA_LOGE("bufferPool is nullptr id: %{public}" PRIu64 "", id);
54              return nullptr;
55          }
56          bufferPoolMap_[id] = bufferPool;
57          bufferPool->SetId(id);
58          return bufferPool;
59      }
60  
61      return bufferPoolMap_[id].lock();
62  }
63  
EraseBufferPoolMapById(uint64_t id)64  void BufferManager::EraseBufferPoolMapById(uint64_t id)
65  {
66      std::lock_guard<std::mutex> l(lock_);
67      auto findIter = bufferPoolMap_.find(id);
68      if (findIter != bufferPoolMap_.end()) {
69          bufferPoolMap_.erase(findIter);
70      }
71  }
72  } // namespace OHOS::Camera
73