OpenShot Library | libopenshot 0.6.0
Loading...
Searching...
No Matches
CacheMemory.cpp
Go to the documentation of this file.
1
9// Copyright (c) 2008-2019 OpenShot Studios, LLC
10//
11// SPDX-License-Identifier: LGPL-3.0-or-later
12
13#include "CacheMemory.h"
14#include "Exceptions.h"
15#include "Frame.h"
16#include "MemoryTrim.h"
17
18using namespace std;
19using namespace openshot;
20
21// Default constructor, no max bytes
23 // Set cache type name
24 cache_type = "CacheMemory";
25 range_version = 0;
27}
28
29// Constructor that sets the max bytes to cache
30CacheMemory::CacheMemory(int64_t max_bytes) : CacheBase(max_bytes) {
31 // Set cache type name
32 cache_type = "CacheMemory";
33 range_version = 0;
35}
36
37// Default destructor
39{
40 Clear();
41
42 // remove mutex
43 delete cacheMutex;
44}
45
46// Add a Frame to the cache
47void CacheMemory::Add(std::shared_ptr<Frame> frame)
48{
49 // Create a scoped lock, to protect the cache from multiple threads
50 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
51 int64_t frame_number = frame->number;
52
53 // Freshen frame if it already exists
54 if (frames.count(frame_number))
55 // Move frame to front of queue
56 Touch(frame_number);
57
58 else
59 {
60 // Add frame to queue and map
61 frames[frame_number] = frame;
62 frame_numbers.push_front(frame_number);
63 ordered_frame_numbers.push_back(frame_number);
65
66 // Clean up old frames
67 CleanUp();
68 }
69}
70
71// Check if frame is already contained in cache
72bool CacheMemory::Contains(int64_t frame_number) {
73 // Create a scoped lock, to protect the cache from multiple threads
74 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
75
76 if (frames.count(frame_number) > 0) {
77 return true;
78 } else {
79 return false;
80 }
81}
82
83// Get a frame from the cache (or NULL shared_ptr if no frame is found)
84std::shared_ptr<Frame> CacheMemory::GetFrame(int64_t frame_number)
85{
86 // Create a scoped lock, to protect the cache from multiple threads
87 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
88
89 // Does frame exists in cache?
90 if (frames.count(frame_number))
91 // return the Frame object
92 return frames[frame_number];
93
94 else
95 // no Frame found
96 return std::shared_ptr<Frame>();
97}
98
99// @brief Get an array of all Frames
100std::vector<std::shared_ptr<openshot::Frame>> CacheMemory::GetFrames()
101{
102 // Create a scoped lock, to protect the cache from multiple threads
103 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
104
105 std::vector<std::shared_ptr<openshot::Frame>> all_frames;
106 std::vector<int64_t>::iterator itr_ordered;
107 for(itr_ordered = ordered_frame_numbers.begin(); itr_ordered != ordered_frame_numbers.end(); ++itr_ordered)
108 {
109 int64_t frame_number = *itr_ordered;
110 all_frames.push_back(GetFrame(frame_number));
111 }
112
113 return all_frames;
114}
115
116// Get the smallest frame number (or NULL shared_ptr if no frame is found)
117std::shared_ptr<Frame> CacheMemory::GetSmallestFrame()
118{
119 // Create a scoped lock, to protect the cache from multiple threads
120 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
121
122 // Loop through frame numbers
123 std::deque<int64_t>::iterator itr;
124 int64_t smallest_frame = -1;
125 for(itr = frame_numbers.begin(); itr != frame_numbers.end(); ++itr)
126 {
127 if (*itr < smallest_frame || smallest_frame == -1)
128 smallest_frame = *itr;
129 }
130
131 // Return frame (if any)
132 if (smallest_frame != -1) {
133 return frames[smallest_frame];
134 } else {
135 return NULL;
136 }
137}
138
139// Gets the maximum bytes value
141{
142 // Create a scoped lock, to protect the cache from multiple threads
143 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
144
145 int64_t total_bytes = 0;
146
147 // Loop through frames, and calculate total bytes
148 std::deque<int64_t>::reverse_iterator itr;
149 for(itr = frame_numbers.rbegin(); itr != frame_numbers.rend(); ++itr)
150 {
151 total_bytes += frames[*itr]->GetBytes();
152 }
153
154 return total_bytes;
155}
156
157// Remove a specific frame
158void CacheMemory::Remove(int64_t frame_number)
159{
160 Remove(frame_number, frame_number);
161}
162
163// Remove range of frames
164void CacheMemory::Remove(int64_t start_frame_number, int64_t end_frame_number)
165{
166 // Create a scoped lock, to protect the cache from multiple threads
167 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
168 // Loop through frame numbers
169 std::deque<int64_t>::iterator itr;
170 for(itr = frame_numbers.begin(); itr != frame_numbers.end();)
171 {
172 if (*itr >= start_frame_number && *itr <= end_frame_number)
173 {
174 // erase frame number
175 itr = frame_numbers.erase(itr);
176 }else
177 itr++;
178 }
179
180 // Loop through ordered frame numbers
181 std::vector<int64_t>::iterator itr_ordered;
182 for(itr_ordered = ordered_frame_numbers.begin(); itr_ordered != ordered_frame_numbers.end();)
183 {
184 if (*itr_ordered >= start_frame_number && *itr_ordered <= end_frame_number)
185 {
186 // erase frame number
187 frames.erase(*itr_ordered);
188 itr_ordered = ordered_frame_numbers.erase(itr_ordered);
189 }else
190 itr_ordered++;
191 }
192
193 // Needs range processing (since cache has changed)
195}
196
197// Move frame to front of queue (so it lasts longer)
198void CacheMemory::Touch(int64_t frame_number)
199{
200 // Create a scoped lock, to protect the cache from multiple threads
201 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
202
203 // Does frame exists in cache?
204 if (frames.count(frame_number))
205 {
206 // Loop through frame numbers
207 std::deque<int64_t>::iterator itr;
208 for(itr = frame_numbers.begin(); itr != frame_numbers.end(); ++itr)
209 {
210 if (*itr == frame_number)
211 {
212 // erase frame number
213 frame_numbers.erase(itr);
214
215 // add frame number to 'front' of queue
216 frame_numbers.push_front(frame_number);
217 break;
218 }
219 }
220 }
221}
222
223// Clear the cache of all frames
225{
226 // Create a scoped lock, to protect the cache from multiple threads
227 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
228
229 frames.clear();
230 frame_numbers.clear();
231 frame_numbers.shrink_to_fit();
232 ordered_frame_numbers.clear();
233 ordered_frame_numbers.shrink_to_fit();
235 // Trim freed arenas back to OS after large clears (debounced)
237}
238
239// Count the frames in the queue
241{
242 // Create a scoped lock, to protect the cache from multiple threads
243 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
244
245 // Return the number of frames in the cache
246 return frames.size();
247}
248
249// Clean up cached frames that exceed the number in our max_bytes variable
250void CacheMemory::CleanUp()
251{
252 // Do we auto clean up?
253 if (max_bytes > 0)
254 {
255 // Create a scoped lock, to protect the cache from multiple threads
256 const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
257
258 while (GetBytes() > max_bytes && frame_numbers.size() > 20)
259 {
260 // Get the oldest frame number.
261 int64_t frame_to_remove = frame_numbers.back();
262
263 // Remove frame_number and frame
264 Remove(frame_to_remove);
265 }
266 }
267}
268
269
270// Generate JSON string of this object
271std::string CacheMemory::Json() {
272
273 // Return formatted string
274 return JsonValue().toStyledString();
275}
276
277// Generate Json::Value for this object
279
280 // Process range data (if anything has changed)
282
283 // Create root json object
284 Json::Value root = CacheBase::JsonValue(); // get parent properties
285 root["type"] = cache_type;
286
287 root["version"] = std::to_string(range_version);
288
289 // Parse and append range data (if any)
290 try {
291 const Json::Value ranges = openshot::stringToJson(json_ranges);
292 root["ranges"] = ranges;
293 } catch (...) { }
294
295 // return JsonValue
296 return root;
297}
298
299// Load JSON string into this object
300void CacheMemory::SetJson(const std::string value) {
301
302 try
303 {
304 // Parse string to Json::Value
305 const Json::Value root = openshot::stringToJson(value);
306 // Set all values that match
307 SetJsonValue(root);
308 }
309 catch (const std::exception& e)
310 {
311 // Error parsing JSON (or missing keys)
312 throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
313 }
314}
315
316// Load Json::Value into this object
317void CacheMemory::SetJsonValue(const Json::Value root) {
318
319 // Close timeline before we do anything (this also removes all open and closing clips)
320 Clear();
321
322 // Set parent data
324
325 if (!root["type"].isNull())
326 cache_type = root["type"].asString();
327}
Header file for CacheMemory class.
Header file for all Exception classes.
Header file for Frame class.
Cross-platform helper to encourage returning freed memory to the OS.
All cache managers in libopenshot are based on this CacheBase class.
Definition CacheBase.h:35
int64_t range_version
The version of the JSON range data (incremented with each change)
Definition CacheBase.h:44
virtual Json::Value JsonValue()=0
Generate Json::Value for this object.
std::string cache_type
This is a friendly type name of the derived cache instance.
Definition CacheBase.h:37
void CalculateRanges()
Calculate ranges of frames.
Definition CacheBase.cpp:36
virtual void SetJsonValue(const Json::Value root)=0
Load Json::Value into this object.
bool needs_range_processing
Something has changed, and the range data needs to be re-calculated.
Definition CacheBase.h:40
int64_t max_bytes
This is the max number of bytes to cache (0 = no limit)
Definition CacheBase.h:38
std::recursive_mutex * cacheMutex
Mutex for multiple threads.
Definition CacheBase.h:47
std::string json_ranges
JSON ranges of frame numbers.
Definition CacheBase.h:41
std::vector< int64_t > ordered_frame_numbers
Ordered list of frame numbers used by cache.
Definition CacheBase.h:42
CacheMemory()
Default constructor, no max bytes.
int64_t Count()
Count the frames in the queue.
void Add(std::shared_ptr< openshot::Frame > frame)
Add a Frame to the cache.
void SetJson(const std::string value)
Load JSON string into this object.
int64_t GetBytes()
Gets the maximum bytes value.
std::string Json()
Generate JSON string of this object.
std::shared_ptr< openshot::Frame > GetFrame(int64_t frame_number)
Get a frame from the cache.
std::vector< std::shared_ptr< openshot::Frame > > GetFrames()
Get an array of all Frames.
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
void Remove(int64_t frame_number)
Remove a specific frame.
void Clear()
Clear the cache of all frames.
Json::Value JsonValue()
Generate Json::Value for this object.
void Touch(int64_t frame_number)
Move frame to front of queue (so it lasts longer)
bool Contains(int64_t frame_number)
Check if frame is already contained in cache.
std::shared_ptr< openshot::Frame > GetSmallestFrame()
Get the smallest frame number.
Exception for invalid JSON.
Definition Exceptions.h:224
This namespace is the default namespace for all code in the openshot library.
Definition Compressor.h:29
bool TrimMemoryToOS() noexcept
Attempt to return unused heap memory to the operating system.
const Json::Value stringToJson(const std::string value)
Definition Json.cpp:16