Files
vslam_cpp/test/test_replay_source.cc

413 lines
11 KiB
C++

#include "vslam/replay_source.h"
#include <fstream>
#include <gtest/gtest.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <string>
#include <unistd.h>
#include <vector>
#include "vslam/record_io.h"
using namespace vslam;
namespace {
std::string TempPath(const char* name) {
return std::string("/tmp/vslam_replay_") + name + "_" +
std::to_string(::getpid()) + ".vsr";
}
// Sinh mot ban ghi giong nhip that: scan 25 Hz, imu 200 Hz, encoder 50 Hz.
void MakeRecording(const std::string& path, int seconds) {
RecordWriterConfig c;
c.path = path;
c.config_json = R"({"lidar":{"range_max":40.0},"note":"ban ghi test"})";
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
const double t0 = 1737000000.0;
const int imu_n = seconds * 200;
for (int i = 0; i < imu_n; ++i) {
const double t = t0 + static_cast<double>(i) / 200.0;
const UnixTime stamp = UnixTime::fromSec(t);
Imu imu;
imu.header.stamp = stamp;
imu.header.frame_id = "imu_link";
imu.angular_velocity.z = 0.1 * std::sin(static_cast<double>(i) * 0.01);
imu.linear_acceleration.z = 9.81;
std::string p;
EncodeImuPayload(imu, &p);
w.Write(VsrStream::kImu, stamp, p);
if (i % 8 == 0) { // 25 Hz
LaserScan s;
s.header.stamp = stamp;
s.header.frame_id = "laser_link";
s.angle_min = -2.356194f;
s.angle_increment = static_cast<float>(2.0 * 2.356194 / 1080.0);
s.scan_time = 0.04f;
// Gia tri THO tu driver: header noi doi, va co tia 0.0.
s.range_min = 0.0f;
s.range_max = 100.0f;
s.ranges.assign(1081, 2.5f);
s.ranges[0] = 0.0f;
std::string sp;
EncodeScanPayload(s, &sp);
w.Write(VsrStream::kScanRaw, stamp, sp);
}
if (i % 4 == 0) { // 50 Hz
std::string ep;
EncodeEncoderPayload(static_cast<double>(i) * 0.001,
static_cast<double>(i) * 0.0011, &ep);
w.Write(VsrStream::kEncoder, stamp, ep);
}
}
w.Close();
}
ScanSanitizerConfig SanCfg() {
ScanSanitizerConfig c;
c.range_min = 0.05;
c.range_max = 40.0;
return c;
}
// Ghi lai toan bo dau ra thanh mot chuoi, de so hai lan chay voi nhau.
struct Recorder {
std::ostringstream out;
int scans = 0, imu = 0, enc = 0;
void Attach(ReplaySource* rs) {
rs->lidar()->SetCallback([this](LaserScanPtr s) {
scans++;
out << "S " << s->header.stamp.toString() << " " << s->range_min << " "
<< s->ranges.size() << " " << (std::isnan(s->ranges[0]) ? "nan" : "num")
<< "\n";
});
rs->mcu()->SetImuCallback([this](ImuPtr m) {
imu++;
out << "I " << m->header.stamp.toString() << " " << m->angular_velocity.z << "\n";
});
rs->base()->SetEncoderCallback([this](const EncoderReading& e) {
enc++;
out << "E " << e.stamp.toString() << " " << e.left_rad << " " << e.right_rad << "\n";
});
rs->lidar()->Open();
rs->mcu()->Open();
rs->base()->Open();
}
};
} // namespace
TEST(ReplaySource, PhatLaiDuMoiStream) {
const std::string path = TempPath("basic");
MakeRecording(path, 2);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
Recorder rec;
rec.Attach(&rs);
rs.Run();
EXPECT_EQ(rec.imu, 400); // 2 s x 200 Hz
EXPECT_EQ(rec.scans, 50); // 2 s x 25 Hz
EXPECT_EQ(rec.enc, 100); // 2 s x 50 Hz
const auto s = rs.stats();
EXPECT_FALSE(s.truncated);
EXPECT_NEAR(s.duration_sec, 1.995, 0.01);
std::remove(path.c_str());
}
TEST(ReplaySource, ChayLaiHaiLanChoKetQuaGiongHET) {
// DAY LA LOI HUA KIEN TRUC QUAN TRONG NHAT CUA P2.
//
// Khong con Gazebo va khong con rosbag thi tang 2 cua chien luoc kiem chung
// (regress.sh so JSON voi expected/) la thu duy nhat bat duoc hoi quy. No
// chi co gia tri neu replay TAT DINH.
//
// Tinh tat dinh do phu thuoc vao quy tac o clock.h: khong stage nao goi
// UnixTime::now() truc tiep. Vi pham mot cho thoi la test nay do.
const std::string path = TempPath("determ");
MakeRecording(path, 2);
std::string first, second;
for (int run = 0; run < 2; ++run) {
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
Recorder rec;
rec.Attach(&rs);
rs.Run();
(run == 0 ? first : second) = rec.out.str();
}
EXPECT_FALSE(first.empty());
EXPECT_EQ(first, second) << "hai lan chay cho ket qua khac nhau";
EXPECT_EQ(first.size(), second.size());
std::remove(path.c_str());
}
TEST(ReplaySource, ApSanitizerLenDuLieuTho) {
// Ban ghi luu SCAN_RAW -- truoc sanitizer. Day chinh la de doi nguong roi
// chay lai tren cung mot file.
const std::string path = TempPath("san");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.apply_sanitizer = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
float seen_min = -1.0f, seen_max = -1.0f;
bool zero_became_nan = false;
rs.lidar()->SetCallback([&](LaserScanPtr s) {
seen_min = s->range_min;
seen_max = s->range_max;
if (std::isnan(s->ranges[0])) zero_became_nan = true;
});
rs.lidar()->Open();
rs.Run();
// Header noi doi cua driver (0.0 / 100.0) phai da bi ep ve gia tri that.
EXPECT_FLOAT_EQ(seen_min, 0.05f);
EXPECT_FLOAT_EQ(seen_max, 40.0f);
EXPECT_TRUE(zero_became_nan) << "tia 0.0 phai thanh NaN";
std::remove(path.c_str());
}
TEST(ReplaySource, TatSanitizerThiThayDuLieuTho) {
const std::string path = TempPath("raw");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.apply_sanitizer = false;
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
float seen_max = -1.0f;
rs.lidar()->SetCallback([&](LaserScanPtr s) { seen_max = s->range_max; });
rs.lidar()->Open();
rs.Run();
EXPECT_FLOAT_EQ(seen_max, 100.0f) << "phai thay gia tri THO cua driver";
std::remove(path.c_str());
}
TEST(ReplaySource, CuaSoStartVaDuration) {
const std::string path = TempPath("window");
MakeRecording(path, 4);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.start_sec = 1.0;
cfg.duration_sec = 1.0;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
Recorder rec;
rec.Attach(&rs);
rs.Run();
// ~1 giay du lieu thay vi 4.
EXPECT_GE(rec.imu, 180);
EXPECT_LE(rec.imu, 220);
EXPECT_GT(rs.stats().skipped, 0u);
std::remove(path.c_str());
}
TEST(ReplaySource, DongHoAoTienTheoStampCuaBanGhi) {
const std::string path = TempPath("clock");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
// Moi stage phai doc dong ho NAY, khong phai dong ho he thong. Kiem rang no
// that su chay theo thoi gian trong file chu khong phai thoi gian that.
ClockPtr clk = rs.clock();
ASSERT_TRUE(clk != nullptr);
EXPECT_TRUE(clk->is_virtual());
std::vector<double> clock_at_scan;
rs.lidar()->SetCallback([&](LaserScanPtr s) {
clock_at_scan.push_back(clk->Now().toSec());
// Dong ho ao phai khop stamp cua ban tin dang xu ly.
EXPECT_NEAR(clk->Now().toSec(), s->header.stamp.toSec(), 1e-6);
});
rs.lidar()->Open();
rs.Run();
ASSERT_GE(clock_at_scan.size(), 2u);
EXPECT_NEAR(clock_at_scan.front(), 1737000000.0, 0.01);
EXPECT_GT(clock_at_scan.back(), clock_at_scan.front());
}
TEST(ReplaySource, ConfigLucGhiDocLaiDuoc) {
// Ban ghi phai TU MO TA: doc lai sau sau thang van biet no chay voi nguong
// nao, khong phai doan.
const std::string path = TempPath("cfg");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
EXPECT_NE(rs.recorded_config_json().find("range_max"), std::string::npos);
EXPECT_NE(rs.recorded_config_json().find("ban ghi test"), std::string::npos);
std::remove(path.c_str());
}
TEST(ReplaySource, LenhMotorKhiReplayDiVaoHuKhong) {
// Khong co banh xe nao quay, nhung lenh phai den duoc BaseInterface: bai
// regression can kiem rang he thong DA ra lenh dung.
const std::string path = TempPath("cmd");
MakeRecording(path, 1);
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
rs.base()->Open();
rs.base()->SetVelocity(0.25, -0.1);
rs.Run();
// Khong nem, khong sap. Gia tri duoc giu lai de kiem.
SUCCEED();
std::remove(path.c_str());
}
TEST(ReplaySource, AnhCuKhongBiKhungSauGhiDe) {
// Nhu bo mo phong va driver RealSense: anh da phat ra phai giu nguyen noi
// dung du nguon da giai ma them nhieu khung -- SlamLoop giu khung moi nhat
// qua Rtabmap::process tren luong khac. Truoc day ba kho giai ma dung chung.
const std::string path = TempPath("img_hold");
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
for (int k = 0; k < 6; ++k) {
const UnixTime stamp = UnixTime::fromSec(1737000000.0 + 0.1 * k);
std::vector<uint8_t> depth(4 * 2 * 2), ir(4 * 2);
for (size_t i = 0; i < depth.size(); ++i) depth[i] = static_cast<uint8_t>(10 * k + i);
for (size_t i = 0; i < ir.size(); ++i) ir[i] = static_cast<uint8_t>(100 + 10 * k + i);
Image d;
d.header.stamp = stamp;
d.width = 4; d.height = 2; d.step = 8;
d.format = PixelFormat::kMono16;
d.depth_scale = 0.001f;
d.data = depth.data();
Image r = d;
r.step = 4;
r.format = PixelFormat::kMono8;
r.data = ir.data();
std::string pd, pr;
EncodeImagePayload(d, &pd);
EncodeImagePayload(r, &pr);
w.Write(VsrStream::kDepth, stamp, pd);
w.Write(VsrStream::kInfra1, stamp, pr);
}
w.Close();
}
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
std::vector<CameraFrame> frames;
std::vector<std::vector<uint8_t>> depth_copy, ir_copy;
rs.camera()->SetCallback([&](const CameraFrame& f) {
frames.push_back(f);
depth_copy.emplace_back(f.depth->data, f.depth->data + 16);
ir_copy.emplace_back(f.infra1->data, f.infra1->data + 8);
});
rs.camera()->Open();
rs.Run();
ASSERT_EQ(frames.size(), 6u);
for (size_t k = 0; k < frames.size(); ++k) {
EXPECT_EQ(std::memcmp(frames[k].depth->data, depth_copy[k].data(), 16), 0)
<< "depth khung " << k << " bi ghi de";
EXPECT_EQ(std::memcmp(frames[k].infra1->data, ir_copy[k].data(), 8), 0)
<< "IR khung " << k << " bi ghi de";
EXPECT_EQ(frames[k].depth->data[0], static_cast<uint8_t>(10 * k));
}
std::remove(path.c_str());
}
TEST(ReplaySource, FileKhongTonTaiThiBaoLoi) {
ReplayConfig cfg;
cfg.path = "/khong/ton/tai/abc.vsr";
ReplaySource rs(cfg);
EXPECT_FALSE(rs.Open().ok());
}
TEST(ReplaySource, FileCutGiuaChungBiBao) {
const std::string path = TempPath("cut");
MakeRecording(path, 1);
{
std::ifstream in(path, std::ios::binary | std::ios::ate);
const long size = static_cast<long>(in.tellg());
in.close();
ASSERT_EQ(::truncate(path.c_str(), size - 50), 0);
}
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
cfg.sanitizer = SanCfg();
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
rs.Run();
EXPECT_TRUE(rs.stats().truncated) << "file cut phai duoc bao, khong im lang";
std::remove(path.c_str());
}