1 parent
df99b6ea7f
commit
d146f11f02
63 files changed
+8331
-2709
No files matched your search
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
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::nanoseconds>(
|
||||
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<int64_t> baseMs_{0};
|
||||
std::atomic<int64_t> startedAtNs_{0};
|
||||
std::atomic<bool> running_{false};
|
||||
};
|
||||
|
||||
} // namespace Echoion::Core
|
||||
Reference in new issue
Block a user