Files
vslam_cpp/libs/vslam_drivers/src/realsense_driver.cc

419 lines
15 KiB
C++

// Driver RealSense D410.
//
// ================== D410 KHAC GI CAC DONG KIA ==================
// D410 chi co Stereo Module: KHONG RGB, KHONG IMU tich hop. Nen:
// - Kenh "rgb" ma SLAM can duoc lap bang anh IR TRAI (infra1, mono8).
// - Nghieng phai lay tu IMU cua MCU, khong phai tu camera.
//
// ================== BA BAY DA BIET TRUOC ==================
// 1. `decimate` cap nhat `binning_x/y` chu KHONG chia lai K. Do la dung quy
// uoc sensor_msgs/CameraInfo, va moi consumer phai tu bu bang
// `fx_binned()`. Chia lai K o day se lam MOI consumer bu HAI LAN.
//
// 2. `RS2_OPTION_GLOBAL_TIME_ENABLED` chua xac minh tren FW 5.17.0.10. Khong
// co thi `get_timestamp()` tra ve dong ho CUA THIET BI, khong phai dong ho
// host -- va moi phep dong bo voi LiDAR/IMU sai hang chuc nam. Driver kiem
// tra domain THAT SU nhan duoc chu khong tin option da set.
//
// 3. Emitter phai co dinh o 1 (Laser), KHONG BAO GIO 2 (Laser Auto): che do
// auto lam depth nhap nhay giua cac khung, va `cliff_detect` doc su nhap
// nhay do thanh lo hong tren san.
//
// ================== VIET DUOC MA CHUA CO CAMERA ==================
// librealsense2 la API cong khai; cai chua lam duoc la KIEM CHUNG tren thiet
// bi that. Nhung thu chi biet duoc khi cam camera vao duoc danh dau ⚠️ CHUA
// XAC MINH ngay tai cho.
#include <librealsense2/rs.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstring>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "vslam/buffer_pool.h"
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Giu rs2::frameset song chung voi Image tro vao buffer cua no.
//
// `Image` KHONG so huu bo nho (xem vslam_common.h): `data` tro thang vao
// buffer cua SDK. Khong giu frameset thi SDK tai su dung buffer do ngay khung
// sau, va consumer doc phai anh MOI trong khi tuong minh doc anh CU -- mot
// loi khong bao gio crash, chi lam moi phep do lech mot khung.
struct FrameKeepAlive {
rs2::frameset fs;
};
class RealSenseDriver : public CameraInterface {
public:
RealSenseDriver(CameraConfig cfg, ClockPtr clock)
: cfg_(std::move(cfg)), clock_(std::move(clock)) {}
~RealSenseDriver() override { Close(); }
void SetCallback(FrameCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override {
if (running_.load()) {
return StatusResponse::Error(StatusCode::kFailedPrecondition, "da mo roi");
}
if (cfg_.decimate == 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"camera.decimate = 0");
}
try {
rs2::config rc;
if (!cfg_.serial.empty()) rc.enable_device(cfg_.serial);
rc.enable_stream(RS2_STREAM_DEPTH, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Z16,
static_cast<int>(cfg_.fps));
if (cfg_.enable_infra1) {
rc.enable_stream(RS2_STREAM_INFRARED, 1, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Y8,
static_cast<int>(cfg_.fps));
}
if (cfg_.enable_infra2) {
rc.enable_stream(RS2_STREAM_INFRARED, 2, static_cast<int>(cfg_.depth_width),
static_cast<int>(cfg_.depth_height), RS2_FORMAT_Y8,
static_cast<int>(cfg_.fps));
}
pipe_.reset(new rs2::pipeline);
profile_.reset(new rs2::pipeline_profile(pipe_->start(rc)));
const StatusResponse st = Configure();
if (!st.ok()) {
pipe_->stop();
pipe_.reset();
profile_.reset();
return st;
}
} catch (const rs2::error& e) {
pipe_.reset();
profile_.reset();
return StatusResponse::Error(
StatusCode::kUnavailable,
std::string("realsense: ") + e.get_failed_function() + ": " + e.what());
} catch (const std::exception& e) {
pipe_.reset();
profile_.reset();
return StatusResponse::Error(StatusCode::kUnavailable,
std::string("realsense: ") + e.what());
}
running_.store(true);
thread_ = std::thread([this] { Loop(); });
return StatusResponse::Ok();
}
void Close() override {
if (!running_.exchange(false)) return;
if (thread_.joinable()) thread_.join();
try {
if (pipe_) pipe_->stop();
} catch (const std::exception&) {
// Dong thiet bi da rut day thi nem; khong co gi de lam va khong duoc
// phep nem tiep tu destructor.
}
pipe_.reset();
profile_.reset();
}
DriverStats Stats() const override {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
private:
StatusResponse Configure() {
rs2::device dev = profile_->get_device();
auto sensors = dev.query_sensors();
for (rs2::sensor& s : sensors) {
// --- Emitter: co dinh o Laser, KHONG BAO GIO Laser Auto ---
if (s.supports(RS2_OPTION_EMITTER_ENABLED)) {
s.set_option(RS2_OPTION_EMITTER_ENABLED,
static_cast<float>(cfg_.emitter_mode));
}
// --- Dong ho ---
// Dat option la MOT chuyen; thiet bi co thuc su doi domain khong lai la
// chuyen khac. Kiem o Loop() bang domain THAT nhan duoc.
if (cfg_.use_global_time && s.supports(RS2_OPTION_GLOBAL_TIME_ENABLED)) {
s.set_option(RS2_OPTION_GLOBAL_TIME_ENABLED, 1.0f);
} else if (cfg_.use_global_time) {
VSLAM_WARN("realsense: thiet bi khong ho tro GLOBAL_TIME_ENABLED -- "
"stamp se theo dong ho THIET BI, khong phai host.");
}
}
// --- depth_scale: met moi don vi ---
// KHONG hardcode 0.001. D4xx mac dinh la vay nhung tuy chinh duoc, va mot
// camera da bi chinh se cho ra do sau sai ti le ma khong co gi bao.
try {
depth_scale_ = profile_->get_device()
.first<rs2::depth_sensor>()
.get_depth_scale();
} catch (const std::exception&) {
depth_scale_ = 0.001f;
VSLAM_WARN("realsense: khong doc duoc depth_scale, dung 0.001 m/don vi");
}
if (!(depth_scale_ > 0.0f)) {
return StatusResponse::Error(StatusCode::kInternal,
"realsense: depth_scale khong duong");
}
// --- Noi suy: doc tu profile, KHONG doan ---
const auto vsp = profile_->get_stream(RS2_STREAM_DEPTH)
.as<rs2::video_stream_profile>();
const rs2_intrinsics in = vsp.get_intrinsics();
info_ = CameraInfo{};
// width/height/K la cua do phan giai LUC HIEU CHUAN, con binning noi anh
// that nho hon bao nhieu lan. Do la dung quy uoc sensor_msgs/CameraInfo.
info_.width = static_cast<uint32_t>(in.width);
info_.height = static_cast<uint32_t>(in.height);
info_.k[0] = in.fx; info_.k[2] = in.ppx;
info_.k[4] = in.fy; info_.k[5] = in.ppy;
info_.k[8] = 1.0;
for (int i = 0; i < 5; ++i) info_.d[i] = in.coeffs[i];
info_.binning_x = cfg_.decimate;
info_.binning_y = cfg_.decimate;
info_.header.frame_id = cfg_.depth_frame_id;
VSLAM_INFO("realsense: " << in.width << "x" << in.height << " @ " << cfg_.fps
<< " Hz, fx=" << in.fx << " cx=" << in.ppx
<< ", depth_scale=" << depth_scale_
<< ", decimate=" << cfg_.decimate);
return StatusResponse::Ok();
}
// Giam mau NEAREST, khong lay trung binh.
//
// Trung binh tren anh depth la SAI: trung binh cua mot diem o 1 m va mot
// diem o 5 m cho ra 3 m, tuc mot be mat KHONG TON TAI lo lung giua. Tren
// mep vat the dieu do sinh ra ca mot vien gia. Lay diem goc la cach
// image_proc/crop_decimate lam, va la ly do no dung `decimate` chu khong
// phai `resize`.
void Decimate16(const uint16_t* src, int sw, int sh, int step,
std::vector<uint8_t>* dst, uint32_t* ow, uint32_t* oh) {
const int w = sw / step, h = sh / step;
dst->resize(static_cast<size_t>(w) * h * 2);
auto* out = reinterpret_cast<uint16_t*>(dst->data());
for (int y = 0; y < h; ++y) {
const uint16_t* row = src + static_cast<size_t>(y) * step * sw;
for (int x = 0; x < w; ++x) out[static_cast<size_t>(y) * w + x] = row[x * step];
}
*ow = static_cast<uint32_t>(w);
*oh = static_cast<uint32_t>(h);
}
void Decimate8(const uint8_t* src, int sw, int sh, int step,
std::vector<uint8_t>* dst, uint32_t* ow, uint32_t* oh) {
const int w = sw / step, h = sh / step;
dst->resize(static_cast<size_t>(w) * h);
for (int y = 0; y < h; ++y) {
const uint8_t* row = src + static_cast<size_t>(y) * step * sw;
for (int x = 0; x < w; ++x) (*dst)[static_cast<size_t>(y) * w + x] = row[x * step];
}
*ow = static_cast<uint32_t>(w);
*oh = static_cast<uint32_t>(h);
}
void Loop() {
bool warned_domain = false;
bool warned_drop = false;
uint64_t last_frame_number = 0;
while (running_.load()) {
rs2::frameset fs;
try {
// Timeout co gioi han: `wait_for_frames()` mac dinh 5 s va se treo ca
// luong neu camera bi rut day. 200 ms cho phep vong kiem `running_`.
if (!pipe_->try_wait_for_frames(&fs, 200)) {
std::lock_guard<std::mutex> lk(mu_);
stats_.errors++; // het gio = mat khung, dem chung o day
continue;
}
} catch (const std::exception& e) {
std::lock_guard<std::mutex> lk(mu_);
stats_.errors++;
VSLAM_ERROR_THROTTLE(5.0, "realsense: " << e.what());
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
rs2::depth_frame depth = fs.get_depth_frame();
if (!depth) continue;
// --- Dau thoi gian ---
//
// Kiem DOMAIN THAT SU nhan duoc, khong tin option da set. Neu khong
// phai HARDWARE_CLOCK/SYSTEM_TIME thi stamp la dong ho CUA THIET BI --
// mot so hoan toan khong lien quan toi dong ho host, va moi phep dong
// bo voi LiDAR/IMU sai hang chuc nam.
const rs2_timestamp_domain dom = depth.get_frame_timestamp_domain();
UnixTime stamp;
if (dom == RS2_TIMESTAMP_DOMAIN_SYSTEM_TIME ||
dom == RS2_TIMESTAMP_DOMAIN_GLOBAL_TIME) {
// get_timestamp() tra milli giay.
stamp = UnixTime::fromSec(depth.get_timestamp() * 1e-3);
} else {
if (!warned_domain) {
warned_domain = true;
VSLAM_WARN("realsense: timestamp domain = "
<< rs2_timestamp_domain_to_string(dom)
<< " (khong phai dong ho host). Dung thoi diem NHAN"
" thay the -- jitter cao hon, nhung it nhat cung mot"
" goc thoi gian voi LiDAR va IMU.");
}
stamp = clock_->Now();
}
// --- Dem khung roi ---
// SDK khong bao khi ta xu ly cham hon camera; so hieu khung thi co.
const uint64_t fn = depth.get_frame_number();
if (last_frame_number != 0 && fn > last_frame_number + 1) {
std::lock_guard<std::mutex> lk(mu_);
stats_.packets_lost += fn - last_frame_number - 1;
if (!warned_drop) {
warned_drop = true;
VSLAM_WARN("realsense: bo lo khung (so hieu nhay " << last_frame_number
<< " -> " << fn << "). Duong camera dang cham hon "
<< cfg_.fps << " Hz.");
}
}
last_frame_number = fn;
if (!cb_) continue;
auto keep = std::make_shared<FrameKeepAlive>();
keep->fs = fs;
CameraFrame out;
out.header.stamp = stamp;
out.header.frame_id = cfg_.depth_frame_id;
auto depth_img = std::make_shared<Image>();
depth_img->header = out.header;
depth_img->format = PixelFormat::kMono16;
depth_img->depth_scale = depth_scale_;
const int sw = depth.get_width(), sh = depth.get_height();
const auto* praw = static_cast<const uint16_t*>(depth.get_data());
if (cfg_.decimate <= 1) {
depth_img->width = static_cast<uint32_t>(sw);
depth_img->height = static_cast<uint32_t>(sh);
depth_img->step = static_cast<uint32_t>(sw) * 2;
depth_img->data = static_cast<const uint8_t*>(depth.get_data());
depth_img->keep_alive = keep; // KHONG copy: giu frameset song
} else {
// MOI khung mot bo dem RIENG tu pool, anh giu no qua keep_alive.
//
// ⚠️ Truoc day la MOT bo dem dung chung, "hop le toi lan goi Loop()
// sau" -- du cho perception chay INLINE trong callback, nhung SlamLoop
// giu khung depth/IR moi nhat qua Rtabmap::process (100-600 ms) tren
// luong KHAC, va `BuildSensorData` boc cv::Mat quanh bo dem ma khong
// copy. Khung sau (33 ms) ghi de giua chung: anh luu vao DB co the la
// nua khung nay nua khung kia.
auto buf = buf_pool_->Acquire();
Decimate16(praw, sw, sh, static_cast<int>(cfg_.decimate), buf.get(),
&depth_img->width, &depth_img->height);
depth_img->step = depth_img->width * 2;
depth_img->data = buf->data();
depth_img->keep_alive = buf;
}
out.depth = depth_img;
if (cfg_.enable_infra1) {
rs2::video_frame ir = fs.get_infrared_frame(1);
if (ir) out.infra1 = WrapIr(ir, out.header, keep);
}
if (cfg_.enable_infra2) {
rs2::video_frame ir = fs.get_infrared_frame(2);
if (ir) out.infra2 = WrapIr(ir, out.header, keep);
}
out.depth_info = info_;
out.depth_info.header = out.header;
{
std::lock_guard<std::mutex> lk(mu_);
stats_.frames++;
stats_.connected = true;
}
cb_(out);
}
}
ImagePtr WrapIr(const rs2::video_frame& ir, const Header& hdr,
const std::shared_ptr<FrameKeepAlive>& keep) {
auto img = std::make_shared<Image>();
img->header = hdr;
img->format = PixelFormat::kMono8;
const int w = ir.get_width(), h = ir.get_height();
if (cfg_.decimate <= 1) {
img->width = static_cast<uint32_t>(w);
img->height = static_cast<uint32_t>(h);
img->step = static_cast<uint32_t>(w);
img->data = static_cast<const uint8_t*>(ir.get_data());
img->keep_alive = keep;
} else {
// Bo dem rieng moi khung, nhu depth o tren.
auto buf = buf_pool_->Acquire();
Decimate8(static_cast<const uint8_t*>(ir.get_data()), w, h,
static_cast<int>(cfg_.decimate), buf.get(), &img->width, &img->height);
img->step = img->width;
img->data = buf->data();
img->keep_alive = buf;
}
return img;
}
CameraConfig cfg_;
ClockPtr clock_;
FrameCallback cb_;
std::unique_ptr<rs2::pipeline> pipe_;
std::unique_ptr<rs2::pipeline_profile> profile_;
float depth_scale_ = 0.001f;
CameraInfo info_;
// Bo dem anh da decimate (depth + IR). Moi khung lay bo dem rieng va tra
// ve pool khi KHONG CON AI giu anh -- 0 malloc o trang thai on dinh.
std::shared_ptr<BufferPool<std::vector<uint8_t>>> buf_pool_ =
BufferPool<std::vector<uint8_t>>::Create(12);
std::atomic<bool> running_{false};
std::thread thread_;
mutable std::mutex mu_;
DriverStats stats_;
};
} // namespace
std::unique_ptr<CameraInterface> CreateRealSenseD410(const CameraConfig& cfg,
ClockPtr clock) {
return std::unique_ptr<CameraInterface>(
new RealSenseDriver(cfg, std::move(clock)));
}
} // namespace vslam