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  if (frames.count(frame_number) > 0) {
74  return true;
75  } else {
76  return false;
77  }
78 }
79 
80 // Get a frame from the cache (or NULL shared_ptr if no frame is found)
81 std::shared_ptr<Frame> CacheMemory::GetFrame(int64_t frame_number)
82 {
83  // Create a scoped lock, to protect the cache from multiple threads
84  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
85 
86  // Does frame exists in cache?
87  if (frames.count(frame_number))
88  // return the Frame object
89  return frames[frame_number];
90 
91  else
92  // no Frame found
93  return std::shared_ptr<Frame>();
94 }
95 
96 // @brief Get an array of all Frames
97 std::vector<std::shared_ptr<openshot::Frame>> CacheMemory::GetFrames()
98 {
99  // Create a scoped lock, to protect the cache from multiple threads
100  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
101 
102  std::vector<std::shared_ptr<openshot::Frame>> all_frames;
103  std::vector<int64_t>::iterator itr_ordered;
104  for(itr_ordered = ordered_frame_numbers.begin(); itr_ordered != ordered_frame_numbers.end(); ++itr_ordered)
105  {
106  int64_t frame_number = *itr_ordered;
107  all_frames.push_back(GetFrame(frame_number));
108  }
109 
110  return all_frames;
111 }
112 
113 // Get the smallest frame number (or NULL shared_ptr if no frame is found)
114 std::shared_ptr<Frame> CacheMemory::GetSmallestFrame()
115 {
116  // Create a scoped lock, to protect the cache from multiple threads
117  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
118 
119  // Loop through frame numbers
120  std::deque<int64_t>::iterator itr;
121  int64_t smallest_frame = -1;
122  for(itr = frame_numbers.begin(); itr != frame_numbers.end(); ++itr)
123  {
124  if (*itr < smallest_frame || smallest_frame == -1)
125  smallest_frame = *itr;
126  }
127 
128  // Return frame (if any)
129  if (smallest_frame != -1) {
130  return frames[smallest_frame];
131  } else {
132  return NULL;
133  }
134 }
135 
136 // Gets the maximum bytes value
138 {
139  // Create a scoped lock, to protect the cache from multiple threads
140  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
141 
142  int64_t total_bytes = 0;
143 
144  // Loop through frames, and calculate total bytes
145  std::deque<int64_t>::reverse_iterator itr;
146  for(itr = frame_numbers.rbegin(); itr != frame_numbers.rend(); ++itr)
147  {
148  total_bytes += frames[*itr]->GetBytes();
149  }
150 
151  return total_bytes;
152 }
153 
154 // Remove a specific frame
155 void CacheMemory::Remove(int64_t frame_number)
156 {
157  Remove(frame_number, frame_number);
158 }
159 
160 // Remove range of frames
161 void CacheMemory::Remove(int64_t start_frame_number, int64_t end_frame_number)
162 {
163  // Create a scoped lock, to protect the cache from multiple threads
164  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
165  // Loop through frame numbers
166  std::deque<int64_t>::iterator itr;
167  for(itr = frame_numbers.begin(); itr != frame_numbers.end();)
168  {
169  if (*itr >= start_frame_number && *itr <= end_frame_number)
170  {
171  // erase frame number
172  itr = frame_numbers.erase(itr);
173  }else
174  itr++;
175  }
176 
177  // Loop through ordered frame numbers
178  std::vector<int64_t>::iterator itr_ordered;
179  for(itr_ordered = ordered_frame_numbers.begin(); itr_ordered != ordered_frame_numbers.end();)
180  {
181  if (*itr_ordered >= start_frame_number && *itr_ordered <= end_frame_number)
182  {
183  // erase frame number
184  frames.erase(*itr_ordered);
185  itr_ordered = ordered_frame_numbers.erase(itr_ordered);
186  }else
187  itr_ordered++;
188  }
189 
190  // Needs range processing (since cache has changed)
191  needs_range_processing = true;
192 }
193 
194 // Move frame to front of queue (so it lasts longer)
195 void CacheMemory::Touch(int64_t frame_number)
196 {
197  // Create a scoped lock, to protect the cache from multiple threads
198  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
199 
200  // Does frame exists in cache?
201  if (frames.count(frame_number))
202  {
203  // Loop through frame numbers
204  std::deque<int64_t>::iterator itr;
205  for(itr = frame_numbers.begin(); itr != frame_numbers.end(); ++itr)
206  {
207  if (*itr == frame_number)
208  {
209  // erase frame number
210  frame_numbers.erase(itr);
211 
212  // add frame number to 'front' of queue
213  frame_numbers.push_front(frame_number);
214  break;
215  }
216  }
217  }
218 }
219 
220 // Clear the cache of all frames
222 {
223  // Create a scoped lock, to protect the cache from multiple threads
224  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
225 
226  frames.clear();
227  frame_numbers.clear();
228  frame_numbers.shrink_to_fit();
229  ordered_frame_numbers.clear();
230  ordered_frame_numbers.shrink_to_fit();
231  needs_range_processing = true;
232  // Trim freed arenas back to OS after large clears (debounced)
233  TrimMemoryToOS();
234 }
235 
236 // Count the frames in the queue
238 {
239  // Create a scoped lock, to protect the cache from multiple threads
240  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
241 
242  // Return the number of frames in the cache
243  return frames.size();
244 }
245 
246 // Clean up cached frames that exceed the number in our max_bytes variable
247 void CacheMemory::CleanUp()
248 {
249  // Do we auto clean up?
250  if (max_bytes > 0)
251  {
252  // Create a scoped lock, to protect the cache from multiple threads
253  const std::lock_guard<std::recursive_mutex> lock(*cacheMutex);
254 
255  while (GetBytes() > max_bytes && frame_numbers.size() > 20)
256  {
257  // Get the oldest frame number.
258  int64_t frame_to_remove = frame_numbers.back();
259 
260  // Remove frame_number and frame
261  Remove(frame_to_remove);
262  }
263  }
264 }
265 
266 
267 // Generate JSON string of this object
268 std::string CacheMemory::Json() {
269 
270  // Return formatted string
271  return JsonValue().toStyledString();
272 }
273 
274 // Generate Json::Value for this object
275 Json::Value CacheMemory::JsonValue() {
276 
277  // Process range data (if anything has changed)
278  CalculateRanges();
279 
280  // Create root json object
281  Json::Value root = CacheBase::JsonValue(); // get parent properties
282  root["type"] = cache_type;
283 
284  root["version"] = std::to_string(range_version);
285 
286  // Parse and append range data (if any)
287  try {
288  const Json::Value ranges = openshot::stringToJson(json_ranges);
289  root["ranges"] = ranges;
290  } catch (...) { }
291 
292  // return JsonValue
293  return root;
294 }
295 
296 // Load JSON string into this object
297 void CacheMemory::SetJson(const std::string value) {
298 
299  try
300  {
301  // Parse string to Json::Value
302  const Json::Value root = openshot::stringToJson(value);
303  // Set all values that match
304  SetJsonValue(root);
305  }
306  catch (const std::exception& e)
307  {
308  // Error parsing JSON (or missing keys)
309  throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
310  }
311 }
312 
313 // Load Json::Value into this object
314 void CacheMemory::SetJsonValue(const Json::Value root) {
315 
316  // Close timeline before we do anything (this also removes all open and closing clips)
317  Clear();
318 
319  // Set parent data
321 
322  if (!root["type"].isNull())
323  cache_type = root["type"].asString();
324 }
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:221
openshot::CacheMemory::Count
int64_t Count()
Count the frames in the queue.
Definition: CacheMemory.cpp:237
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:137
openshot::CacheMemory::GetFrame
std::shared_ptr< openshot::Frame > GetFrame(int64_t frame_number)
Get a frame from the cache.
Definition: CacheMemory.cpp:81
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:155
openshot::CacheMemory::JsonValue
Json::Value JsonValue()
Generate Json::Value for this object.
Definition: CacheMemory.cpp:275
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:195
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:268
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:114
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:297
openshot::CacheMemory::SetJsonValue
void SetJsonValue(const Json::Value root)
Load Json::Value into this object.
Definition: CacheMemory.cpp:314
openshot::CacheMemory::GetFrames
std::vector< std::shared_ptr< openshot::Frame > > GetFrames()
Get an array of all Frames.
Definition: CacheMemory.cpp:97
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