#include "HybridJsFpsTracking.hpp" #include #include #include #include #include #include #include #include #include #include using namespace facebook; namespace margelo::nitro::performancetoolkit { namespace { constexpr double FPS_WINDOW_MS = 1000.0; // Sliding window for FPS calculation (1 second) constexpr double BUFFER_UPDATE_INTERVAL_MS = FPS_WINDOW_MS; // Must be same as FPS_WINDOW_MS otherwise the FPS calculation will be incorrect } // namespace class JsFpsTracker : public std::enable_shared_from_this { public: JsFpsTracker(std::function writer, std::weak_ptr dispatcher) : _writer(std::move(writer)), _dispatcher(std::move(dispatcher)), _framesInWindow(0), _lastJsTickNs(0), _running(true), _taskPending(false) {} ~JsFpsTracker() { stop(); } void start() { startFramePacingLoop(); // High-frequency frame counting startReportingLoop(); // Low-frequency FPS reporting } void stop() { _running = false; stopFramePacingLoop(); stopReportingLoop(); } private: void startFramePacingLoop() { if (_framePacingThread.joinable()) { return; } auto self = shared_from_this(); // Get frame interval dynamically based on device refresh rate // const double frameIntervalMs = RuntimeBridgeState::get().getFrameIntervalMs(); const double frameIntervalMs = 16.666666666666668; // For now fix it to 60 FPS const auto frameInterval = std::chrono::duration_cast( std::chrono::duration(frameIntervalMs)); _framePacingThread = std::thread([self, frameInterval]() { auto nextWake = std::chrono::steady_clock::now(); while (self->_running.load()) { nextWake += frameInterval; std::this_thread::sleep_until(nextWake); if (!self->_running.load()) { break; } // ONLY post a task to JS - no calculations here self->scheduleNextFrame(); } }); } void stopFramePacingLoop() { if (_framePacingThread.joinable()) { auto framePacingThread = std::move(_framePacingThread); if (framePacingThread.get_id() == std::this_thread::get_id()) { framePacingThread.detach(); } else { framePacingThread.join(); } } } void startReportingLoop() { if (_reportingThread.joinable()) { return; } auto self = shared_from_this(); // Reporting thread wakes up only at BUFFER_UPDATE_INTERVAL_MS (1 second) const auto reportInterval = std::chrono::duration_cast( std::chrono::duration(BUFFER_UPDATE_INTERVAL_MS)); _reportingThread = std::thread([self, reportInterval]() { // Initialize lastReportTime auto lastReportTime = std::chrono::steady_clock::now(); while (self->_running.load()) { // Sleep for the full report interval (1 second) std::this_thread::sleep_for(reportInterval); if (!self->_running.load()) { break; } // Calculate FPS based on accumulated frame count const auto now = std::chrono::steady_clock::now(); const auto elapsed = std::chrono::duration_cast(now - lastReportTime); const double windowMs = static_cast(elapsed.count()); // Read and reset frame counter const uint32_t frames = self->_framesInWindow.exchange(0); // Detect JS stall based on last tick timestamp const long long lastTickNs = self->_lastJsTickNs.load(); const auto nowNs = std::chrono::duration_cast(now.time_since_epoch()).count(); const bool jsStalled = (lastTickNs == 0) || ((nowNs - lastTickNs) >= static_cast(FPS_WINDOW_MS * 1'000'000.0)); double fps = 0.0; if (frames > 0 && windowMs > 0.0) { fps = (frames * 1000.0) / windowMs; } else if (jsStalled) { fps = 0.0; } // double deviceMaxFps = RuntimeBridgeState::get().getDeviceRefreshRate(); const double deviceMaxFps = 60.0; // For now fix it to 60 FPS const double cappedFps = std::min(std::round(fps), deviceMaxFps); // Write to native buffer as Int32 (not on JS thread) if (self->_writer) { self->_writer(static_cast(cappedFps)); } // Update lastReportTime for next iteration lastReportTime = now; } }); } void stopReportingLoop() { if (_reportingThread.joinable()) { auto reportingThread = std::move(_reportingThread); if (reportingThread.get_id() == std::this_thread::get_id()) { reportingThread.detach(); } else { reportingThread.join(); } } } void scheduleNextFrame() { if (!_running.load()) { return; } // Check if there's already a task pending to avoid queue buildup bool expected = false; if (!_taskPending.compare_exchange_strong(expected, true)) { return; } auto dispatcher = _dispatcher.lock(); if (!dispatcher) { // JS runtime is gone (teardown / reload in flight). Reset the gate and // try again next frame; a reload will re-install a fresh dispatcher. _taskPending = false; return; } // Capture shared_ptr to keep tracker alive auto self = shared_from_this(); dispatcher->runAsync([self]() { if (!self->_running.load()) { self->_taskPending = false; return; } // Record a JS tick and increment frame counter only const auto nowNs = std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()) .count(); self->_lastJsTickNs.store(nowNs); self->_framesInWindow.fetch_add(1); self->_taskPending = false; }); } std::function _writer; std::weak_ptr _dispatcher; std::atomic _framesInWindow; std::atomic _lastJsTickNs; std::atomic _running; std::atomic _taskPending; std::thread _framePacingThread; std::thread _reportingThread; }; HybridJsFpsTracking::HybridJsFpsTracking() : HybridObject(TAG) {} HybridJsFpsTracking::~HybridJsFpsTracking() { if (_tracker != nullptr) { _tracker->stop(); _tracker.reset(); } } void HybridJsFpsTracking::loadHybridMethods() { HybridJsFpsTrackingSpec::loadHybridMethods(); registerHybrids(this, [](Prototype& prototype) { prototype.registerRawHybridMethod( "__installJsDispatcher", 0, &HybridJsFpsTracking::installJsDispatcher); }); } jsi::Value HybridJsFpsTracking::installJsDispatcher(jsi::Runtime& runtime, const jsi::Value& /* thisValue */, const jsi::Value* /* args */, size_t /* count */) { // The dispatcher is keyed by `jsi::Runtime`, so re-calling this from a fresh // JS runtime (e.g. after a full reload) transparently replaces the stale one. auto dispatcher = Dispatcher::getRuntimeGlobalDispatcher(runtime); { std::lock_guard lock(_startMutex); _jsDispatcher = std::move(dispatcher); } tryStart(); return jsi::Value::undefined(); } void HybridJsFpsTracking::tryStart() { std::lock_guard lock(_startMutex); if (_fpsBuffer == nullptr) { return; } if (_jsDispatcher.expired()) { return; } if (_tracker != nullptr) { return; } auto bufferWeak = std::weak_ptr(_fpsBuffer); auto writer = [bufferWeak](int32_t fpsInt) { if (auto buffer = bufferWeak.lock()) { *reinterpret_cast(buffer->data()) = fpsInt; } }; _tracker = std::make_shared(std::move(writer), _jsDispatcher); _tracker->start(); } std::shared_ptr HybridJsFpsTracking::getJsFpsBuffer() { // Allocate buffer if needed (owning, 4 bytes for one Int32 FPS value) { std::lock_guard lock(_startMutex); if (_fpsBuffer == nullptr) { _fpsBuffer = ArrayBuffer::allocate(sizeof(int32_t)); *reinterpret_cast(_fpsBuffer->data()) = 0; } } // If the dispatcher isn't installed yet (consumer forgot to import // `hybrids.ts` on the JS thread), the tracker starts as soon as it is — and // until then the buffer stays initialized to 0. tryStart(); return _fpsBuffer; } } // namespace margelo::nitro::performancetoolkit