1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "stream_buffer_cache.h"
17 #include <algorithm>
18 
19 namespace android::hardware::camera::device::V3_4::implementation {
20 
get(uint64_t buffer_id)21 std::shared_ptr<CachedStreamBuffer> StreamBufferCache::get(uint64_t buffer_id) {
22   auto id_match =
23       [buffer_id](const std::shared_ptr<CachedStreamBuffer>& buffer) {
24         return buffer->bufferId() == buffer_id;
25       };
26   std::lock_guard<std::mutex> lock(mutex_);
27   auto found = std::find_if(cache_.begin(), cache_.end(), id_match);
28   return (found != cache_.end()) ? *found : nullptr;
29 }
30 
remove(uint64_t buffer_id)31 void StreamBufferCache::remove(uint64_t buffer_id) {
32   auto id_match =
33       [&buffer_id](const std::shared_ptr<CachedStreamBuffer>& buffer) {
34         return buffer->bufferId() == buffer_id;
35       };
36   std::lock_guard<std::mutex> lock(mutex_);
37   cache_.erase(std::remove_if(cache_.begin(), cache_.end(), id_match));
38 }
39 
update(const StreamBuffer & buffer)40 void StreamBufferCache::update(const StreamBuffer& buffer) {
41   auto id = buffer.bufferId;
42   auto id_match = [id](const std::shared_ptr<CachedStreamBuffer>& buffer) {
43     return buffer->bufferId() == id;
44   };
45   std::lock_guard<std::mutex> lock(mutex_);
46   auto found = std::find_if(cache_.begin(), cache_.end(), id_match);
47   if (found == cache_.end()) {
48     cache_.emplace_back(std::make_shared<CachedStreamBuffer>(buffer));
49   } else {
50     (*found)->importFence(buffer.acquireFence);
51   }
52 }
53 
clear()54 void StreamBufferCache::clear() {
55   std::lock_guard<std::mutex> lock(mutex_);
56   cache_.clear();
57 }
58 
removeStreamsExcept(std::set<int32_t> streams_to_keep)59 void StreamBufferCache::removeStreamsExcept(std::set<int32_t> streams_to_keep) {
60   std::lock_guard<std::mutex> lock(mutex_);
61   for (auto it = cache_.begin(); it != cache_.end();) {
62     if (streams_to_keep.count((*it)->streamId()) == 0) {
63       it = cache_.erase(it);
64     } else {
65       it++;
66     }
67   }
68 }
69 
70 }  // namespace android::hardware::camera::device::V3_4::implementation
71