423 lines
14 KiB
C++
423 lines
14 KiB
C++
#include <chrono>
|
|
#include <thread>
|
|
#include "vslam/replay_source.h"
|
|
|
|
#include <atomic>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <vector>
|
|
|
|
#include "vslam/log.h"
|
|
#include "vslam/record_io.h"
|
|
#include "vslam/scan_sanitizer.h"
|
|
|
|
namespace vslam {
|
|
namespace {
|
|
|
|
// Bon lop duoi day la interface driver THAT, chi khac o cho nguon du lieu la
|
|
// file chu khong phai socket. vslam_node khong phan biet duoc -- do la muc
|
|
// dich.
|
|
//
|
|
// Chung khong tu chay: ReplaySource::Run() day du lieu vao chung. Open()/
|
|
// Close() chi bat/tat co, vi vong doi thuc do ReplaySource quan.
|
|
|
|
class ReplayLidar : public LidarInterface {
|
|
public:
|
|
void SetCallback(ScanCallback cb) override { cb_ = std::move(cb); }
|
|
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
|
|
void Close() override { open_ = false; }
|
|
DriverStats Stats() const override { return stats_; }
|
|
|
|
void Push(LaserScanPtr scan) {
|
|
if (!open_ || !cb_) return;
|
|
stats_.frames++;
|
|
stats_.connected = true;
|
|
cb_(std::move(scan));
|
|
}
|
|
|
|
private:
|
|
ScanCallback cb_;
|
|
bool open_ = false;
|
|
DriverStats stats_;
|
|
};
|
|
|
|
class ReplayCamera : public CameraInterface {
|
|
public:
|
|
void SetCallback(FrameCallback cb) override { cb_ = std::move(cb); }
|
|
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
|
|
void Close() override { open_ = false; }
|
|
DriverStats Stats() const override { return stats_; }
|
|
|
|
void Push(const CameraFrame& f) {
|
|
if (!open_ || !cb_) return;
|
|
stats_.frames++;
|
|
stats_.connected = true;
|
|
cb_(f);
|
|
}
|
|
|
|
private:
|
|
FrameCallback cb_;
|
|
bool open_ = false;
|
|
DriverStats stats_;
|
|
};
|
|
|
|
class ReplayMcu : public McuInterface {
|
|
public:
|
|
void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); }
|
|
void SetBaroCallback(BaroCallback cb) override { baro_cb_ = std::move(cb); }
|
|
void SetUltrasonicCallback(UltrasonicCallback cb) override { us_cb_ = std::move(cb); }
|
|
void SetBumperCallback(BumperCallback cb) override { bumper_cb_ = std::move(cb); }
|
|
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
|
|
void Close() override { open_ = false; }
|
|
DriverStats Stats() const override { return stats_; }
|
|
|
|
void PushImu(ImuPtr imu) {
|
|
if (!open_ || !imu_cb_) return;
|
|
stats_.frames++;
|
|
stats_.connected = true;
|
|
imu_cb_(std::move(imu));
|
|
}
|
|
void PushBaro(const FluidPressure& p, const Temperature& t) {
|
|
if (!open_ || !baro_cb_) return;
|
|
baro_cb_(p, t);
|
|
}
|
|
|
|
private:
|
|
ImuCallback imu_cb_;
|
|
BaroCallback baro_cb_;
|
|
UltrasonicCallback us_cb_;
|
|
BumperCallback bumper_cb_;
|
|
|
|
public:
|
|
void PushUltrasonic(const UltrasonicReading& u) { if (us_cb_) us_cb_(u); }
|
|
void PushBumper(const BumperReading& b) { if (bumper_cb_) bumper_cb_(b); }
|
|
|
|
private:
|
|
bool open_ = false;
|
|
DriverStats stats_;
|
|
};
|
|
|
|
class ReplayBase : public BaseInterface {
|
|
public:
|
|
void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); }
|
|
|
|
// Lenh motor khi replay di vao hu khong -- KHONG co banh xe nao quay.
|
|
// Dem lai de bai regression kiem duoc rang he thong DA ra lenh dung, du
|
|
// khong co gi de thuc thi.
|
|
void SetVelocity(double linear, double angular) override {
|
|
std::lock_guard<std::mutex> lk(mu_);
|
|
last_linear_ = linear;
|
|
last_angular_ = angular;
|
|
cmds_++;
|
|
}
|
|
|
|
StatusResponse Open() override { open_ = true; return StatusResponse::Ok(); }
|
|
void Close() override { open_ = false; }
|
|
DriverStats Stats() const override { return stats_; }
|
|
|
|
void Push(const EncoderReading& e) {
|
|
if (!open_ || !cb_) return;
|
|
stats_.frames++;
|
|
stats_.connected = true;
|
|
cb_(e);
|
|
}
|
|
|
|
void LastCommand(double* lin, double* ang, uint64_t* n) const {
|
|
std::lock_guard<std::mutex> lk(mu_);
|
|
*lin = last_linear_;
|
|
*ang = last_angular_;
|
|
*n = cmds_;
|
|
}
|
|
|
|
private:
|
|
EncoderCallback cb_;
|
|
bool open_ = false;
|
|
DriverStats stats_;
|
|
mutable std::mutex mu_;
|
|
double last_linear_ = 0.0;
|
|
double last_angular_ = 0.0;
|
|
uint64_t cmds_ = 0;
|
|
};
|
|
|
|
} // namespace
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
struct ReplaySource::Impl {
|
|
ReplayConfig cfg;
|
|
RecordReader reader;
|
|
|
|
ReplayLidar lidar;
|
|
ReplayCamera camera;
|
|
ReplayMcu mcu;
|
|
ReplayBase base;
|
|
|
|
std::shared_ptr<ReplayClock> clock;
|
|
std::unique_ptr<ScanSanitizer> sanitizer;
|
|
|
|
std::atomic<bool> stop{false};
|
|
mutable std::mutex stats_mu;
|
|
Stats stats;
|
|
|
|
// Khung camera duoc rap tu nhieu chunk (depth, infra1, infra2, camera_info)
|
|
// roi phat mot lan khi thay chunk depth ke tiep hoac khi het file.
|
|
CameraFrame pending_frame;
|
|
bool have_pending = false;
|
|
std::vector<uint8_t> depth_storage;
|
|
std::vector<uint8_t> infra1_storage;
|
|
std::vector<uint8_t> infra2_storage;
|
|
CameraInfo last_info;
|
|
bool have_info = false;
|
|
|
|
explicit Impl(ReplayConfig c) : cfg(std::move(c)) {}
|
|
|
|
void FlushCameraFrame() {
|
|
if (!have_pending) return;
|
|
if (have_info) pending_frame.depth_info = last_info;
|
|
camera.Push(pending_frame);
|
|
{
|
|
std::lock_guard<std::mutex> lk(stats_mu);
|
|
stats.camera_frames++;
|
|
}
|
|
have_pending = false;
|
|
pending_frame = CameraFrame{};
|
|
}
|
|
};
|
|
|
|
ReplaySource::ReplaySource(ReplayConfig cfg)
|
|
: impl_(std::make_unique<Impl>(std::move(cfg))) {}
|
|
|
|
ReplaySource::~ReplaySource() { RequestStop(); }
|
|
|
|
StatusResponse ReplaySource::Open() {
|
|
const StatusResponse st = impl_->reader.Open(impl_->cfg.path);
|
|
if (!st.ok()) return st;
|
|
|
|
impl_->clock = MakeReplayClock(impl_->reader.info().start_stamp);
|
|
impl_->clock->SetSpeed(impl_->cfg.deterministic ? 0.0 : impl_->cfg.speed);
|
|
|
|
if (impl_->cfg.apply_sanitizer) {
|
|
try {
|
|
impl_->sanitizer = std::make_unique<ScanSanitizer>(impl_->cfg.sanitizer);
|
|
} catch (const std::exception& e) {
|
|
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
|
std::string("sanitizer: ") + e.what());
|
|
}
|
|
}
|
|
|
|
VSLAM_INFO("replay: mo " << impl_->cfg.path << ", bat dau tu "
|
|
<< impl_->reader.info().start_stamp.toString()
|
|
<< (impl_->cfg.deterministic ? " (che do tat dinh)" : ""));
|
|
return StatusResponse::Ok();
|
|
}
|
|
|
|
ClockPtr ReplaySource::clock() const { return impl_->clock; }
|
|
LidarInterface* ReplaySource::lidar() { return &impl_->lidar; }
|
|
CameraInterface* ReplaySource::camera() { return &impl_->camera; }
|
|
McuInterface* ReplaySource::mcu() { return &impl_->mcu; }
|
|
BaseInterface* ReplaySource::base() { return &impl_->base; }
|
|
|
|
const std::string& ReplaySource::recorded_config_json() const {
|
|
return impl_->reader.info().config_json;
|
|
}
|
|
|
|
void ReplaySource::RequestStop() { impl_->stop.store(true); }
|
|
|
|
void ReplaySource::Run() {
|
|
VsrChunkHeader h;
|
|
std::string payload;
|
|
|
|
const UnixTime file_start = impl_->reader.info().start_stamp;
|
|
UnixTime first_stamp;
|
|
bool have_first = false;
|
|
// Moc de dong bo thoi gian tuong khi phat theo thoi gian that.
|
|
bool have_play_origin = false;
|
|
std::chrono::steady_clock::time_point play_origin_wall;
|
|
UnixTime play_origin_stamp;
|
|
UnixTime last_stamp;
|
|
|
|
while (!impl_->stop.load() && impl_->reader.Next(&h, &payload)) {
|
|
const UnixTime stamp = UnixTime::fromNSec(static_cast<int64_t>(h.stamp_ns));
|
|
if (!have_first) {
|
|
first_stamp = stamp;
|
|
have_first = true;
|
|
// Dat dong ho ao theo chunk DAU TIEN, khong theo start_stamp cua header.
|
|
//
|
|
// start_stamp la thoi diem writer MO FILE, do dong ho tuong cua may ghi.
|
|
// No khong nhat thiet trung voi moc thoi gian cua du lieu: mot ban ghi
|
|
// chuyen doi tu nguon khac, hoac mot may co dong ho sai, se lech han.
|
|
// Neu lay theo header thi SetNow() tu choi lui va dong ho ao ket o thoi
|
|
// gian that -- moi phep timeout theo stamp sau do deu sai.
|
|
//
|
|
// allow_backward chi o DUNG lan dau nay.
|
|
impl_->clock->SetNow(stamp, /*allow_backward=*/true);
|
|
}
|
|
last_stamp = stamp;
|
|
|
|
// Cua so start/duration.
|
|
const double rel = SecondsBetween(stamp, first_stamp);
|
|
if (rel < impl_->cfg.start_sec) {
|
|
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
|
impl_->stats.skipped++;
|
|
continue;
|
|
}
|
|
if (impl_->cfg.duration_sec > 0.0 &&
|
|
rel > impl_->cfg.start_sec + impl_->cfg.duration_sec) {
|
|
break;
|
|
}
|
|
|
|
// Lai dong ho ao TRUOC khi day du lieu, de moi stage nhin thay thoi gian
|
|
// dung luc ban tin nay den.
|
|
impl_->clock->SetNow(stamp);
|
|
|
|
if (!impl_->cfg.deterministic && impl_->cfg.speed > 0.0) {
|
|
// Ngu cho toi khi thoi gian TUONG bat kip stamp cua chunk nay.
|
|
//
|
|
// ⚠️ Ban truoc viet `SleepUntil(Steady() + nanoseconds(0))` -- tuc la
|
|
// ngu KHONG giay nao. `speed` va `deterministic=false` khong co tac
|
|
// dung gi, va ban ghi luon chay het toc. Triong chung danh lua: ca
|
|
// duong ong van dung, chi la mot ban ghi 8 giay chay xong trong 0.4
|
|
// giay, va tren web UI thi no giong het nhu "replay bi treo o khung
|
|
// cuoi".
|
|
//
|
|
// Moc la chunk DAU TIEN duoc phat (sau cua so start_sec), khong phai
|
|
// chunk dau file: neu khong thi voi --start 60 no se ngu 60 giay truoc
|
|
// khi phat gi.
|
|
if (!have_play_origin) {
|
|
play_origin_wall = std::chrono::steady_clock::now();
|
|
play_origin_stamp = stamp;
|
|
have_play_origin = true;
|
|
}
|
|
const double elapsed = SecondsBetween(stamp, play_origin_stamp) /
|
|
impl_->cfg.speed;
|
|
const auto target =
|
|
play_origin_wall +
|
|
std::chrono::duration_cast<std::chrono::steady_clock::duration>(
|
|
std::chrono::duration<double>(elapsed));
|
|
// Cho phep tut lai: neu may qua cham thi phat tiep ngay, khong don no
|
|
// thanh mot cu ngu bu.
|
|
if (target > std::chrono::steady_clock::now()) {
|
|
std::this_thread::sleep_until(target);
|
|
}
|
|
}
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
|
impl_->stats.chunks++;
|
|
}
|
|
|
|
switch (h.stream) {
|
|
case VsrStream::kScanRaw: {
|
|
auto scan = std::make_shared<LaserScan>();
|
|
if (!DecodeScanPayload(payload, scan.get())) break;
|
|
// Ban ghi luu du lieu THO (truoc sanitizer) chinh la de cho nay: doi
|
|
// nguong sanitizer roi chay lai tren cung mot file.
|
|
if (impl_->sanitizer) impl_->sanitizer->Apply(scan.get());
|
|
impl_->lidar.Push(std::move(scan));
|
|
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
|
impl_->stats.scans++;
|
|
break;
|
|
}
|
|
case VsrStream::kImu: {
|
|
auto imu = std::make_shared<Imu>();
|
|
if (!DecodeImuPayload(payload, imu.get())) break;
|
|
impl_->mcu.PushImu(std::move(imu));
|
|
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
|
impl_->stats.imu++;
|
|
break;
|
|
}
|
|
case VsrStream::kBaro: {
|
|
FluidPressure p;
|
|
Temperature t;
|
|
if (!DecodeBaroPayload(payload, &p, &t)) break;
|
|
impl_->mcu.PushBaro(p, t);
|
|
break;
|
|
}
|
|
case VsrStream::kEncoder: {
|
|
EncoderReading e;
|
|
if (!DecodeEncoderPayload(payload, &e.left_rad, &e.right_rad)) break;
|
|
e.stamp = stamp;
|
|
e.valid = true;
|
|
impl_->base.Push(e);
|
|
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
|
impl_->stats.encoder++;
|
|
break;
|
|
}
|
|
case VsrStream::kUltrasonic: {
|
|
UltrasonicReading u;
|
|
if (!DecodeUltrasonicPayload(payload, u.range, &u.count, 8)) break;
|
|
u.stamp = stamp;
|
|
impl_->mcu.PushUltrasonic(u);
|
|
break;
|
|
}
|
|
case VsrStream::kBumper: {
|
|
BumperReading b;
|
|
if (!DecodeBumperPayload(payload, &b.mask)) break;
|
|
b.stamp = stamp;
|
|
impl_->mcu.PushBumper(b);
|
|
break;
|
|
}
|
|
case VsrStream::kDepth: {
|
|
// Chunk depth moi = khung truoc da day du -> phat khung truoc.
|
|
impl_->FlushCameraFrame();
|
|
auto img = std::make_shared<Image>();
|
|
if (!DecodeImagePayload(payload, img.get(), &impl_->depth_storage)) break;
|
|
impl_->pending_frame.header = img->header;
|
|
impl_->pending_frame.depth = img;
|
|
impl_->have_pending = true;
|
|
break;
|
|
}
|
|
case VsrStream::kInfra1: {
|
|
auto img = std::make_shared<Image>();
|
|
if (!DecodeImagePayload(payload, img.get(), &impl_->infra1_storage)) break;
|
|
impl_->pending_frame.infra1 = img;
|
|
break;
|
|
}
|
|
case VsrStream::kInfra2: {
|
|
auto img = std::make_shared<Image>();
|
|
if (!DecodeImagePayload(payload, img.get(), &impl_->infra2_storage)) break;
|
|
impl_->pending_frame.infra2 = img;
|
|
break;
|
|
}
|
|
case VsrStream::kCameraInfo: {
|
|
if (DecodeCameraInfoPayload(payload, &impl_->last_info)) {
|
|
impl_->have_info = true;
|
|
}
|
|
break;
|
|
}
|
|
case VsrStream::kCmdVel:
|
|
// Lenh dieu khien DA GHI la dau vao cua lop safety, khong phai dau ra.
|
|
// Replay khong tu dong ap chung: viec do do wiring quyet dinh.
|
|
break;
|
|
case VsrStream::kEvent: {
|
|
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
|
impl_->stats.events++;
|
|
VSLAM_DEBUG("replay: su kien tai " << stamp.toString() << ": " << payload);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
impl_->FlushCameraFrame();
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
|
impl_->stats.truncated = impl_->reader.truncated();
|
|
if (have_first) impl_->stats.duration_sec = SecondsBetween(last_stamp, first_stamp);
|
|
}
|
|
|
|
const Stats s = stats();
|
|
VSLAM_INFO("replay: xong. " << s.chunks << " chunk trong " << s.duration_sec
|
|
<< " s -- " << s.scans << " scan, " << s.imu << " imu, "
|
|
<< s.encoder << " encoder, " << s.camera_frames << " khung camera"
|
|
<< (s.truncated ? " [FILE CUT GIUA CHUNG]" : ""));
|
|
(void)file_start;
|
|
}
|
|
|
|
ReplaySource::Stats ReplaySource::stats() const {
|
|
std::lock_guard<std::mutex> lk(impl_->stats_mu);
|
|
return impl_->stats;
|
|
}
|
|
|
|
} // namespace vslam
|