OpenShot Library | libopenshot 1.1.1
Loading...
Searching...
No Matches
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
26namespace {
27// Limit trim attempts to once per interval to avoid spamming platform calls
28constexpr uint64_t kMinTrimIntervalMs = 30000; // 30s debounce
29std::atomic<uint64_t> g_last_trim_ms{0};
30std::atomic<bool> g_trim_in_progress{false};
31
32uint64_t NowMs() {
33 using namespace std::chrono;
34 return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
35}
36} // namespace
37
38namespace openshot {
39
40bool TrimMemoryToOS() 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
45 if (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
77 g_trim_in_progress.store(false, std::memory_order_release);
78 return did_trim;
79}
80
81} // namespace openshot
Cross-platform helper to encourage returning freed memory to the OS.
This namespace is the default namespace for all code in the openshot library.
bool TrimMemoryToOS() noexcept
Attempt to return unused heap memory to the operating system.