| 38 | namespace openshot { |
| 39 | |
| 40 | bool 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 |