OpenShot Library | libopenshot  0.5.0
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 
18 using namespace std;
19 using namespace openshot;
20 
21 // Default constructor, no max bytes
22 CacheMemory::CacheMemory() : CacheBase(0) {
23  // Set cache type name
24  cache_type = "CacheMemory";
25  range_version = 0;
26  needs_range_processing = false;
27 }
28 
29 // Constructor that sets the max bytes to cache
30 CacheMemory::CacheMemory(int64_t max_bytes) : CacheBase(max_bytes) {
31  // Set cache type name
32  cache_type = "CacheMemory";
33  range_version = 0;
34  needs_range_processing = false;
35 }
36 
37 // Default destructor
39 {
40  Clear();
41 
42  // remove mutex
43  delete cacheMutex;
44 }
45 
46 // Add a Frame to the cache
47 void 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
72 bool 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)
84 std::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
100 std::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)
117 std::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
158 void CacheMemory::Remove(int64_t frame_number)
159 {
160  Remove(frame_number, frame_number);
161 }
162 
163 // Remove range of frames
164 void 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)
194  needs_range_processing = true;
195 }
196 
197 // Move frame to front of queue (so it lasts longer)
198 void 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();
234  needs_range_processing = true;
235  // Trim freed arenas back to OS after large clears (debounced)
236  TrimMemoryToOS();
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
250 void 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
271 std::string CacheMemory::Json() {
272 
273  // Return formatted string
274  return JsonValue().toStyledString();
275 }
276 
277 // Generate Json::Value for this object
278 Json::Value CacheMemory::JsonValue() {
279 
280  // Process range data (if anything has changed)
281  CalculateRanges();
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
300 void 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
317 void 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 }
openshot::stringToJson
const Json::Value stringToJson(const std::string value)
Definition: Json.cpp:16
openshot::CacheMemory::Clear
void Clear()
Clear the cache of all frames.
Definition: CacheMemory.cpp:224
openshot::CacheMemory::Count
int64_t Count()
Count the frames in the queue.
Definition: CacheMemory.cpp:240
openshot::CacheBase::needs_range_processing
bool needs_range_processing
Something has changed, and the range data needs to be re-calculated.
Definition: CacheBase.h:40
openshot::CacheMemory::GetBytes
int64_t GetBytes()
Gets the maximum bytes value.
Definition: CacheMemory.cpp:140
openshot::CacheMemory::GetFrame
std::shared_ptr< openshot::Frame > GetFrame(int64_t frame_number)
Get a frame from the cache.
Definition: CacheMemory.cpp:84
openshot::CacheBase::max_bytes
int64_t max_bytes
This is the max number of bytes to cache (0 = no limit)
Definition: CacheBase.h:38
openshot::CacheMemory::Add
void Add(std::shared_ptr< openshot::Frame > frame)
Add a Frame to the cache.
Definition: CacheMemory.cpp:47
openshot::CacheBase::ordered_frame_numbers
std::vector< int64_t > ordered_frame_numbers
Ordered list of frame numbers used by cache.
Definition: CacheBase.h:42
openshot
This namespace is the default namespace for all code in the openshot library.
Definition: Compressor.h:28
openshot::CacheBase::json_ranges
std::string json_ranges
JSON ranges of frame numbers.
Definition: CacheBase.h:41
MemoryTrim.h
Cross-platform helper to encourage returning freed memory to the OS.
openshot::CacheMemory::Contains
bool Contains(int64_t frame_number)
Check if frame is already contained in cache.
Definition: CacheMemory.cpp:72
openshot::CacheMemory::Remove
void Remove(int64_t frame_number)
Remove a specific frame.
Definition: CacheMemory.cpp:158
openshot::CacheMemory::JsonValue
Json::Value JsonValue()
Generate Json::Value for this object.
Definition: CacheMemory.cpp:278
openshot::CacheBase
All cache managers in libopenshot are based on this CacheBase class.
Definition: CacheBase.h:34
openshot::CacheBase::SetJsonValue
virtual void SetJsonValue(const Json::Value root)=0
Load Json::Value into this object.
Definition: CacheBase.cpp:111
openshot::CacheMemory::~CacheMemory
virtual ~CacheMemory()
Definition: CacheMemory.cpp:38
openshot::CacheMemory::Touch
void Touch(int64_t frame_number)
Move frame to front of queue (so it lasts longer)
Definition: CacheMemory.cpp:198
openshot::InvalidJSON
Exception for invalid JSON.
Definition: Exceptions.h:217
CacheMemory.h
Header file for CacheMemory class.
openshot::CacheMemory::Json
std::string Json()
Generate JSON string of this object.
Definition: CacheMemory.cpp:271
openshot::CacheBase::JsonValue
virtual Json::Value JsonValue()=0
Generate Json::Value for this object.
Definition: CacheBase.cpp:100
openshot::CacheBase::CalculateRanges
void CalculateRanges()
Calculate ranges of frames.
Definition: CacheBase.cpp:36
Frame.h
Header file for Frame class.
openshot::CacheMemory::GetSmallestFrame
std::shared_ptr< openshot::Frame > GetSmallestFrame()
Get the smallest frame number.
Definition: CacheMemory.cpp:117
openshot::CacheBase::cache_type
std::string cache_type
This is a friendly type name of the derived cache instance.
Definition: CacheBase.h:37
openshot::CacheMemory::CacheMemory
CacheMemory()
Default constructor, no max bytes.
Definition: CacheMemory.cpp:22
openshot::TrimMemoryToOS
bool TrimMemoryToOS() noexcept
Attempt to return unused heap memory to the operating system.
Definition: MemoryTrim.cpp:40
openshot::CacheMemory::SetJson
void SetJson(const std::string value)
Load JSON string into this object.
Definition: CacheMemory.cpp:300
openshot::CacheMemory::SetJsonValue
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: CacheMemory.cpp:317
openshot::CacheMemory::GetFrames
std::vector< std::shared_ptr< openshot::Frame > > GetFrames()
Get an array of all Frames.
Definition: CacheMemory.cpp:100
openshot::CacheBase::range_version
int64_t range_version
The version of the JSON range data (incremented with each change)
Definition: CacheBase.h:44
Exceptions.h
Header file for all Exception classes.
openshot::CacheBase::cacheMutex
std::recursive_mutex * cacheMutex
Mutex for multiple threads.
Definition: CacheBase.h:47