#pragma once #include #include #include namespace Echoion::Core { // Wall-clock based playback position. Replaces the playbackPosition_ / // playbackBasePosition_ / playbackStartTime_ triple whose reset logic was // duplicated across play/resume/skip/seek/track-finished/restore. // // Lock-free: the engine thread writes, any thread reads a consistent // position (worst case one field is a few ns stale, irrelevant at ms // granularity for UI display). class PositionClock { public: using ms = std::chrono::milliseconds; // Track started from zero (or restarted); clock runs. void restart() { seekTo(ms{0}); running_.store(true); } // Jump to a position and keep running/paused state. void seekTo(ms position) { baseMs_.store(position.count()); startedAtNs_.store(nowNs()); } void pause() { if (!running_.exchange(false)) { return; } baseMs_.store(currentMs()); } void resume() { if (running_.load()) { return; // already running; resetting startedAt would // rewind the position } startedAtNs_.store(nowNs()); running_.store(true); } void stop() { running_.store(false); baseMs_.store(0); } [[nodiscard]] bool running() const { return running_.load(); } [[nodiscard]] ms position() const { return ms{currentMs()}; } private: [[nodiscard]] static int64_t nowNs() { return std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()) .count(); } [[nodiscard]] int64_t currentMs() const { const int64_t base = baseMs_.load(); if (!running_.load()) { return base; } const int64_t elapsedNs = nowNs() - startedAtNs_.load(); return base + elapsedNs / 1'000'000; } std::atomic baseMs_{0}; std::atomic startedAtNs_{0}; std::atomic running_{false}; }; } // namespace Echoion::Core