OpenShot Library | libopenshot  0.5.0
MemoryTrim.cpp
Go to the documentation of this file.
1 
8 // Copyright (c) 2008-2025 OpenShot Studios, LLC
9 //
10 // SPDX-License-Identifier: LGPL-3.0-or-later
11 
12 #include "MemoryTrim.h"
13 
14 #include <atomic>
15 #include <chrono>
16 #include <cstdint>
17 
18 #if defined(__GLIBC__)
19 #include <malloc.h>
20 #elif defined(_WIN32)
21 #include <malloc.h>
22 #elif defined(__APPLE__)
23 #include <malloc/malloc.h>
24 #endif
25 
26 namespace {
27 // Limit trim attempts to once per interval to avoid spamming platform calls
28 constexpr uint64_t kMinTrimIntervalMs = 1000; // 1s debounce
29 std::atomic<uint64_t> g_last_trim_ms{0};
30 std::atomic<bool> g_trim_in_progress{false};
31 
32 uint64_t NowMs() {
33  using namespace std::chrono;
34  return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
35 }
36 } // namespace
37 
38 namespace openshot {
39 
40 bool TrimMemoryToOS(bool force) noexcept {
41  const uint64_t now_ms = NowMs();
42  const uint64_t last_ms = g_last_trim_ms.load(std::memory_order_relaxed);
43 
44  // Skip if we recently trimmed (unless forced)
45  if (!force && now_ms - last_ms < kMinTrimIntervalMs)
46  return false;
47 
48  // Only one trim attempt runs at a time
49  bool expected = false;
50  if (!g_trim_in_progress.compare_exchange_strong(expected, true, std::memory_order_acq_rel))
51  return false;
52 
53  bool did_trim = false;
54 
55 #if defined(__GLIBC__)
56  // GLIBC exposes malloc_trim to release free arenas back to the OS
57  malloc_trim(0);
58  did_trim = true;
59 #elif defined(_WIN32)
60  // MinGW/MSYS2 expose _heapmin to compact the CRT heap
61  _heapmin();
62  did_trim = true;
63 #elif defined(__APPLE__)
64  // macOS uses the malloc zone API to relieve memory pressure
65  malloc_zone_t* zone = malloc_default_zone();
66  malloc_zone_pressure_relief(zone, 0);
67  did_trim = true;
68 #else
69  // Platforms without a known trimming API
70  did_trim = false;
71 #endif
72 
73  if (did_trim)
74  g_last_trim_ms.store(now_ms, std::memory_order_relaxed);
75 
76  g_trim_in_progress.store(false, std::memory_order_release);
77  return did_trim;
78 }
79 
80 } // namespace openshot
openshot
This namespace is the default namespace for all code in the openshot library.
Definition: Compressor.h:28
MemoryTrim.h
Cross-platform helper to encourage returning freed memory to the OS.
openshot::TrimMemoryToOS
bool TrimMemoryToOS(bool force) noexcept
Attempt to return unused heap memory to the operating system.
Definition: MemoryTrim.cpp:40