From 906f3dece7bca669edecbbcbbf48d7343c492eb3 Mon Sep 17 00:00:00 2001 From: MichalPelka Date: Sun, 22 Nov 2026 02:47:36 +0100 Subject: [PATCH 01/21] step 1: load recordings through a RecordingSource interface load_data() hard-coded the lidarNNNN.laz / imuNNNN.csv pairing, and the lazy raw cloud loader re-read LAZ files by path. Both now go through RecordingSource, so other recording formats (ROS1 bag, MCAP, Ouster pcap) can be added as further sources without touching the pipeline. The sources live in recording_sources/, shared by step 1 and the raw data viewer. - recording_sources/recording_source.h: the interface (working directory, time-ordered point chunks, change stamp, IMU stream), plus PointFilter and ChunkStamp. Imu and InputFileSpan move here from lidar_odometry.h. - recording_sources/laz_csv_source: the existing folder loader, moved out of load_data unchanged (file sorting and pairing, calibration and serial-number checks, MURATA_IMU fallback). - load_data(): the file-list overloads keep their signatures and wrap LazCsvSource; a new overload takes any RecordingSource. - RawCloudLoader (moved to recording_sources/) holds the source instead of file paths; lazy_ensure / lazy_release become RawCloudLoader::ensure / release. No behaviour change: single-threaded step 1 runs (taskset -c 0, useMultithread = false) on the Underground Parking dataset give byte-identical result files to main, lazy and eager. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158FTTEePKhmGqE9Z1HgwUd --- apps/lidar_odometry_step_1/CMakeLists.txt | 8 +- apps/lidar_odometry_step_1/lidar_odometry.cpp | 612 +++++------------- apps/lidar_odometry_step_1/lidar_odometry.h | 20 +- .../raw_cloud_loader.cpp | 54 -- apps/mandeye_raw_data_viewer/CMakeLists.txt | 5 +- pybind/CMakeLists.txt | 4 +- recording_sources/laz_csv_source.cpp | 358 ++++++++++ recording_sources/laz_csv_source.h | 35 + recording_sources/raw_cloud_loader.cpp | 51 ++ .../raw_cloud_loader.h | 26 +- recording_sources/recording_source.h | 58 ++ 11 files changed, 703 insertions(+), 528 deletions(-) delete mode 100644 apps/lidar_odometry_step_1/raw_cloud_loader.cpp create mode 100644 recording_sources/laz_csv_source.cpp create mode 100644 recording_sources/laz_csv_source.h create mode 100644 recording_sources/raw_cloud_loader.cpp rename {apps/lidar_odometry_step_1 => recording_sources}/raw_cloud_loader.h (57%) create mode 100644 recording_sources/recording_source.h diff --git a/apps/lidar_odometry_step_1/CMakeLists.txt b/apps/lidar_odometry_step_1/CMakeLists.txt index fc550b33..a95efe69 100644 --- a/apps/lidar_odometry_step_1/CMakeLists.txt +++ b/apps/lidar_odometry_step_1/CMakeLists.txt @@ -22,8 +22,10 @@ set(SOURCES lidar_odometry_utils_optimizers.cpp lidar_odometry.cpp lidar_odometry.h points_global_spill.h points_global_spill.cpp - raw_cloud_loader.h raw_cloud_loader.cpp output_folders.h output_folders.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.h ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/raw_cloud_loader.h ${REPOSITORY_DIRECTORY}/recording_sources/raw_cloud_loader.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/recording_source.h toml_io.h toml_io.cpp ) @@ -42,6 +44,8 @@ target_apply_hdmapping_profiler(lidar_odometry_step_1) target_include_directories( lidar_odometry_step_1 PRIVATE include + ${CMAKE_CURRENT_SOURCE_DIR} + ${REPOSITORY_DIRECTORY}/recording_sources ${REPOSITORY_DIRECTORY}/core/include ${REPOSITORY_DIRECTORY}/core_hd_mapping/include ${THIRDPARTY_DIRECTORY} @@ -97,6 +101,8 @@ target_apply_hdmapping_profiler(drag_folder_with_mandeye_data_and_drop_here-prec target_include_directories( drag_folder_with_mandeye_data_and_drop_here-precision_forestry PRIVATE include + ${CMAKE_CURRENT_SOURCE_DIR} + ${REPOSITORY_DIRECTORY}/recording_sources ${REPOSITORY_DIRECTORY}/core/include ${REPOSITORY_DIRECTORY}/core_hd_mapping/include ${THIRDPARTY_DIRECTORY} diff --git a/apps/lidar_odometry_step_1/lidar_odometry.cpp b/apps/lidar_odometry_step_1/lidar_odometry.cpp index e5384d3c..9c1ee0ac 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry.cpp @@ -1,5 +1,6 @@ #include "lidar_odometry.h" #include "hdmapping_profiler.hpp" +#include "laz_csv_source.h" #include "raw_cloud_loader.h" #include "tbb/tbb.h" #include @@ -11,8 +12,6 @@ #include #endif -#include "spdlog/spdlog.h" - #include namespace fs = std::filesystem; @@ -123,487 +122,206 @@ static void report_lidar_gaps( std::cerr << "WARNING: ... and " << lines.size() - kMaxLines << " more\n"; } -//! Time span and sample count of one IMU file's samples. -static InputFileSpan imu_file_span(const std::string& file, const Imu& samples) -{ - InputFileSpan span{ file }; - for (const auto& sample : samples) - { - const double t = std::get<0>(sample).first; - span.first = span.count == 0 ? t : std::min(span.first, t); - span.last = span.count == 0 ? t : std::max(span.last, t); - span.count++; - } - return span; -} - -bool load_data( - std::vector& input_file_names, +// The body of load_data shared by every RecordingSource; the caller has set up the run report and the timing scope. +static bool load_from_source( + const std::shared_ptr& source, LidarOdometryParams& params, std::vector>& pointsPerFile, Imu& imu_data, - bool debugMsg) -{ - InputFileSpans unused; - return load_data(input_file_names, params, pointsPerFile, imu_data, debugMsg, unused); -} - -bool load_data( - std::vector& input_file_names, - LidarOdometryParams& params, - std::vector>& pointsPerFile, - Imu& imu_data, - bool debugMsg, InputFileSpans& fileSpans) { - fileSpans = {}; - if (!params.run_report || params.run_report->live().status != "running") - params.run_report = std::make_shared( - input_file_names.empty() ? fs::path{} : fs::path(input_file_names.front()).parent_path(), params.points_global_spill_directory); - RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Loading); - HDMAP_ZONE_SCOPE("load_data"); - std::sort(input_file_names.begin(), input_file_names.end()); - std::vector csv_files, laz_files; - std::string sn_file; - std::string calibrationFile; - - std::cout << "Loading data..\n--------------\n"; - - // --- Separate files by type - for (const auto& fileName : input_file_names) - { - std::string ext = fs::path(fileName).extension().string(); - std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - - if (ext == ".csv") - csv_files.push_back(fileName); - else if (ext == ".json") - { - std::string stem = fs::path(fileName).filename().stem().string(); // get filename without extension - - // skip files not related to calibration - if (!stem.starts_with("status") && !stem.starts_with("cam0") && !stem.starts_with("cam1")) - if (calibrationFile.empty()) - calibrationFile = fileName; - else - std::cout << "Unexpected JSON file found (" << fileName << "). Ignored..\n"; - } - else if ((ext == ".laz") || (ext == ".las")) - laz_files.push_back(fileName); - else if (ext == ".mjc") - { - if (calibrationFile.empty()) - calibrationFile = fileName; - else - std::cout << "Unexpected calibration file found (" << fileName << "). Ignored.." << std::endl; - } - else if ((ext == ".sn") && sn_file.empty()) + const fs::path working_directory = source->workingDirectory(); + source->loadImu(imu_data, fileSpans.imu); + + // Sort once after merging + std::sort( + imu_data.begin(), + imu_data.end(), + [](const auto& a, const auto& b) { - sn_file = fileName; - std::cout << "Only using first SN file found\n"; - } - } + return std::get<0>(a).first < std::get<0>(b).first; + }); - auto get4index = [](const std::string& path) -> std::string + if (params.imu_offset_qw != 1.0 || params.imu_offset_qx != 0.0 || params.imu_offset_qy != 0.0 || params.imu_offset_qz != 0.0) { - auto s = fs::path(path).stem().string(); - return s.size() > 4 ? s.substr(s.size() - 4) : s; - }; - - for (size_t i = 0; i < laz_files.size(); i++) - { - std::string lfs = get4index(laz_files[i]); - - bool found = false; - for (size_t j = 0; j < csv_files.size(); j++) - { - std::string cfs = get4index(csv_files[j]); - if (lfs.compare(cfs) == 0) - { - found = true; - break; - } - } - - if (!found) + const Eigen::Quaterniond imu_offset(params.imu_offset_qw, params.imu_offset_qx, params.imu_offset_qy, params.imu_offset_qz); + if (imu_offset.norm() < 1e-9) { - std::cout << "\n!!! there is no CSV file for: " << laz_files[i] << " !!! \n\n"; + std::cerr << "imu_offset quaternion (w x y z) is zero, it must describe a rotation\n"; + return false; } + rotate_imu(imu_data, imu_offset); + std::cout << "IMU readings rotated by offset quaternion (w x y z): " << params.imu_offset_qw << " " << params.imu_offset_qx + << " " << params.imu_offset_qy << " " << params.imu_offset_qz << "\n"; } - for (size_t i = 0; i < csv_files.size(); i++) + if (params.imu_target_rate_hz > 0.0) { - std::string lfs = get4index(csv_files[i]); - - bool found = false; - for (size_t j = 0; j < laz_files.size(); j++) - { - std::string cfs = get4index(laz_files[j]); - if (lfs.compare(cfs) == 0) - { - found = true; - break; - } - } - - if (!found) - { - std::cout << "\n!!! there is no LAZ file for: " << csv_files[i] << " !!! \n\n"; - } + const size_t samples_before = imu_data.size(); + imu_data = average_imu_to_rate(imu_data, params.imu_target_rate_hz); + std::cout << "IMU averaged to " << params.imu_target_rate_hz << " Hz: " << samples_before << " -> " << imu_data.size() + << " samples\n"; } - if (input_file_names.size() > 2) - { - std::string working_directory = fs::path(input_file_names.front()).parent_path().string(); + // The IMU timestamps are already sorted; publishing their span needs no point-cloud reads or extra scan. + if (params.run_report && !imu_data.empty()) + params.run_report->setRecordingSpan(std::get<0>(imu_data.front()).first, std::get<0>(imu_data.back()).first); - if (laz_files.size() != csv_files.size()) - std::cout << "!!! file number issue. continuing can lead to incomplete data!!!\n" << std::endl; + const size_t minSize = source->chunkCount(); + std::cout << "Loading point clouds (" << minSize << " files)..\n"; + std::cout << "total - filter = kept\n-----------------------\n"; - // check if folder exists! - if (!fs::exists(working_directory)) - { - std::cerr << "Folder '" << working_directory << "' does not exist.\n"; - return false; - } + pointsPerFile.resize(minSize); + // the first file's points are dropped unless params.skip_first_file is off + const size_t firstUsedFile = params.skip_first_file ? 1 : 0; - // --- Calibration and IMU setup - const auto preloadedCalibration = MLvxCalib::GetCalibrationFromFile(calibrationFile); - const std::string imuSnToUse = MLvxCalib::GetImuSnToUse(calibrationFile); - const auto idToSn = MLvxCalib::GetIdToSnMapping(sn_file); + // --- Working directories - // gate invalid calibration - std::stringstream err; - if (idToSn.size() > 1) - { - bool valid = true; - for (const auto& [_, sn] : idToSn) - { - if (!preloadedCalibration.contains(sn)) - { - valid = false; - err << "Missing serial number from calibration file " << sn.c_str() << "\n"; - } - } - - if (!valid) - { - err << "Data containst Lidars with those serial numbers :" << std::endl; - for (const auto& [id, sn] : idToSn) - { - err << " - " << id << " : " << sn.c_str() << "\n"; - } - - if (calibrationFile.empty()) - { - err << "But no calibration was given found\n"; - } - else - { - err << "Calibration file found : " << calibrationFile.c_str() << ", but contains following Lidars : \n"; - for (const auto& [sn, _] : preloadedCalibration) - { - err << " - " << sn << "\n"; - } - } - spdlog::error(err.str()); - throw std::runtime_error(err.str()); - } - } - - if (!preloadedCalibration.empty()) - { - std::cout << "Loaded calibration for:\n"; - for (const auto& [sn, _] : preloadedCalibration) - std::cout << " -> " << sn << "\n"; - - bool hasError = false; - - for (const auto& [id, sn] : idToSn) - { - if (preloadedCalibration.find(sn) == preloadedCalibration.end()) - { - std::cerr << "WRONG CALIBRATION FILE! THE SERIAL NUMBER SHOULD BE " << sn << "!!!\n"; - hasError = true; - } - } - - if (!hasError && preloadedCalibration.find(imuSnToUse) == preloadedCalibration.end()) - { - std::cerr << "MISSING CALIBRATION FOR imuSnToUse: " << imuSnToUse << "!!!\n"; - std::cerr << "Available serial numbers in calibration file are:\n"; - for (const auto& [snKey, _] : preloadedCalibration) - std::cerr << " - " << snKey << "\n"; - - hasError = true; - } - - if (hasError) - { - std::cerr << "Press ENTER to exit...\n"; - std::cin.get(); - std::exit(EXIT_FAILURE); - } - } - else - { - std::cout << "There is no calibration file in folder!" << std::endl; - std::cout << "IGNORE THIS MESSAGE IF YOU ONLY HAVE 1 LiDAR" << std::endl; - - // example file for 2x LiDAR": - /* - { - "calibration" : { - "47MDL9T0020193" : { - "identity" : "true" - }, - "47MDL9S0020300" : - { - "order" : "ROW", - "inverted" : "TRUE", - "data" : [ - 0.999824, 0.00466397, -0.0181595, -0.00425984, - -0.0181478, -0.00254457, -0.999832, -0.151599, - -0.0047094, 0.999986, -0.00245948, -0.146408, - 0, 0, 0, 1 - ] - } - }, - "imuToUse" : "47MDL9T0020193" - }*/ - } + fs::path wdp = working_directory / "preview"; + params.working_directory_preview = wdp.string(); + const CacheLocation cache = current_cache_location(working_directory, params.session_cache_choice); + params.working_directory_cache = new_run_cache_folder(cache, working_directory).string(); + if (params.run_report && cache.kind != CacheKind::DataFolder) + params.run_report->addVolume(cache.base, "cache"); - const int imuNumberToUse = MLvxCalib::GetImuIdToUse(idToSn, imuSnToUse); - // --- Load IMU data (still sequential, could parallelize later) - std::cout << "loading IMU data from 'imu****.csv' using ID " << imuNumberToUse << " from reference '" << sn_file << "' ..\n"; + std::vector names(minSize); + for (size_t i = 0; i < minSize; ++i) + names[i] = source->chunkName(i); - std::size_t minSize = std::min(laz_files.size(), csv_files.size()); - // Each thread loads into its own local vector - std::vector imuChunks(minSize); + PointFilter filter; + filter.omit_timestamp_zero = true; + filter.xy_inner = params.filter_threshold_xy_inner; + filter.xy_outer = params.filter_threshold_xy_outer; + params.raw_cloud_loader.reset(); + if (params.lazy_load_raw_clouds) + { + params.raw_cloud_loader = std::make_shared(); + auto& L = *params.raw_cloud_loader; + // a reload (the GUI opening another folder) must not keep the previous session's clouds + std::vector>(minSize).swap(pointsPerFile); + L.source = source; + L.filter = filter; + L.stamp.assign(minSize, ChunkStamp{}); + L.t_first.assign(minSize, 0.0); + L.t_last.assign(minSize, 0.0); + L.n.assign(minSize, 0); + L.loaded.assign(minSize, 0); + L.done.assign(minSize, 0); + std::vector> gaps_in_file(minSize); tbb::parallel_for( - tbb::blocked_range(0, minSize), - [&](const tbb::blocked_range& range) + std::min(firstUsedFile, minSize), // a skipped file's cloud is never used + minSize, + [&](size_t i) { - for (size_t i = range.begin(); i < range.end(); ++i) + auto data = source->loadPoints(i, filter); + // after the read: a cloud drive may report other metadata once it has downloaded the file + L.stamp[i] = source->stamp(i); + L.n[i] = data.size(); + if (!data.empty()) { - imuChunks[i] = load_imu(csv_files[i].c_str(), imuNumberToUse); + L.t_first[i] = data.front().timestamp; + L.t_last[i] = data.back().timestamp; } + gaps_in_file[i] = find_lidar_gaps(data, kLidarGapWarningS); }); - + report_lidar_gaps(names, firstUsedFile, gaps_in_file, L.t_first, L.t_last); for (size_t i = 0; i < minSize; ++i) - fileSpans.imu.push_back(imu_file_span(csv_files[i], imuChunks[i])); - - // Merge all chunks sequentially at the end - for (auto& chunk : imuChunks) - imu_data.insert(imu_data.end(), std::make_move_iterator(chunk.begin()), std::make_move_iterator(chunk.end())); + fileSpans.laz.push_back({ names[i], L.t_first[i], L.t_last[i], L.n[i] }); + if (params.save_calibration_validation && minSize > 0) // as the eager load: the first file, then dropped + write_calibration_validation(wdp, source->loadPoints(0, filter), params); + size_t totalPoints = 0; + for (auto k : L.n) + totalPoints += k; + std::cout << "TOTAL: " << totalPoints << " (lazy: ranges recorded, clouds loaded on demand)\n..loading finished.\n\n"; + return true; + } - // Units with an external IMU (e.g. Murata) leave 'imu****.csv' header-only and log the IMU - // into a subfolder, in files not aligned with the LiDAR chunks - const fs::path murataImuDir = fs::path(working_directory) / "MURATA_IMU"; - if (imu_data.empty() && fs::is_directory(murataImuDir)) + // --- Parallel load of LAZ files + std::vector> gaps_in_file(minSize); + std::vector t_first(minSize, 0.0); + std::vector t_last(minSize, 0.0); + tbb::parallel_for( + size_t(0), + minSize, + [&](size_t i) { - std::vector murataFiles; - for (const auto& entry : fs::directory_iterator(murataImuDir)) - { - std::string ext = entry.path().extension().string(); - std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - if (entry.is_regular_file() && ext == ".csv" && entry.file_size() > 0) - murataFiles.push_back(entry.path().string()); - } - std::sort(murataFiles.begin(), murataFiles.end()); - std::cout << "no IMU data in 'imu****.csv', loading " << murataFiles.size() << " file(s) from '" << murataImuDir.string() - << "' ..\n"; - - std::vector murataChunks(murataFiles.size()); - tbb::parallel_for( - size_t(0), - murataFiles.size(), - [&](size_t i) - { - murataChunks[i] = load_imu(murataFiles[i], imuNumberToUse); - }); - fileSpans.imu.clear(); - for (size_t i = 0; i < murataFiles.size(); ++i) - fileSpans.imu.push_back(imu_file_span(murataFiles[i], murataChunks[i])); - for (auto& chunk : murataChunks) - imu_data.insert(imu_data.end(), std::make_move_iterator(chunk.begin()), std::make_move_iterator(chunk.end())); - } + auto data = source->loadPoints(i, filter); - // Sort once after merging - std::sort( - imu_data.begin(), - imu_data.end(), - [](const auto& a, const auto& b) - { - return std::get<0>(a).first < std::get<0>(b).first; - }); + // Optional calibration validation (first file only) + if ((i == 0) && params.save_calibration_validation) + write_calibration_validation(wdp, data, params); - if (params.imu_offset_qw != 1.0 || params.imu_offset_qx != 0.0 || params.imu_offset_qy != 0.0 || params.imu_offset_qz != 0.0) - { - const Eigen::Quaterniond imu_offset(params.imu_offset_qw, params.imu_offset_qx, params.imu_offset_qy, params.imu_offset_qz); - if (imu_offset.norm() < 1e-9) + if (!data.empty()) { - std::cerr << "imu_offset quaternion (w x y z) is zero, it must describe a rotation\n"; - return false; + t_first[i] = data.front().timestamp; + t_last[i] = data.back().timestamp; } - rotate_imu(imu_data, imu_offset); - std::cout << "IMU readings rotated by offset quaternion (w x y z): " << params.imu_offset_qw << " " << params.imu_offset_qx - << " " << params.imu_offset_qy << " " << params.imu_offset_qz << "\n"; - } - - if (params.imu_target_rate_hz > 0.0) - { - const size_t samples_before = imu_data.size(); - imu_data = average_imu_to_rate(imu_data, params.imu_target_rate_hz); - std::cout << "IMU averaged to " << params.imu_target_rate_hz << " Hz: " << samples_before << " -> " << imu_data.size() - << " samples\n"; - } + gaps_in_file[i] = find_lidar_gaps(data, kLidarGapWarningS); - // The IMU timestamps are already sorted; publishing their span needs no point-cloud reads or extra scan. - if (params.run_report && !imu_data.empty()) - params.run_report->setRecordingSpan(std::get<0>(imu_data.front()).first, std::get<0>(imu_data.back()).first); + // Store results + pointsPerFile[i] = std::move(data); + }); + report_lidar_gaps(names, firstUsedFile, gaps_in_file, t_first, t_last); + for (size_t i = 0; i < minSize; ++i) + fileSpans.laz.push_back({ names[i], t_first[i], t_last[i], pointsPerFile[i].size() }); - // --- Precompute calibration once (major optimization) - const auto combinedCalibration = MLvxCalib::CombineIntoCalibration(idToSn, preloadedCalibration); - - std::cout << "Loading point clouds (" << minSize << " files)..\n"; - std::cout << "total - filter = kept\n-----------------------\n"; - - if (debugMsg) // if true this will break parallelism - { - for (const auto& [id, calib] : combinedCalibration) - std::cout << " id : " << id << "\n" << calib.matrix() << "\n"; - } - - pointsPerFile.resize(minSize); - // the first file's points are dropped unless params.skip_first_file is off - const size_t firstUsedFile = params.skip_first_file ? 1 : 0; - - // --- Working directories - - fs::path wdp = fs::path(working_directory) / "preview"; - params.working_directory_preview = wdp.string(); - const CacheLocation cache = current_cache_location(working_directory, params.session_cache_choice); - params.working_directory_cache = new_run_cache_folder(cache, working_directory).string(); - if (params.run_report && cache.kind != CacheKind::DataFolder) - params.run_report->addVolume(cache.base, "cache"); - - params.raw_cloud_loader.reset(); - if (params.lazy_load_raw_clouds) - { - params.raw_cloud_loader = std::make_shared(); - auto& L = *params.raw_cloud_loader; - // a reload (the GUI opening another folder) must not keep the previous session's clouds - std::vector>(minSize).swap(pointsPerFile); - const double inner = params.filter_threshold_xy_inner, outer = params.filter_threshold_xy_outer; - L.files.assign(laz_files.begin(), laz_files.begin() + minSize); - L.file_size.assign(minSize, 0); - L.file_time.assign(minSize, fs::file_time_type{}); - const std::vector files = L.files; - L.load = [files, inner, outer, combinedCalibration](size_t i) - { - auto data = load_point_cloud(files[i].c_str(), true, inner, outer, combinedCalibration); - std::sort( - data.begin(), - data.end(), - [](const Point3Di& a, const Point3Di& b) - { - return a.timestamp < b.timestamp; - }); - return data; - }; - L.t_first.assign(minSize, 0.0); - L.t_last.assign(minSize, 0.0); - L.n.assign(minSize, 0); - L.loaded.assign(minSize, 0); - L.done.assign(minSize, 0); - std::vector> gaps_in_file(minSize); - tbb::parallel_for( - std::min(firstUsedFile, minSize), // a skipped file's cloud is never used - minSize, - [&](size_t i) - { - auto data = L.load(i); - // after the read: a cloud drive may report other metadata once it has downloaded the file - std::error_code ec; - L.file_size[i] = fs::file_size(L.files[i], ec); - L.file_time[i] = fs::last_write_time(L.files[i], ec); - L.n[i] = data.size(); - if (!data.empty()) - { - L.t_first[i] = data.front().timestamp; - L.t_last[i] = data.back().timestamp; - } - gaps_in_file[i] = find_lidar_gaps(data, kLidarGapWarningS); - }); - report_lidar_gaps(L.files, firstUsedFile, gaps_in_file, L.t_first, L.t_last); - for (size_t i = 0; i < minSize; ++i) - fileSpans.laz.push_back({ L.files[i], L.t_first[i], L.t_last[i], L.n[i] }); - if (params.save_calibration_validation && minSize > 0) // as the eager load: the first file, then dropped - write_calibration_validation(wdp, L.load(0), params); - size_t totalPoints = 0; - for (auto k : L.n) - totalPoints += k; - std::cout << "TOTAL: " << totalPoints << " (lazy: ranges recorded, clouds loaded on demand)\n..loading finished.\n\n"; - return true; - } - - // --- Parallel load of LAZ files - std::vector> gaps_in_file(minSize); - std::vector t_first(minSize, 0.0); - std::vector t_last(minSize, 0.0); - tbb::parallel_for( - size_t(0), - minSize, - [&](size_t i) - { - const std::string& fn = laz_files[i]; - - auto data = load_point_cloud( - fn.c_str(), true, params.filter_threshold_xy_inner, params.filter_threshold_xy_outer, combinedCalibration); - - std::sort( - data.begin(), - data.end(), - [](const Point3Di& a, const Point3Di& b) - { - return a.timestamp < b.timestamp; - }); - - // Optional calibration validation (first file only) - if ((i == 0) && params.save_calibration_validation) - write_calibration_validation(wdp, data, params); - - if (!data.empty()) - { - t_first[i] = data.front().timestamp; - t_last[i] = data.back().timestamp; - } - gaps_in_file[i] = find_lidar_gaps(data, kLidarGapWarningS); + if (params.skip_first_file && pointsPerFile.size() > 0) + pointsPerFile.front().clear(); - // Store results - pointsPerFile[i] = std::move(data); - }); - report_lidar_gaps(laz_files, firstUsedFile, gaps_in_file, t_first, t_last); - for (size_t i = 0; i < minSize; ++i) - fileSpans.laz.push_back({ laz_files[i], t_first[i], t_last[i], pointsPerFile[i].size() }); + // --- Summary + size_t totalPoints = 0; + for (const auto& pp : pointsPerFile) + totalPoints += pp.size(); - if (params.skip_first_file && pointsPerFile.size() > 0) - pointsPerFile.front().clear(); + std::cout << "TOTAL: " << totalPoints << "\n..loading finished.\n\n"; + return true; +} - // --- Summary - size_t totalPoints = 0; - for (const auto& pp : pointsPerFile) - totalPoints += pp.size(); +bool load_data( + std::vector& input_file_names, + LidarOdometryParams& params, + std::vector>& pointsPerFile, + Imu& imu_data, + bool debugMsg) +{ + InputFileSpans unused; + return load_data(input_file_names, params, pointsPerFile, imu_data, debugMsg, unused); +} - std::cout << "TOTAL: " << totalPoints << "\n..loading finished.\n\n"; - return true; - } - else - { - std::cout << "Not enough files to continue: " << input_file_names.size() << std::endl; +bool load_data( + std::vector& input_file_names, + LidarOdometryParams& params, + std::vector>& pointsPerFile, + Imu& imu_data, + bool debugMsg, + InputFileSpans& fileSpans) +{ + fileSpans = {}; + if (!params.run_report || params.run_report->live().status != "running") + params.run_report = std::make_shared( + input_file_names.empty() ? fs::path{} : fs::path(input_file_names.front()).parent_path(), params.points_global_spill_directory); + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Loading); + HDMAP_ZONE_SCOPE("load_data"); + std::shared_ptr source = LazCsvSource::open(input_file_names, debugMsg); + if (!source) return false; - } + return load_from_source(source, params, pointsPerFile, imu_data, fileSpans); +} + +bool load_data( + const std::shared_ptr& source, + LidarOdometryParams& params, + std::vector>& pointsPerFile, + Imu& imu_data, + InputFileSpans& fileSpans) +{ + fileSpans = {}; + if (!params.run_report || params.run_report->live().status != "running") + params.run_report = std::make_shared(source->workingDirectory(), params.points_global_spill_directory); + RunReport::Scope timing(params.run_report.get(), RunReport::Stage::Loading); + HDMAP_ZONE_SCOPE("load_data"); + return load_from_source(source, params, pointsPerFile, imu_data, fileSpans); } void calculate_trajectory(Trajectory& trajectory, Imu& imu_data, LidarOdometryParams& params, bool debugMsg) @@ -790,7 +508,7 @@ bool compute_step_1( params.initial_points.reserve(params.threshold_initial_points); auto& ppf = pointsPerFile; - RawCloudLoader* loader = params.raw_cloud_loader.get(); + const auto& loader = params.raw_cloud_loader; // null unless lazy_load_raw_clouds if (loader) { if (ppf.size() != loader->n.size()) @@ -804,7 +522,7 @@ bool compute_step_1( } for (size_t fi = 0; fi < pointsPerFile.size(); fi++) { - if (!lazy_ensure(loader, ppf, fi)) + if (loader && !loader->ensure(ppf, fi)) return step_1_failed(params, loader->error); const auto& pp = pointsPerFile[fi]; // number_of_points += pp.size(); @@ -906,11 +624,11 @@ bool compute_step_1( if (L.n[index] == 0) continue; if (L.t_last[index] < t0) // every later chunk starts later still: never read again - lazy_release(loader, ppf, index); + L.release(ppf, index); else if (L.t_first[index] < t1) // may hold points in [t0, t1): load; the search below decides { - if (!lazy_ensure(loader, ppf, index)) - return step_1_failed(params, loader->error); + if (!L.ensure(ppf, index)) + return step_1_failed(params, L.error); } } } diff --git a/apps/lidar_odometry_step_1/lidar_odometry.h b/apps/lidar_odometry_step_1/lidar_odometry.h index 6ca4c19e..d64f7f8f 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.h +++ b/apps/lidar_odometry_step_1/lidar_odometry.h @@ -4,6 +4,7 @@ #include #include "lidar_odometry_utils.h" +#include "recording_source.h" #include "run_report.h" #include "toml_io.h" #include @@ -14,17 +15,6 @@ #include using Trajectory = std::map>; -using Imu = std::vector, Eigen::Vector3f, Eigen::Vector3f>>; - -//! Time span of one input file as load_data read it. -struct InputFileSpan -{ - std::string file; - double first = 0.0; //!< first sample's LiDAR-clock time [s]; 0 when count is 0 - double last = 0.0; //!< last sample's LiDAR-clock time [s] - size_t count = 0; //!< points or IMU samples read -}; - //! Per-file spans load_data reports when asked, e.g. for a Gantt chart of the session. struct InputFileSpans { @@ -50,6 +40,14 @@ bool load_data( Imu& imu_data, bool debugMsg, InputFileSpans& fileSpans); +//! Loads any recording; the file-list overloads above open the folder as a LazCsvSource and continue here. +//! @param fileSpans receives the spans; reset first +bool load_data( + const std::shared_ptr& source, + LidarOdometryParams& params, + std::vector>& pointsPerFile, + Imu& imu_data, + InputFileSpans& fileSpans); void calculate_trajectory(Trajectory& trajectory, Imu& imu_data, LidarOdometryParams& params, bool debugMsg); // pointsPerFile is read, and with lazy_load_raw_clouds loaded and freed file by file bool compute_step_1( diff --git a/apps/lidar_odometry_step_1/raw_cloud_loader.cpp b/apps/lidar_odometry_step_1/raw_cloud_loader.cpp deleted file mode 100644 index 4de5729e..00000000 --- a/apps/lidar_odometry_step_1/raw_cloud_loader.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "raw_cloud_loader.h" - -//! Empty if file i still has the size and modification time recorded by load_data, else what differs. -static std::string metadata_change(const RawCloudLoader& L, size_t i) -{ - std::error_code size_error, time_error; - const auto size = fs::file_size(L.files[i], size_error); - const auto time = fs::last_write_time(L.files[i], time_error); - if (time_error) - return "cannot read its modification time: " + time_error.message(); - if (size != L.file_size[i]) - return size_error ? "cannot read its size: " + size_error.message() - : "size " + std::to_string(L.file_size[i]) + " -> " + std::to_string(size) + " bytes"; - if (time != L.file_time[i]) - return "modification time changed"; - return {}; -} - -bool lazy_ensure(RawCloudLoader* L, std::vector>& ppf, size_t i) -{ - if (!L || L->loaded[i] || L->done[i] || L->n[i] == 0) - return true; - const auto refuse = [&](const std::string& what, const std::string& why) - { - L->error = "'" + L->files[i] + "' " + what + " (" + why + - "). If the data folder is on a network or cloud drive, copy it to a local disk and try again."; - return false; - }; - if (const std::string why = metadata_change(*L, i); !why.empty()) - return refuse("changed or vanished since it was first read", why); - ppf[i] = L->load(i); - // checked again after the read, so a file replaced while it was being opened is refused too - std::string why = metadata_change(*L, i); - if (why.empty() && ppf[i].size() != L->n[i]) - why = std::to_string(L->n[i]) + " -> " + std::to_string(ppf[i].size()) + " points"; - else if (why.empty() && (ppf[i].front().timestamp != L->t_first[i] || ppf[i].back().timestamp != L->t_last[i])) - why = "first or last point timestamp differs"; - if (!why.empty()) - { - std::vector().swap(ppf[i]); - return refuse("reads differently than when it was first read", why); - } - L->loaded[i] = 1; - return true; -} - -void lazy_release(RawCloudLoader* L, std::vector>& ppf, size_t i) -{ - if (!L || !L->loaded[i]) - return; - std::vector().swap(ppf[i]); - L->loaded[i] = 0; - L->done[i] = 1; -} diff --git a/apps/mandeye_raw_data_viewer/CMakeLists.txt b/apps/mandeye_raw_data_viewer/CMakeLists.txt index e987b7b3..3736611d 100644 --- a/apps/mandeye_raw_data_viewer/CMakeLists.txt +++ b/apps/mandeye_raw_data_viewer/CMakeLists.txt @@ -10,8 +10,9 @@ set(SOURCES ../lidar_odometry_step_1/lidar_odometry_utils.cpp ../lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp ../lidar_odometry_step_1/points_global_spill.cpp - ../lidar_odometry_step_1/raw_cloud_loader.cpp ../lidar_odometry_step_1/output_folders.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/raw_cloud_loader.cpp ) # Windows: add resource file @@ -26,6 +27,8 @@ add_executable( target_include_directories( mandeye_raw_data_viewer PRIVATE include + ${REPOSITORY_DIRECTORY}/apps/lidar_odometry_step_1 + ${REPOSITORY_DIRECTORY}/recording_sources ${REPOSITORY_DIRECTORY}/core/include ${REPOSITORY_DIRECTORY}/core_hd_mapping/include ${THIRDPARTY_DIRECTORY} diff --git a/pybind/CMakeLists.txt b/pybind/CMakeLists.txt index 366c7096..b44d3eb1 100644 --- a/pybind/CMakeLists.txt +++ b/pybind/CMakeLists.txt @@ -75,8 +75,9 @@ target_sources(lidar_odometry_py ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/points_global_spill.cpp - ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/raw_cloud_loader.cpp ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/output_folders.cpp + ${CMAKE_SOURCE_DIR}/recording_sources/laz_csv_source.cpp + ${CMAKE_SOURCE_DIR}/recording_sources/raw_cloud_loader.cpp ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/toml_io.cpp ) @@ -120,6 +121,7 @@ target_include_directories(core_py target_include_directories(lidar_odometry_py PRIVATE ${pybind11_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1 + ${CMAKE_SOURCE_DIR}/recording_sources ${REPOSITORY_DIRECTORY}/core/include ${REPOSITORY_DIRECTORY}/core_hd_mapping/include ${EIGEN3_INCLUDE_DIR} diff --git a/recording_sources/laz_csv_source.cpp b/recording_sources/laz_csv_source.cpp new file mode 100644 index 00000000..c3c0a1fe --- /dev/null +++ b/recording_sources/laz_csv_source.cpp @@ -0,0 +1,358 @@ +#include "laz_csv_source.h" + +#include "spdlog/spdlog.h" +#include "tbb/tbb.h" + +#include +#include +#include +#include + +namespace fs = std::filesystem; + +//! Time span and sample count of one IMU file's samples. +static InputFileSpan imu_file_span(const std::string& file, const Imu& samples) +{ + InputFileSpan span{ file }; + for (const auto& sample : samples) + { + const double t = std::get<0>(sample).first; + span.first = span.count == 0 ? t : std::min(span.first, t); + span.last = span.count == 0 ? t : std::max(span.last, t); + span.count++; + } + return span; +} + +std::unique_ptr LazCsvSource::open(std::vector& input_file_names, bool debugMsg) +{ + std::sort(input_file_names.begin(), input_file_names.end()); + std::vector csv_files, laz_files; + std::string sn_file; + std::string calibrationFile; + + std::cout << "Loading data..\n--------------\n"; + + // --- Separate files by type + for (const auto& fileName : input_file_names) + { + std::string ext = fs::path(fileName).extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + + if (ext == ".csv") + csv_files.push_back(fileName); + else if (ext == ".json") + { + std::string stem = fs::path(fileName).filename().stem().string(); // get filename without extension + + // skip files not related to calibration + if (!stem.starts_with("status") && !stem.starts_with("cam0") && !stem.starts_with("cam1")) + if (calibrationFile.empty()) + calibrationFile = fileName; + else + std::cout << "Unexpected JSON file found (" << fileName << "). Ignored..\n"; + } + else if ((ext == ".laz") || (ext == ".las")) + laz_files.push_back(fileName); + else if (ext == ".mjc") + { + if (calibrationFile.empty()) + calibrationFile = fileName; + else + std::cout << "Unexpected calibration file found (" << fileName << "). Ignored.." << std::endl; + } + else if ((ext == ".sn") && sn_file.empty()) + { + sn_file = fileName; + std::cout << "Only using first SN file found\n"; + } + } + + auto get4index = [](const std::string& path) -> std::string + { + auto s = fs::path(path).stem().string(); + return s.size() > 4 ? s.substr(s.size() - 4) : s; + }; + + for (size_t i = 0; i < laz_files.size(); i++) + { + std::string lfs = get4index(laz_files[i]); + + bool found = false; + for (size_t j = 0; j < csv_files.size(); j++) + { + std::string cfs = get4index(csv_files[j]); + if (lfs.compare(cfs) == 0) + { + found = true; + break; + } + } + + if (!found) + { + std::cout << "\n!!! there is no CSV file for: " << laz_files[i] << " !!! \n\n"; + } + } + + for (size_t i = 0; i < csv_files.size(); i++) + { + std::string lfs = get4index(csv_files[i]); + + bool found = false; + for (size_t j = 0; j < laz_files.size(); j++) + { + std::string cfs = get4index(laz_files[j]); + if (lfs.compare(cfs) == 0) + { + found = true; + break; + } + } + + if (!found) + { + std::cout << "\n!!! there is no LAZ file for: " << csv_files[i] << " !!! \n\n"; + } + } + + if (input_file_names.size() <= 2) + { + std::cout << "Not enough files to continue: " << input_file_names.size() << std::endl; + return nullptr; + } + + std::string working_directory = fs::path(input_file_names.front()).parent_path().string(); + + if (laz_files.size() != csv_files.size()) + std::cout << "!!! file number issue. continuing can lead to incomplete data!!!\n" << std::endl; + + // check if folder exists! + if (!fs::exists(working_directory)) + { + std::cerr << "Folder '" << working_directory << "' does not exist.\n"; + return nullptr; + } + + // --- Calibration and IMU setup + const auto preloadedCalibration = MLvxCalib::GetCalibrationFromFile(calibrationFile); + const std::string imuSnToUse = MLvxCalib::GetImuSnToUse(calibrationFile); + const auto idToSn = MLvxCalib::GetIdToSnMapping(sn_file); + + // gate invalid calibration + std::stringstream err; + if (idToSn.size() > 1) + { + bool valid = true; + for (const auto& [_, sn] : idToSn) + { + if (!preloadedCalibration.contains(sn)) + { + valid = false; + err << "Missing serial number from calibration file " << sn.c_str() << "\n"; + } + } + + if (!valid) + { + err << "Data containst Lidars with those serial numbers :" << std::endl; + for (const auto& [id, sn] : idToSn) + { + err << " - " << id << " : " << sn.c_str() << "\n"; + } + + if (calibrationFile.empty()) + { + err << "But no calibration was given found\n"; + } + else + { + err << "Calibration file found : " << calibrationFile.c_str() << ", but contains following Lidars : \n"; + for (const auto& [sn, _] : preloadedCalibration) + { + err << " - " << sn << "\n"; + } + } + spdlog::error(err.str()); + throw std::runtime_error(err.str()); + } + } + + if (!preloadedCalibration.empty()) + { + std::cout << "Loaded calibration for:\n"; + for (const auto& [sn, _] : preloadedCalibration) + std::cout << " -> " << sn << "\n"; + + bool hasError = false; + + for (const auto& [id, sn] : idToSn) + { + if (preloadedCalibration.find(sn) == preloadedCalibration.end()) + { + std::cerr << "WRONG CALIBRATION FILE! THE SERIAL NUMBER SHOULD BE " << sn << "!!!\n"; + hasError = true; + } + } + + if (!hasError && preloadedCalibration.find(imuSnToUse) == preloadedCalibration.end()) + { + std::cerr << "MISSING CALIBRATION FOR imuSnToUse: " << imuSnToUse << "!!!\n"; + std::cerr << "Available serial numbers in calibration file are:\n"; + for (const auto& [snKey, _] : preloadedCalibration) + std::cerr << " - " << snKey << "\n"; + + hasError = true; + } + + if (hasError) + { + std::cerr << "Press ENTER to exit...\n"; + std::cin.get(); + std::exit(EXIT_FAILURE); + } + } + else + { + std::cout << "There is no calibration file in folder!" << std::endl; + std::cout << "IGNORE THIS MESSAGE IF YOU ONLY HAVE 1 LiDAR" << std::endl; + + // example file for 2x LiDAR": + /* + { + "calibration" : { + "47MDL9T0020193" : { + "identity" : "true" + }, + "47MDL9S0020300" : + { + "order" : "ROW", + "inverted" : "TRUE", + "data" : [ + 0.999824, 0.00466397, -0.0181595, -0.00425984, + -0.0181478, -0.00254457, -0.999832, -0.151599, + -0.0047094, 0.999986, -0.00245948, -0.146408, + 0, 0, 0, 1 + ] + } + }, + "imuToUse" : "47MDL9T0020193" + }*/ + } + + std::unique_ptr source(new LazCsvSource()); + source->working_directory_ = working_directory; + source->sn_file_ = sn_file; + source->imu_number_to_use_ = MLvxCalib::GetImuIdToUse(idToSn, imuSnToUse); + // --- Precompute calibration once (major optimization) + source->calibration_ = MLvxCalib::CombineIntoCalibration(idToSn, preloadedCalibration); + + const std::size_t minSize = std::min(laz_files.size(), csv_files.size()); + source->laz_files_.assign(laz_files.begin(), laz_files.begin() + minSize); + source->csv_files_.assign(csv_files.begin(), csv_files.begin() + minSize); + + if (debugMsg) // if true this will break parallelism + { + for (const auto& [id, calib] : source->calibration_) + std::cout << " id : " << id << "\n" << calib.matrix() << "\n"; + } + return source; +} + +fs::path LazCsvSource::workingDirectory() const +{ + return working_directory_; +} + +size_t LazCsvSource::chunkCount() const +{ + return laz_files_.size(); +} + +std::string LazCsvSource::chunkName(size_t i) const +{ + return laz_files_[i]; +} + +std::vector LazCsvSource::loadPoints(size_t i, const PointFilter& filter) const +{ + auto data = load_point_cloud(laz_files_[i].c_str(), filter.omit_timestamp_zero, filter.xy_inner, filter.xy_outer, calibration_); + std::sort( + data.begin(), + data.end(), + [](const Point3Di& a, const Point3Di& b) + { + return a.timestamp < b.timestamp; + }); + return data; +} + +ChunkStamp LazCsvSource::stamp(size_t i) const +{ + std::error_code ec; + ChunkStamp s; + s.size = fs::file_size(laz_files_[i], ec); + if (!ec) + s.time = fs::last_write_time(laz_files_[i], ec); + s.valid = !ec; + return s; +} + +void LazCsvSource::loadImu(Imu& imu_data, std::vector& imuSpans) const +{ + // --- Load IMU data (still sequential, could parallelize later) + std::cout << "loading IMU data from 'imu****.csv' using ID " << imu_number_to_use_ << " from reference '" << sn_file_ << "' ..\n"; + + const std::size_t minSize = csv_files_.size(); + // Each thread loads into its own local vector + std::vector imuChunks(minSize); + + tbb::parallel_for( + tbb::blocked_range(0, minSize), + [&](const tbb::blocked_range& range) + { + for (size_t i = range.begin(); i < range.end(); ++i) + { + imuChunks[i] = load_imu(csv_files_[i].c_str(), imu_number_to_use_); + } + }); + + for (size_t i = 0; i < minSize; ++i) + imuSpans.push_back(imu_file_span(csv_files_[i], imuChunks[i])); + + // Merge all chunks sequentially at the end + for (auto& chunk : imuChunks) + imu_data.insert(imu_data.end(), std::make_move_iterator(chunk.begin()), std::make_move_iterator(chunk.end())); + + // Units with an external IMU (e.g. Murata) leave 'imu****.csv' header-only and log the IMU + // into a subfolder, in files not aligned with the LiDAR chunks + const fs::path murataImuDir = working_directory_ / "MURATA_IMU"; + if (imu_data.empty() && fs::is_directory(murataImuDir)) + { + std::vector murataFiles; + for (const auto& entry : fs::directory_iterator(murataImuDir)) + { + std::string ext = entry.path().extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + if (entry.is_regular_file() && ext == ".csv" && entry.file_size() > 0) + murataFiles.push_back(entry.path().string()); + } + std::sort(murataFiles.begin(), murataFiles.end()); + std::cout << "no IMU data in 'imu****.csv', loading " << murataFiles.size() << " file(s) from '" << murataImuDir.string() + << "' ..\n"; + + std::vector murataChunks(murataFiles.size()); + tbb::parallel_for( + size_t(0), + murataFiles.size(), + [&](size_t i) + { + murataChunks[i] = load_imu(murataFiles[i], imu_number_to_use_); + }); + imuSpans.clear(); + for (size_t i = 0; i < murataFiles.size(); ++i) + imuSpans.push_back(imu_file_span(murataFiles[i], murataChunks[i])); + for (auto& chunk : murataChunks) + imu_data.insert(imu_data.end(), std::make_move_iterator(chunk.begin()), std::make_move_iterator(chunk.end())); + } +} diff --git a/recording_sources/laz_csv_source.h b/recording_sources/laz_csv_source.h new file mode 100644 index 00000000..358533f4 --- /dev/null +++ b/recording_sources/laz_csv_source.h @@ -0,0 +1,35 @@ +#pragma once + +#include "recording_source.h" + +#include +#include +#include +#include + +//! A Mandeye recording folder: lidarNNNN.laz chunks paired with imuNNNN.csv files by their last four stem characters, +//! plus the optional calibration (.mjc or calibration .json), .sn file and MURATA_IMU folder. +class LazCsvSource : public RecordingSource +{ +public: + //! Sorts input_file_names, pairs the files and loads and checks the calibration; exits the process on a wrong + //! calibration file, as load_data always did. Returns null when there are not enough files or the folder is missing. + static std::unique_ptr open(std::vector& input_file_names, bool debugMsg); + + std::filesystem::path workingDirectory() const override; + size_t chunkCount() const override; + std::string chunkName(size_t i) const override; + std::vector loadPoints(size_t i, const PointFilter& filter) const override; + ChunkStamp stamp(size_t i) const override; + void loadImu(Imu& imu_data, std::vector& imuSpans) const override; + +private: + LazCsvSource() = default; + + std::filesystem::path working_directory_; + std::vector laz_files_; //!< the first chunkCount() LAZ files, each paired with csv_files_[i] + std::vector csv_files_; + std::string sn_file_; + int imu_number_to_use_ = 0; + std::unordered_map calibration_; +}; diff --git a/recording_sources/raw_cloud_loader.cpp b/recording_sources/raw_cloud_loader.cpp new file mode 100644 index 00000000..d467012d --- /dev/null +++ b/recording_sources/raw_cloud_loader.cpp @@ -0,0 +1,51 @@ +#include "raw_cloud_loader.h" + +//! Empty if chunk i still has the stamp recorded by load_data, else what differs. +static std::string stamp_change(const RawCloudLoader& L, size_t i) +{ + const ChunkStamp now = L.source->stamp(i); + if (!now.valid) + return "cannot read its size or modification time"; + if (now.size != L.stamp[i].size) + return "size " + std::to_string(L.stamp[i].size) + " -> " + std::to_string(now.size) + " bytes"; + if (now.time != L.stamp[i].time) + return "modification time changed"; + return {}; +} + +bool RawCloudLoader::ensure(std::vector>& ppf, size_t i) +{ + if (loaded[i] || done[i] || n[i] == 0) + return true; + const auto refuse = [&](const std::string& what, const std::string& why) + { + error = "'" + source->chunkName(i) + "' " + what + " (" + why + + "). If the data folder is on a network or cloud drive, copy it to a local disk and try again."; + return false; + }; + if (const std::string why = stamp_change(*this, i); !why.empty()) + return refuse("changed or vanished since it was first read", why); + ppf[i] = source->loadPoints(i, filter); + // checked again after the read, so a file replaced while it was being opened is refused too + std::string why = stamp_change(*this, i); + if (why.empty() && ppf[i].size() != n[i]) + why = std::to_string(n[i]) + " -> " + std::to_string(ppf[i].size()) + " points"; + else if (why.empty() && (ppf[i].front().timestamp != t_first[i] || ppf[i].back().timestamp != t_last[i])) + why = "first or last point timestamp differs"; + if (!why.empty()) + { + std::vector().swap(ppf[i]); + return refuse("reads differently than when it was first read", why); + } + loaded[i] = 1; + return true; +} + +void RawCloudLoader::release(std::vector>& ppf, size_t i) +{ + if (!loaded[i]) + return; + std::vector().swap(ppf[i]); + loaded[i] = 0; + done[i] = 1; +} diff --git a/apps/lidar_odometry_step_1/raw_cloud_loader.h b/recording_sources/raw_cloud_loader.h similarity index 57% rename from apps/lidar_odometry_step_1/raw_cloud_loader.h rename to recording_sources/raw_cloud_loader.h index 8be68a53..1bd4bc99 100644 --- a/apps/lidar_odometry_step_1/raw_cloud_loader.h +++ b/recording_sources/raw_cloud_loader.h @@ -1,8 +1,9 @@ #pragma once #include "lidar_odometry_utils.h" +#include "recording_source.h" -#include +#include #include #include @@ -16,19 +17,18 @@ //! same order. The loader lives in LidarOdometryParams::raw_cloud_loader, so each pipeline owns its own. struct RawCloudLoader { - std::function(size_t)> load; - std::vector files; - std::vector file_size; - std::vector file_time; + std::shared_ptr source; + PointFilter filter; + std::vector stamp; //!< each chunk's state when first read std::vector t_first, t_last; std::vector n; std::vector loaded, done; - std::string error; //!< why lazy_ensure last refused a file -}; - -//! Load file i if step 1 needs it and it is not in memory. Lazy loading reads every file twice (the range pass in -//! load_data, then here), so a file that changed in between is refused rather than silently processed. -//! @return false if file i was refused; L->error says why -bool lazy_ensure(RawCloudLoader* L, std::vector>& ppf, size_t i); + std::string error; //!< why ensure last refused a chunk -void lazy_release(RawCloudLoader* L, std::vector>& ppf, size_t i); \ No newline at end of file + //! Load chunk i into ppf[i] if step 1 needs it and it is not in memory. Lazy loading reads every chunk twice (the + //! range pass in load_data, then here), so a chunk that changed in between is refused rather than silently processed. + //! @return false if chunk i was refused; error says why + bool ensure(std::vector>& ppf, size_t i); + //! Free ppf[i] for good: step 1 has passed its last point. + void release(std::vector>& ppf, size_t i); +}; diff --git a/recording_sources/recording_source.h b/recording_sources/recording_source.h new file mode 100644 index 00000000..4389e9a6 --- /dev/null +++ b/recording_sources/recording_source.h @@ -0,0 +1,58 @@ +#pragma once + +#include "lidar_odometry_utils.h" + +#include +#include +#include +#include +#include +#include + +using Imu = std::vector, Eigen::Vector3f, Eigen::Vector3f>>; + +//! Time span of one input file as load_data read it. +struct InputFileSpan +{ + std::string file; + double first = 0.0; //!< first sample's LiDAR-clock time [s]; 0 when count is 0 + double last = 0.0; //!< last sample's LiDAR-clock time [s] + size_t count = 0; //!< points or IMU samples read +}; + +//! Filter every RecordingSource applies to the points it returns (the arguments of load_point_cloud). +struct PointFilter +{ + bool omit_timestamp_zero = true; + double xy_inner = 0.0; + double xy_outer = 0.0; +}; + +//! State of a chunk's backing data, compared to detect a chunk that changed between two reads. +struct ChunkStamp +{ + bool valid = false; + std::uintmax_t size = 0; + std::filesystem::file_time_type time{}; +}; + +//! A recording as step 1 reads it: an IMU stream plus raw LiDAR points split into time-ordered chunks. +//! load_data() and the lazy raw cloud loader read input data only through this interface. +class RecordingSource +{ +public: + virtual ~RecordingSource() = default; + + //! Folder that receives preview/, cache/ and the default lio_result_*. + virtual std::filesystem::path workingDirectory() const = 0; + //! Number of point chunks. + virtual size_t chunkCount() const = 0; + //! Name of chunk i in logs and InputFileSpans (the full path for file-backed chunks). + virtual std::string chunkName(size_t i) const = 0; + //! Calibrated points of chunk i that pass the filter, sorted by timestamp. Safe to call from several threads. + virtual std::vector loadPoints(size_t i, const PointFilter& filter) const = 0; + //! Current state of chunk i's backing data. + virtual ChunkStamp stamp(size_t i) const = 0; + //! Appends every IMU sample, unsorted, to imu_data; imuSpans receives one span per IMU input file. + virtual void loadImu(Imu& imu_data, std::vector& imuSpans) const = 0; +}; From 3626609876f39f03b02ae9e98d876a8b82c79e49 Mon Sep 17 00:00:00 2001 From: MichalPelka Date: Sun, 22 Nov 2026 03:24:10 +0100 Subject: [PATCH 02/21] rosbags: read a log-time range of MCAP and ROS1 bag files The readers could only stream a whole file. Reading one time window on its own is what a lazily loaded recording needs. - McapFileReader::read and Ros1BagFileReader::read take an optional LogTimeRange [start_ns, end_ns); the default still reads everything. MCAP passes it to mcap's ReadMessageOptions, so the chunk index skips the rest. An indexed ROS1 bag decompresses only the chunks whose chunk info overlaps the range; an unindexed one is scanned whole. - logTimeSpan() / Ros1BagReader::recordTimeSpan() report the first and last message time from the statistics record or the chunk index. - The IMU rotation and acceleration-unit conversion of mcap_to_laz move to rosbags/ImuTransform.h for reuse; the converter is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158FTTEePKhmGqE9Z1HgwUd --- apps/console_tools/CMakeLists.txt | 4 +- apps/console_tools/mcap_to_laz.cpp | 60 +++++----------------- rosbags/ImuTransform.h | 42 +++++++++++++++ rosbags/McapReader.cpp | 22 +++++++- rosbags/McapReader.h | 22 ++++++-- rosbags/Ros1Bag.cpp | 82 +++++++++++++++++++++++++++++- rosbags/Ros1Bag.h | 26 ++++++++-- 7 files changed, 200 insertions(+), 58 deletions(-) create mode 100644 rosbags/ImuTransform.h diff --git a/apps/console_tools/CMakeLists.txt b/apps/console_tools/CMakeLists.txt index 7a9c5fa9..9fe0bf19 100644 --- a/apps/console_tools/CMakeLists.txt +++ b/apps/console_tools/CMakeLists.txt @@ -85,7 +85,7 @@ target_link_libraries( # mcap_to_laz: the inverse of laz_to_mcap -- MCAP/ROS2 bag -> mandeye session # directory. Needs neither lidar_odometry_utils.cpp nor core: reading is # rosbags/McapReader and writing is rosbags/MandeyeSessionWriter, so laszip + -# mcap + spdlog is the whole dependency set. +# mcap + spdlog (+ header-only Eigen) is the whole dependency set. # # McapWriter.cpp is compiled in even though nothing here writes bags: it holds # the single MCAP_IMPLEMENTATION definition, which McapReader.cpp deliberately @@ -101,6 +101,7 @@ add_executable( target_include_directories( mcap_to_laz PRIVATE ${REPOSITORY_DIRECTORY}/rosbags + ${EIGEN3_INCLUDE_DIR} ${LASZIP_INCLUDE_DIR}/LASzip/include) target_link_libraries( @@ -130,6 +131,7 @@ target_compile_definitions(bag_to_laz PRIVATE HDMAPPING_IMPORT_ROS1_BAG) target_include_directories( bag_to_laz PRIVATE ${REPOSITORY_DIRECTORY}/rosbags + ${EIGEN3_INCLUDE_DIR} ${LASZIP_INCLUDE_DIR}/LASzip/include) target_link_libraries( bag_to_laz diff --git a/apps/console_tools/mcap_to_laz.cpp b/apps/console_tools/mcap_to_laz.cpp index 87cb5294..3f316edb 100644 --- a/apps/console_tools/mcap_to_laz.cpp +++ b/apps/console_tools/mcap_to_laz.cpp @@ -7,6 +7,7 @@ // load_point_cloud()/load_imu(); reading is handled by rosbags/McapReader and // writing by rosbags/MandeyeSessionWriter, which keeps this tool free of // core/TBB/glm/toml++/vqf. +#include "ImuTransform.h" #include "MandeyeSessionWriter.h" #include "McapReader.h" #if defined(HDMAPPING_IMPORT_ROS1_BAG) @@ -41,40 +42,6 @@ namespace constexpr const char* kInputDescription = "a ros2msg/CDR MCAP bag, e.g. one written by laz_to_mcap"; #endif - // Standard gravity, the g HDMapping's IMU csv is scaled in. - constexpr double kStandardGravity = 9.80665; - - // What the importer does to every IMU sample before it reaches the csv: - // rotate it into the lidar frame (the frame HDMapping assumes the IMU is in) - // and bring acceleration to g. - struct ImuTransform - { - double qx = 0.0, qy = 0.0, qz = 0.0, qw = 1.0; // IMU frame -> lidar frame - double acc_scale = 1.0; // 1 for a bag already in g, 1/9.80665 for m/s^2 - }; - - void rotate(const ImuTransform& q, float& x, float& y, float& z) - { - // v' = v + 2w (u x v) + 2 u x (u x v), u = (qx, qy, qz) - const double vx = x, vy = y, vz = z; - const double cx = q.qy * vz - q.qz * vy, cy = q.qz * vx - q.qx * vz, cz = q.qx * vy - q.qy * vx; - x = static_cast(vx + 2.0 * (q.qw * cx + q.qy * cz - q.qz * cy)); - y = static_cast(vy + 2.0 * (q.qw * cy + q.qz * cx - q.qx * cz)); - z = static_cast(vz + 2.0 * (q.qw * cz + q.qx * cy - q.qy * cx)); - } - - void apply_imu_transform(const ImuTransform& t, std::vector& samples) - { - for (auto& s : samples) - { - rotate(t, s.gyro_x, s.gyro_y, s.gyro_z); - rotate(t, s.acc_x, s.acc_y, s.acc_z); - s.acc_x = static_cast(s.acc_x * t.acc_scale); - s.acc_y = static_cast(s.acc_y * t.acc_scale); - s.acc_z = static_cast(s.acc_z * t.acc_scale); - } - } - // Absolute time grid, matching MessageSplitter in laz_to_mcap.cpp: a timestamp t // belongs to bin floor(t / chunk_seconds). Because the grid is absolute rather // than relative to the first message, lidar and IMU bin identically without the @@ -332,7 +299,7 @@ int main(const int argc, const char** argv) rosbags::McapReaderOptions options; double chunk_seconds = 10.0; bool list_only = false; - ImuTransform imu_transform; + rosbags::ImuTransform imu_transform; for (int i = 1; i < argc; ++i) { @@ -381,29 +348,26 @@ int main(const int argc, const char** argv) } else if (arg == "--imu-rotation" && i + 4 < argc) { + double qx = 0.0, qy = 0.0, qz = 0.0, qw = 1.0; try { - imu_transform.qx = std::stod(argv[++i]); - imu_transform.qy = std::stod(argv[++i]); - imu_transform.qz = std::stod(argv[++i]); - imu_transform.qw = std::stod(argv[++i]); + qx = std::stod(argv[++i]); + qy = std::stod(argv[++i]); + qz = std::stod(argv[++i]); + qw = std::stod(argv[++i]); } catch (const std::exception&) { spdlog::error("Invalid --imu-rotation (expected four numbers qx qy qz qw)"); return EXIT_FAILURE; } - const double n = std::sqrt( - imu_transform.qx * imu_transform.qx + imu_transform.qy * imu_transform.qy + imu_transform.qz * imu_transform.qz + - imu_transform.qw * imu_transform.qw); + const Eigen::Quaterniond q(qw, qx, qy, qz); + const double n = q.norm(); if (!std::isfinite(n) || std::abs(n - 1.0) > 1e-3) { spdlog::error("Invalid --imu-rotation (not a unit quaternion, norm {:.6f})", n); return EXIT_FAILURE; } - imu_transform.qx /= n; - imu_transform.qy /= n; - imu_transform.qz /= n; - imu_transform.qw /= n; + imu_transform.imu_to_lidar = q.normalized(); } else if (arg == "--imu-acc-unit" && hasValue) { @@ -411,7 +375,7 @@ int main(const int argc, const char** argv) if (unit == "g") imu_transform.acc_scale = 1.0; else if (unit == "ms2") - imu_transform.acc_scale = 1.0 / kStandardGravity; + imu_transform.acc_scale = 1.0 / rosbags::kStandardGravity; else { spdlog::error("Unknown --imu-acc-unit '{}' (expected g|ms2)", unit); @@ -534,7 +498,7 @@ int main(const int argc, const char** argv) spdlog::info("Bag serial number: {}", serial_number); if (!topics.imu.empty()) imu_progress.finish(imu.size()); - apply_imu_transform(imu_transform, imu); + rosbags::applyImuTransform(imu_transform, imu); spdlog::info("Read {} IMU sample(s)", imu.size()); rosbags::MandeyeSessionWriter writer(session_dir, /*with_rgb=*/false, /*with_ring=*/true); diff --git a/rosbags/ImuTransform.h b/rosbags/ImuTransform.h new file mode 100644 index 00000000..dddc4b71 --- /dev/null +++ b/rosbags/ImuTransform.h @@ -0,0 +1,42 @@ +#pragma once +// What an importer does to every IMU sample of a bag before HDMapping uses it: +// rotate it into the lidar frame (the frame HDMapping assumes the IMU is in) and +// bring acceleration to g. Shared by mcap_to_laz / bag_to_laz and the bag +// recording source of lidar_odometry_step_1. +#include "McapWriter.h" // McapImuSample + +#include + +#include + +namespace rosbags +{ + +// Standard gravity, the g HDMapping's IMU csv is scaled in. +inline constexpr double kStandardGravity = 9.80665; + +struct ImuTransform +{ + Eigen::Quaterniond imu_to_lidar = Eigen::Quaterniond::Identity(); // IMU frame -> lidar frame + double acc_scale = 1.0; // 1 for a bag already in g, 1/9.80665 for m/s^2 +}; + +inline void applyImuTransform(const ImuTransform& t, McapImuSample& s) +{ + const Eigen::Vector3f gyro = (t.imu_to_lidar * Eigen::Vector3d(s.gyro_x, s.gyro_y, s.gyro_z)).cast(); + const Eigen::Vector3f acc = (t.imu_to_lidar * Eigen::Vector3d(s.acc_x, s.acc_y, s.acc_z)).cast(); + s.gyro_x = gyro.x(); + s.gyro_y = gyro.y(); + s.gyro_z = gyro.z(); + s.acc_x = static_cast(acc.x() * t.acc_scale); + s.acc_y = static_cast(acc.y() * t.acc_scale); + s.acc_z = static_cast(acc.z() * t.acc_scale); +} + +inline void applyImuTransform(const ImuTransform& t, std::vector& samples) +{ + for(auto& s : samples) + applyImuTransform(t, s); +} + +} // namespace rosbags diff --git a/rosbags/McapReader.cpp b/rosbags/McapReader.cpp index 80d5a835..77a5b66f 100644 --- a/rosbags/McapReader.cpp +++ b/rosbags/McapReader.cpp @@ -202,7 +202,25 @@ const std::string& McapFileReader::lidarLayoutWarning() const return impl_->lidarLayoutWarning; } -bool McapFileReader::read(const Callbacks& callbacks) +std::optional McapFileReader::logTimeSpan() const +{ + if(!impl_) + return std::nullopt; + if(const auto& statistics = impl_->reader.statistics(); statistics && statistics->messageCount > 0) + return LogTimeRange{statistics->messageStartTime, statistics->messageEndTime + 1}; + const auto& chunkIndexes = impl_->reader.chunkIndexes(); + if(chunkIndexes.empty()) + return std::nullopt; + LogTimeRange span{std::numeric_limits::max(), 0}; + for(const auto& chunk : chunkIndexes) + { + span.start_ns = std::min(span.start_ns, chunk.messageStartTime); + span.end_ns = std::max(span.end_ns, chunk.messageEndTime + 1); + } + return span; +} + +bool McapFileReader::read(const Callbacks& callbacks, const LogTimeRange& range) { if(!isOpen()) return false; @@ -218,6 +236,8 @@ bool McapFileReader::read(const Callbacks& callbacks) return true; mcap::ReadMessageOptions read_options; + read_options.startTime = range.start_ns; + read_options.endTime = range.end_ns; read_options.readOrder = impl_->timeOrdered ? mcap::ReadMessageOptions::ReadOrder::LogTimeOrder : mcap::ReadMessageOptions::ReadOrder::FileOrder; read_options.topicFilter = [&](std::string_view topic) { diff --git a/rosbags/McapReader.h b/rosbags/McapReader.h index 49ecb2bc..ec105aa1 100644 --- a/rosbags/McapReader.h +++ b/rosbags/McapReader.h @@ -4,7 +4,9 @@ #include #include #include +#include #include +#include #include #include @@ -47,6 +49,14 @@ struct ResolvedTopics LidarSchema lidar_schema = LidarSchema::Unknown; }; +// Half-open range [start_ns, end_ns) of message log times: the MCAP log time, or +// the record time of a ROS1 bag. The default covers every message. +struct LogTimeRange +{ + uint64_t start_ns = 0; + uint64_t end_ns = std::numeric_limits::max(); +}; + // One channel as found in the file, for --list output and diagnostics. struct ChannelInfo { @@ -111,9 +121,15 @@ class McapFileReader std::function onSn; }; - // Streams the whole file through `callbacks`. Returns false on a read error - // (see error()); a file with no matching messages is not an error. - bool read(const Callbacks& callbacks); + // Streams the messages whose log time lies in `range` (by default the whole + // file) through `callbacks`. Uses the chunk index to skip the rest when the file + // has one. Returns false on a read error (see error()); a file with no matching + // messages is not an error. + bool read(const Callbacks& callbacks, const LogTimeRange& range = {}); + + // Log times of the file's first and last message, from the statistics record or + // the chunk index; nullopt when the file has neither. + std::optional logTimeSpan() const; private: struct Impl; diff --git a/rosbags/Ros1Bag.cpp b/rosbags/Ros1Bag.cpp index f6d5d060..005fe05e 100644 --- a/rosbags/Ros1Bag.cpp +++ b/rosbags/Ros1Bag.cpp @@ -434,8 +434,18 @@ bool Ros1BagReader::readIndex() break; message_counts[conn] += count; } + IndexedChunk chunk; + const auto start = header.find("start_time"); + const auto end = header.find("end_time"); + if(fieldAs(header, "chunk_pos", chunk.pos) && start != header.end() && end != header.end()) + { + chunk.start_ns = timeFromField(start->second); + chunk.end_ns = timeFromField(end->second); + chunks_.push_back(chunk); + } } } + std::sort(chunks_.begin(), chunks_.end(), [](const IndexedChunk& a, const IndexedChunk& b) { return a.pos < b.pos; }); for(const auto& [conn, count] : message_counts) { const auto it = connections_.find(conn); @@ -499,10 +509,72 @@ bool Ros1BagReader::parseRecords(const uint8_t* data, size_t size, const Message return true; } +std::optional Ros1BagReader::recordTimeSpan() const +{ + if(chunks_.empty()) + return std::nullopt; + LogTimeRange span{std::numeric_limits::max(), 0}; + for(const auto& chunk : chunks_) + { + span.start_ns = std::min(span.start_ns, chunk.start_ns); + span.end_ns = std::max(span.end_ns, chunk.end_ns + 1); + } + return span; +} + bool Ros1BagReader::forEachMessage(const MessageFn& fn) { if(!isOpen()) return false; + return scanAll(fn); +} + +bool Ros1BagReader::forEachMessage(const MessageFn& fn, const LogTimeRange& range) +{ + if(!isOpen()) + return false; + const MessageFn inRange = [&](const Ros1Connection& c, uint64_t time_ns, const uint8_t* data, size_t size) + { + return time_ns < range.start_ns || time_ns >= range.end_ns || fn(c, time_ns, data, size); + }; + if(chunks_.empty()) + return scanAll(inRange); + + HeaderFields header; + std::vector data, chunk; + bool stop = false; + for(const auto& indexed : chunks_) + { + if(indexed.end_ns < range.start_ns || indexed.start_ns >= range.end_ns) + continue; + file_.clear(); + file_.seekg(static_cast(indexed.pos)); + if(!readRecord(file_, header, data, error_)) + { + if(error_.empty()) + error_ = "cannot read the chunk at offset " + std::to_string(indexed.pos); + return false; + } + uint8_t op = 0; + uint32_t size = 0; + const auto compression = header.find("compression"); + if(!fieldAs(header, "op", op) || op != kOpChunk || compression == header.end() || !fieldAs(header, "size", size)) + { + error_ = "malformed chunk record at offset " + std::to_string(indexed.pos); + return false; + } + if(!decompress(compression->second, data, size, chunk, error_)) + return false; + if(!parseRecords(chunk.data(), chunk.size(), inRange, stop)) + return false; + if(stop) + break; + } + return true; +} + +bool Ros1BagReader::scanAll(const MessageFn& fn) +{ file_.clear(); file_.seekg(static_cast(kMagicSize)); HeaderFields header; @@ -1008,7 +1080,12 @@ const std::string& Ros1BagFileReader::lidarLayoutWarning() const return warning_; } -bool Ros1BagFileReader::read(const Callbacks& callbacks) +std::optional Ros1BagFileReader::logTimeSpan() const +{ + return reader_.recordTimeSpan(); +} + +bool Ros1BagFileReader::read(const Callbacks& callbacks, const LogTimeRange& range) { if(!open_) return false; @@ -1075,7 +1152,8 @@ bool Ros1BagFileReader::read(const Callbacks& callbacks) callbacks.onSn(time_ns, sn); } return true; - }); + }, + range); if(!ok) error_ = reader_.error(); return ok; diff --git a/rosbags/Ros1Bag.h b/rosbags/Ros1Bag.h index 65000244..c8ece478 100644 --- a/rosbags/Ros1Bag.h +++ b/rosbags/Ros1Bag.h @@ -55,15 +55,31 @@ class Ros1BagReader // Returns false on a read or decompression error (see error()). using MessageFn = std::function; bool forEachMessage(const MessageFn& fn); + // As above, for the messages whose record time lies in `range`. An indexed bag + // reads only the chunks that overlap it; an unindexed one is scanned whole. + bool forEachMessage(const MessageFn& fn, const LogTimeRange& range); + + // Record times covered by the chunks in the index section; nullopt for an + // unindexed bag. + std::optional recordTimeSpan() const; private: + struct IndexedChunk + { + uint64_t pos{}; + uint64_t start_ns{}; + uint64_t end_ns{}; // inclusive, as in the chunk info record + }; + bool readIndex(); bool parseRecords(const uint8_t* data, size_t size, const MessageFn& fn, bool& stop); + bool scanAll(const MessageFn& fn); std::ifstream file_; std::string error_; uint64_t index_pos_{}; std::map connections_; + std::vector chunks_; // from the index section, ordered by file position }; class Ros1BagWriter @@ -193,9 +209,13 @@ class Ros1BagFileReader bool timeOrdered() const; const std::string& lidarLayoutWarning() const; - // Streams the whole bag through `callbacks`; `log_time_ns` is the bag record - // time. Returns false on a read error (see error()). - bool read(const Callbacks& callbacks); + // Streams the messages whose record time lies in `range` (by default the whole + // bag) through `callbacks`; `log_time_ns` is the bag record time. Returns false + // on a read error (see error()). + bool read(const Callbacks& callbacks, const LogTimeRange& range = {}); + + // Record times covered by the bag's chunks; nullopt for an unindexed bag. + std::optional logTimeSpan() const; private: Ros1BagReader reader_; From 9d5e8543d3ef72b0b65a430fef87309b57ea19ff Mon Sep 17 00:00:00 2001 From: MichalPelka Date: Sun, 22 Nov 2026 03:24:10 +0100 Subject: [PATCH 03/21] step 1, raw viewer: open ROS1 bags and MCAP files directly A ROS1 bag or MCAP file no longer has to be converted with bag_to_laz / mcap_to_laz before step 1 or the raw data viewer can read it. - BagSource (recording_sources/bag_source.h/.cpp): a RecordingSource for both formats. Chunks are windows of message log time (10 s by default) read through the file's index, each with its own reader, so lazy and parallel loading work. Points keep the lidar frame (lidar id 0); IMU samples are rotated into the lidar frame and scaled to g, as the converters do. The working directory is the file's folder. Unindexed files are refused with a hint to reindex them. - BagSourceConfigUi (recording_sources/bag_source_ui.h/.cpp): ImGui form that produces the BagSourceConfig: lidar and IMU topics from the file's channels (the only candidate preselected), PointCloud2 layout, IMU acceleration unit and rotation, chunk length. - lidar_odometry_step_1: "Load & process ROS bag / MCAP" button and drag and drop open the form; the command line accepts a .bag/.mcap path and uses its only lidar and IMU topics. - mandeye_raw_data_viewer: "Open ROS bag / MCAP" in the open menu and drag and drop. Underground Parking exported with laz_to_mcap / laz_to_bag and read directly gives the same trajectory as the same MCAP converted back with mcap_to_laz (229.96 / 230.25 m against 230.36 m, single thread). The difference from the original LAZ session (223.55 m) comes from the export round trip. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158FTTEePKhmGqE9Z1HgwUd --- apps/lidar_odometry_step_1/CMakeLists.txt | 17 +- .../lidar_odometry_gui.cpp | 144 +++++++-- apps/mandeye_raw_data_viewer/CMakeLists.txt | 10 +- .../mandeye_raw_data_viewer.cpp | 74 ++++- core/include/Core/pfd_wrapper.hpp | 1 + recording_sources/bag_source.cpp | 297 ++++++++++++++++++ recording_sources/bag_source.h | 62 ++++ recording_sources/bag_source_ui.cpp | 123 ++++++++ recording_sources/bag_source_ui.h | 31 ++ 9 files changed, 729 insertions(+), 30 deletions(-) create mode 100644 recording_sources/bag_source.cpp create mode 100644 recording_sources/bag_source.h create mode 100644 recording_sources/bag_source_ui.cpp create mode 100644 recording_sources/bag_source_ui.h diff --git a/apps/lidar_odometry_step_1/CMakeLists.txt b/apps/lidar_odometry_step_1/CMakeLists.txt index a95efe69..f659c238 100644 --- a/apps/lidar_odometry_step_1/CMakeLists.txt +++ b/apps/lidar_odometry_step_1/CMakeLists.txt @@ -34,8 +34,18 @@ if(WIN32) list(APPEND SOURCES "resource.rc") endif() +# ROS1 bag / MCAP recordings (bag_source): the rosbags readers. McapWriter.cpp holds the single MCAP_IMPLEMENTATION +# that McapReader.cpp relies on. +set(BAG_SOURCES + ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.h ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/bag_source_ui.h ${REPOSITORY_DIRECTORY}/recording_sources/bag_source_ui.cpp + ${REPOSITORY_DIRECTORY}/rosbags/McapReader.cpp + ${REPOSITORY_DIRECTORY}/rosbags/McapWriter.cpp + ${REPOSITORY_DIRECTORY}/rosbags/Ros1Bag.cpp +) + add_executable( - lidar_odometry_step_1 lidar_odometry_gui.cpp ${SOURCES} + lidar_odometry_step_1 lidar_odometry_gui.cpp ${SOURCES} ${BAG_SOURCES} ) target_compile_definitions(lidar_odometry_step_1 PRIVATE WITH_GUI=1) @@ -57,11 +67,14 @@ target_include_directories( ${LASZIP_INCLUDE_DIR}/LASzip/include ${THIRDPARTY_DIRECTORY}/observation_equations/codes ${THIRDPARTY_DIRECTORY}/vqf/vqf/cpp - ${THIRDPARTY_DIRECTORY}/Fusion/Fusion) + ${THIRDPARTY_DIRECTORY}/Fusion/Fusion + ${REPOSITORY_DIRECTORY}/rosbags) target_link_libraries( lidar_odometry_step_1 PRIVATE + mcap + ros1bag_compression step1_run_report # core_raylib_utils brings in core_raylib (core, raylib), raylib_widgets and rlImGui. core_raylib_utils diff --git a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp index 274eb290..6381f42c 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp @@ -15,6 +15,8 @@ #undef ShowCursor #endif +#include "bag_source.h" +#include "bag_source_ui.h" #include "lidar_odometry.h" #include "lidar_odometry_utils.h" #include "render_cache.h" @@ -205,6 +207,9 @@ bool pipelinePending = false; bool pendingCompute = true, pendingSave = true; std::string pendingFolder; void startPipeline(const std::string& folder, bool compute, bool save); +std::shared_ptr pending_recording; //!< set with startPipeline; step1() loads it instead of the folder +std::unique_ptr bag_config_ui; //!< the open ROS bag / MCAP window, if any +std::string bag_open_error; static void resources_gui() { @@ -697,21 +702,36 @@ void step1(const std::string& input_folder_name, const std::atomic& loPaus { trajectory_points_dirty = true; std::vector input_file_names; + // a recording prepared in the ROS bag / MCAP window is loaded instead of the folder's files + const std::shared_ptr recording = std::exchange(pending_recording, nullptr); std::cout << "Selected folder: '" << input_folder_name << std::endl; - if (fs::exists(input_folder_name)) + if (recording || fs::exists(input_folder_name)) { check_output_folders(input_folder_name, params.session_cache_choice); // before anything is loaded - RunReport::Scope discovery(params.run_report.get(), RunReport::Stage::Loading); - for (const auto& entry : fs::directory_iterator(input_folder_name)) - if (entry.is_regular_file()) - input_file_names.push_back(entry.path().string()); - - discovery.finish(); - if (load_data(input_file_names, params, pointsPerFile, imu_data, full_debug_messages)) + bool loaded = false; + if (recording) + { + InputFileSpans spans; + loaded = load_data(recording, params, pointsPerFile, imu_data, spans); + if (loaded) + working_directory = recording->workingDirectory().string(); + } + else + { + RunReport::Scope discovery(params.run_report.get(), RunReport::Stage::Loading); + for (const auto& entry : fs::directory_iterator(input_folder_name)) + if (entry.is_regular_file()) + input_file_names.push_back(entry.path().string()); + + discovery.finish(); + loaded = load_data(input_file_names, params, pointsPerFile, imu_data, full_debug_messages); + if (loaded) + working_directory = fs::path(input_file_names[0]).parent_path().string(); + } + if (loaded) { - working_directory = fs::path(input_file_names[0]).parent_path().string(); calculate_trajectory(trajectory, imu_data, params, full_debug_messages); if (compute_step_1(pointsPerFile, params, trajectory, worker_data, loPause)) { @@ -1915,6 +1935,43 @@ void startPipeline(const std::string& folder, bool compute, bool save) pipelinePending = true; } +//! Opens the window that configures a ROS1 bag or MCAP file; asks for the file when none is given. +void openBag(const std::string& file = "") +{ + std::string path = file; + if (path.empty()) + { + const auto files = mandeye::fd::OpenFileDialog("Select ROS1 bag or MCAP file", mandeye::fd::Bag_filter, false); + if (files.empty()) + return; + path = files.front(); + } + bag_open_error.clear(); + bag_config_ui = std::make_unique(path); +} + +//! Window with the topic choice of the selected bag; Open loads it and starts processing. +static void bag_source_window() +{ + bool open = true; + ImGui::Begin("Open ROS bag / MCAP", &open, ImGuiWindowFlags_AlwaysAutoResize); + if (bag_config_ui->draw()) + { + auto source = open_bag_source(bag_config_ui->config(), bag_open_error); + if (source) + { + pending_recording = std::move(source); + startPipeline(pending_recording->workingDirectory().string(), true, true); + open = false; + } + } + if (!bag_open_error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", bag_open_error.c_str()); + ImGui::End(); + if (!open) + bag_config_ui.reset(); +} + static void launchPipeline(const std::string& folder, bool compute, bool save) { if (loRunning) @@ -2034,24 +2091,50 @@ bool step1( std::vector& worker_data, const std::atomic& loPause) { - params.run_report = std::make_shared(folder, params.points_global_spill_directory, "cli"); - check_output_folders(folder, params.session_cache_choice); // before anything is loaded + // a ROS1 bag or MCAP file is read with its only lidar and IMU topics (the GUI lets the user choose) + const bool bag = is_bag_file(folder) && fs::is_regular_file(folder); + const fs::path data_folder = bag ? fs::path(folder).parent_path() : fs::path(folder); + params.run_report = std::make_shared(data_folder, params.points_global_spill_directory, "cli"); + check_output_folders(data_folder, params.session_cache_choice); // before anything is loaded std::vector input_file_names; RunReport::Scope discovery(params.run_report.get(), RunReport::Stage::Loading); - for (const auto& entry : fs::directory_iterator(folder)) + bool loaded = false; + if (bag) { - if (!entry.is_directory()) + BagSourceConfig config; + config.file = folder; + std::string error; + const auto source = open_bag_source(config, error); + discovery.finish(); + if (!source) { - std::cout << entry.path() << std::endl; - input_file_names.push_back(entry.path().string()); + std::cerr << "Cannot read '" << folder << "': " << error << std::endl; + return false; } + InputFileSpans spans; + loaded = load_data(source, params, pointsPerFile, imu_data, spans); + if (loaded) + working_directory = source->workingDirectory().string(); } + else + { + for (const auto& entry : fs::directory_iterator(folder)) + { + if (!entry.is_directory()) + { + std::cout << entry.path() << std::endl; + input_file_names.push_back(entry.path().string()); + } + } - discovery.finish(); - if (load_data(input_file_names, params, pointsPerFile, imu_data, full_debug_messages)) + discovery.finish(); + loaded = load_data(input_file_names, params, pointsPerFile, imu_data, full_debug_messages); + if (loaded) + working_directory = fs::path(input_file_names[0]).parent_path().string(); + } + if (loaded) { - working_directory = fs::path(input_file_names[0]).parent_path().string(); calculate_trajectory(trajectory, imu_data, params, full_debug_messages); if (!compute_step_1(pointsPerFile, params, trajectory, worker_data, loPause)) return false; @@ -2467,9 +2550,12 @@ void display() view_kbd_shortcuts(); - // Drag and drop: a Mandeye data folder, or any file in one, is processed like "Load & process scanning". + // Drag and drop: a Mandeye data folder, or any file in one, is processed like "Load & process scanning"; + // a ROS1 bag or MCAP file opens its window first. const auto dropped = takeDroppedFiles(); - if (!dropped.empty() && !loRunning && !pipelinePending) + if (!dropped.empty() && !loRunning && !pipelinePending && is_bag_file(dropped[0]) && fs::is_regular_file(dropped[0])) + openBag(dropped[0]); + else if (!dropped.empty() && !loRunning && !pipelinePending) { fs::path folder(dropped[0]); if (!fs::is_directory(folder)) @@ -2754,6 +2840,12 @@ void display() cache_location_menu(); + ImGui::SameLine(); + if (ImGui::Button("Load & process ROS bag / MCAP")) + openBag(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Select a ROS1 bag (*.bag) or an MCAP file (*.mcap), choose its topics and start processing"); + ImGui::SameLine(); ImGui::Dummy(ImVec2(20, 0)); ImGui::SameLine(); @@ -2920,6 +3012,9 @@ void display() settings_gui(); } + if (!loRunning && bag_config_ui) + bag_source_window(); + if (loRunning) progress_window(); @@ -2979,7 +3074,8 @@ int main(int argc, char* argv[]) << std::filesystem::path(argv[0]).stem().string() << " \n" << std::filesystem::path(argv[0]).stem().string() << " --dump-default-params \n\n" << "where\n" - << " Path where scan files are located (*.csv, *.laz, *.sn)\n" + << " Path where scan files are located (*.csv, *.laz, *.sn), or a ROS1 bag\n" + << " (*.bag) / MCAP file (*.mcap) with one lidar and one IMU topic\n" << " Path to TOML parameter file (*.toml)\n" << " Path where processed session should be stored\n" << " (with alone, default parameters are used and the\n" @@ -3022,8 +3118,10 @@ int main(int argc, char* argv[]) if (argc == 2) // running from command line { auto path = fs::path(argv[1]); - if (is_directory(path)) + if (is_directory(path) || (is_bag_file(path) && fs::is_regular_file(path))) { + // results and failure reports go next to a bag file, or into the data folder + const fs::path input_dir = is_directory(path) ? path : path.parent_path(); std::string working_directory; std::vector worker_data; @@ -3035,7 +3133,7 @@ int main(int argc, char* argv[]) !step2(worker_data, params, loPause)) { std::cerr << "Lidar odometry failed: no point-cloud results saved" << std::endl; - save_failed_run_report(params, get_next_result_path(path.string()), "Loading/preparation/odometry failed"); + save_failed_run_report(params, get_next_result_path(input_dir.string()), "Loading/preparation/odometry failed"); remove_cache(params); return 1; } diff --git a/apps/mandeye_raw_data_viewer/CMakeLists.txt b/apps/mandeye_raw_data_viewer/CMakeLists.txt index 3736611d..fd0ceaca 100644 --- a/apps/mandeye_raw_data_viewer/CMakeLists.txt +++ b/apps/mandeye_raw_data_viewer/CMakeLists.txt @@ -13,6 +13,11 @@ set(SOURCES ../lidar_odometry_step_1/output_folders.cpp ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.cpp ${REPOSITORY_DIRECTORY}/recording_sources/raw_cloud_loader.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/bag_source_ui.cpp + ${REPOSITORY_DIRECTORY}/rosbags/McapReader.cpp + ${REPOSITORY_DIRECTORY}/rosbags/McapWriter.cpp + ${REPOSITORY_DIRECTORY}/rosbags/Ros1Bag.cpp ) # Windows: add resource file @@ -40,11 +45,14 @@ target_include_directories( ${LASZIP_INCLUDE_DIR}/LASzip/include ${THIRDPARTY_DIRECTORY}/observation_equations/codes ${THIRDPARTY_DIRECTORY}/vqf/vqf/cpp - ${THIRDPARTY_DIRECTORY}/Fusion/Fusion) + ${THIRDPARTY_DIRECTORY}/Fusion/Fusion + ${REPOSITORY_DIRECTORY}/rosbags) target_link_libraries( mandeye_raw_data_viewer PRIVATE + mcap + ros1bag_compression step1_run_report # core_raylib_utils brings in core_raylib (core, raylib), raylib_widgets and rlImGui. core_raylib_utils diff --git a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp index fef970bc..a2017eb8 100644 --- a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp +++ b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp @@ -27,6 +27,8 @@ #include "../lidar_odometry_step_1/lidar_odometry.h" #include "../lidar_odometry_step_1/lidar_odometry_utils.h" +#include "bag_source.h" +#include "bag_source_ui.h" #include #include #include @@ -1034,7 +1036,9 @@ void rebuildAllData(bool preserve_position) playback_playing = false; } -void loadFiles(std::vector input_file_names) +//! Loads the files of a Mandeye data folder, or the prepared recording when source is set (input_file_names is then +//! empty). +void loadFiles(std::vector input_file_names, const std::shared_ptr& source = nullptr) { LidarOdometryParams params; // dummy for load_data function params.save_calibration_validation = false; @@ -1047,10 +1051,12 @@ void loadFiles(std::vector input_file_names) Imu imu_data; // no files selected, quit loading - if (input_file_names.empty()) + if (input_file_names.empty() && !source) return; - if (load_data(input_file_names, params, pointsPerFile, imu_data, false, file_spans)) + const bool loaded = source ? load_data(source, params, pointsPerFile, imu_data, file_spans) + : load_data(input_file_names, params, pointsPerFile, imu_data, false, file_spans); + if (loaded) { // clear possible previous data @@ -1122,6 +1128,11 @@ void loadFiles(std::vector input_file_names) } } + // a recording's chunks have no files of their own: name them as load_data did + if (source) + for (const auto& span : file_spans.laz) + laz_files.push_back(span.file); + // rest of RAW data viewer processing // VQF initialization @@ -1292,9 +1303,17 @@ void openFolder() loadFiles(input_file_names); } -//! Drag and drop: dropped folders load like "Open folder", dropped files like "Open files". +void openBag(const std::string& file = ""); + +//! Drag and drop: dropped folders load like "Open folder", dropped files like "Open files", +//! a single dropped ROS1 bag or MCAP file opens its window. void openDropped(const std::vector& paths) { + if (paths.size() == 1 && is_bag_file(paths.front()) && fs::is_regular_file(paths.front())) + { + openBag(paths.front()); + return; + } std::vector input_file_names; for (const auto& path : paths) { @@ -1315,6 +1334,45 @@ void openFiles() loadFiles(input_file_names); } +std::unique_ptr bag_config_ui; //!< the open ROS bag / MCAP window, if any +std::string bag_open_error; + +//! Opens the window that configures a ROS1 bag or MCAP file; asks for the file when none is given. +void openBag(const std::string& file) +{ + std::string path = file; + if (path.empty()) + { + const auto files = mandeye::fd::OpenFileDialog("Select ROS1 bag or MCAP file", mandeye::fd::Bag_filter, false); + if (files.empty()) + return; + path = files.front(); + } + bag_open_error.clear(); + bag_config_ui = std::make_unique(path); +} + +//! Window with the topic choice of the selected bag; Open loads it. +void bag_source_window() +{ + bool open = true; + ImGui::Begin("Open ROS bag / MCAP", &open, ImGuiWindowFlags_AlwaysAutoResize); + if (bag_config_ui->draw()) + { + const auto source = open_bag_source(bag_config_ui->config(), bag_open_error); + if (source) + { + loadFiles({}, source); + open = false; + } + } + if (!bag_open_error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", bag_open_error.c_str()); + ImGui::End(); + if (!open) + bag_config_ui.reset(); +} + void imu_data_gui() { ImGui::Begin("IMU data", &show_imu_data); @@ -2122,6 +2180,11 @@ void display() openFiles(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Select files for analyze"); + if (ImGui::MenuItem("Open ROS bag / MCAP")) + openBag(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip( + "Select a ROS1 bag (*.bag) or an MCAP file (*.mcap) and choose its topics, or drop the file on the window"); ImGui::MenuItem("Skip first file", nullptr, &skip_first_file); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Drop the points of the first LAZ file on the next load, as step 1 does"); @@ -2296,6 +2359,9 @@ void display() if (is_settings_gui) settings_gui(); + if (bag_config_ui) + bag_source_window(); + rlImGuiEnd(); } diff --git a/core/include/Core/pfd_wrapper.hpp b/core/include/Core/pfd_wrapper.hpp index 6c7bae70..ae6c736f 100644 --- a/core/include/Core/pfd_wrapper.hpp +++ b/core/include/Core/pfd_wrapper.hpp @@ -13,6 +13,7 @@ namespace mandeye::fd const std::vector LAS_LAZ_filter = { "LASzip file (*.laz)", "*.laz", "LAS file (*.las)", "*.las", "All files", "*" }; const std::vector LazFilter = { "LAS/LAZ files (*.laz)", "*.las *.laz" }; const std::vector E57_filter = { "E57 point cloud (*.e57)", "*.e57", "All files", "*" }; + const std::vector Bag_filter = { "ROS1 bag / MCAP (*.bag *.mcap)", "*.bag *.mcap", "All files", "*" }; const std::vector ImageFilter = { "Image files (*.bmp, *.jpg, *.jpeg, *.png)", "*.bmp *.jpg *.jpeg *.png", "All files", "*" }; diff --git a/recording_sources/bag_source.cpp b/recording_sources/bag_source.cpp new file mode 100644 index 00000000..5203ae76 --- /dev/null +++ b/recording_sources/bag_source.cpp @@ -0,0 +1,297 @@ +// The rosbags headers come first: they re-enable std::byte on MSVC before any standard header (see rosbags/McapWriter.h). +#include "ImuTransform.h" +#include "McapReader.h" +#include "Ros1Bag.h" + +#include "bag_source.h" + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace +{ + std::string lower_extension(const fs::path& file) + { + std::string ext = file.extension().string(); + std::transform( + ext.begin(), + ext.end(), + ext.begin(), + [](unsigned char c) + { + return static_cast(std::tolower(c)); + }); + return ext; + } + + bool is_ros1_bag(const fs::path& file) + { + return lower_extension(file) == ".bag"; + } + + //! Message type without its package, as both readers compare it: "sensor_msgs/msg/Imu" -> "Imu". + std::string_view type_name(std::string_view type) + { + const auto slash = type.rfind('/'); + return slash == std::string_view::npos ? type : type.substr(slash + 1); + } + + rosbags::McapReaderOptions reader_options(const BagSourceConfig& config) + { + rosbags::McapReaderOptions options; + options.lidar_topic = config.lidar_topic; + options.imu_topic = config.imu_topic; + switch (config.lidar_layout) + { + case BagSourceConfig::LidarLayout::Auto: + options.lidar_preset = rosbags::Pc2Preset::Auto; + break; + case BagSourceConfig::LidarLayout::Hesai: + options.lidar_preset = rosbags::Pc2Preset::Hesai; + break; + case BagSourceConfig::LidarLayout::Ouster: + options.lidar_preset = rosbags::Pc2Preset::Ouster; + break; + } + return options; + } + + rosbags::ImuTransform imu_transform(const BagSourceConfig& config) + { + rosbags::ImuTransform t; + const auto& q = config.imu_to_lidar; // qx qy qz qw + t.imu_to_lidar = Eigen::Quaterniond(q[3], q[0], q[1], q[2]); + t.acc_scale = config.imu_acc_in_g ? 1.0 : 1.0 / rosbags::kStandardGravity; + return t; + } + + ChunkStamp file_stamp(const fs::path& file) + { + std::error_code ec; + ChunkStamp s; + s.size = fs::file_size(file, ec); + if (!ec) + s.time = fs::last_write_time(file, ec); + s.valid = !ec; + return s; + } + + //! A ROS1 bag or MCAP file split into windows of message log time. Every read opens its own reader, so chunks can be + //! loaded from several threads at once. + template + class BagSource final : public RecordingSource + { + public: + BagSource(const BagSourceConfig& config, const rosbags::LogTimeRange& span) + : config_(config) + , options_(reader_options(config)) + , imu_transform_(imu_transform(config)) + , span_(span) + { + const uint64_t length = span_.end_ns - span_.start_ns; + chunk_ns_ = config_.chunk_seconds > 0.0 ? static_cast(config_.chunk_seconds * 1e9) : length; + chunk_ns_ = std::max(chunk_ns_, 1); + chunk_count_ = std::max(1, static_cast((length + chunk_ns_ - 1) / chunk_ns_)); + } + + fs::path workingDirectory() const override + { + return config_.file.parent_path(); + } + + size_t chunkCount() const override + { + return chunk_count_; + } + + std::string chunkName(size_t i) const override + { + char index[16]; + std::snprintf(index, sizeof(index), "#%04zu", i); + return config_.file.string() + index; + } + + std::vector loadPoints(size_t i, const PointFilter& filter) const override + { + std::vector points; + Reader reader(config_.file, options_); + if (!reader.isOpen()) + { + std::cerr << "cannot open '" << config_.file.string() << "': " << reader.error() << "\n"; + return points; + } + + size_t total = 0; + typename Reader::Callbacks callbacks; + callbacks.onPointCloud = [&](uint64_t, std::vector&& cloud) + { + total += cloud.size(); + for (const auto& p : cloud) + { + if (filter.omit_timestamp_zero && p.timestamp == 0.0) + continue; + const double r = std::sqrt(static_cast(p.x) * p.x + static_cast(p.y) * p.y); + if (r <= filter.xy_inner || r >= filter.xy_outer) + continue; + Point3Di q{}; + q.point = Eigen::Vector3d(p.x, p.y, p.z); + q.timestamp = p.timestamp; + q.intensity = p.intensity; + q.lidarid = 0; + points.push_back(q); + } + }; + if (!reader.read(callbacks, window(i))) + std::cerr << "reading '" << chunkName(i) << "' failed: " << reader.error() << "\n"; + if (!reader.lidarLayoutWarning().empty()) + std::cerr << "'" << config_.file.string() << "': " << reader.lidarLayoutWarning() << "\n"; + + std::sort( + points.begin(), + points.end(), + [](const Point3Di& a, const Point3Di& b) + { + return a.timestamp < b.timestamp; + }); + std::cout << chunkName(i) << ": " << total << " - " << total - points.size() << " = " << points.size() << std::endl; + return points; + } + + ChunkStamp stamp(size_t) const override + { + return file_stamp(config_.file); + } + + void loadImu(Imu& imu_data, std::vector& imuSpans) const override + { + std::cout << "loading IMU data from '" << config_.file.string() << "' ..\n"; + Reader reader(config_.file, options_); + if (!reader.isOpen()) + { + std::cerr << "cannot open '" << config_.file.string() << "': " << reader.error() << "\n"; + return; + } + const size_t first = imu_data.size(); + typename Reader::Callbacks callbacks; + callbacks.onImu = [&](rosbags::McapImuSample s) + { + rosbags::applyImuTransform(imu_transform_, s); + imu_data.emplace_back( + std::pair(s.timestamp, 0.0), Eigen::Vector3f(s.gyro_x, s.gyro_y, s.gyro_z), Eigen::Vector3f(s.acc_x, s.acc_y, s.acc_z)); + }; + if (!reader.read(callbacks)) + std::cerr << "reading IMU from '" << config_.file.string() << "' failed: " << reader.error() << "\n"; + + InputFileSpan span{ config_.file.string() }; + for (size_t k = first; k < imu_data.size(); ++k) + { + const double t = std::get<0>(imu_data[k]).first; + span.first = span.count == 0 ? t : std::min(span.first, t); + span.last = span.count == 0 ? t : std::max(span.last, t); + span.count++; + } + imuSpans.push_back(span); + } + + private: + rosbags::LogTimeRange window(size_t i) const + { + rosbags::LogTimeRange w; + w.start_ns = span_.start_ns + i * chunk_ns_; + w.end_ns = i + 1 == chunk_count_ ? span_.end_ns : w.start_ns + chunk_ns_; + return w; + } + + BagSourceConfig config_; + rosbags::McapReaderOptions options_; + rosbags::ImuTransform imu_transform_; + rosbags::LogTimeRange span_; + uint64_t chunk_ns_ = 1; + size_t chunk_count_ = 1; + }; + + template + std::shared_ptr open_with(const BagSourceConfig& config, std::string& error) + { + Reader reader(config.file, reader_options(config)); + if (!reader.isOpen()) + { + error = reader.error(); + return nullptr; + } + if (reader.topics().lidar.empty()) + { + error = "no lidar topic (sensor_msgs/PointCloud2 or livox_ros_driver/CustomMsg) in the file"; + return nullptr; + } + if (reader.topics().imu.empty()) + { + error = "no IMU topic (sensor_msgs/Imu) in the file"; + return nullptr; + } + const auto span = reader.logTimeSpan(); + if (!span) + { + error = "the file has no index, so its time windows cannot be read on their own (reindex it: `rosbag reindex` for a " + "ROS1 bag, `mcap recover` for an MCAP file)"; + return nullptr; + } + return std::make_shared>(config, *span); + } + + template + std::vector channels_of(const fs::path& file, std::string& error) + { + Reader reader(file); + std::vector channels; + for (const auto& c : reader.channels()) + { + BagChannel channel{ c.topic, c.schema_name, c.message_count, BagChannel::Kind::Other }; + const auto type = type_name(c.schema_name); + if (type == "PointCloud2" || type == "CustomMsg") + channel.kind = BagChannel::Kind::Lidar; + else if (type == "Imu") + channel.kind = BagChannel::Kind::Imu; + channels.push_back(std::move(channel)); + } + // a reader that found channels but no unique lidar/IMU topic still lists them; only an unreadable file is an error + if (channels.empty()) + error = reader.error().empty() ? "the file has no topics" : reader.error(); + return channels; + } +} // namespace + +bool is_bag_file(const fs::path& file) +{ + const std::string ext = lower_extension(file); + return ext == ".bag" || ext == ".mcap"; +} + +std::vector list_bag_channels(const fs::path& file, std::string& error) +{ + error.clear(); + return is_ros1_bag(file) ? channels_of(file, error) : channels_of(file, error); +} + +std::shared_ptr open_bag_source(const BagSourceConfig& config, std::string& error) +{ + error.clear(); + if (!is_bag_file(config.file)) + { + error = "not a .bag or .mcap file: " + config.file.string(); + return nullptr; + } + if (config.chunk_seconds < 0.0) + { + error = "chunk length must not be negative"; + return nullptr; + } + return is_ros1_bag(config.file) ? open_with(config, error) + : open_with(config, error); +} diff --git a/recording_sources/bag_source.h b/recording_sources/bag_source.h new file mode 100644 index 00000000..9c9bf821 --- /dev/null +++ b/recording_sources/bag_source.h @@ -0,0 +1,62 @@ +#pragma once + +#include "recording_source.h" + +#include +#include +#include +#include +#include +#include + +// No rosbags header here: they re-enable std::byte on MSVC and must come before any standard header (see +// rosbags/McapWriter.h), which a header included by GUI code cannot guarantee. + +//! How a ROS1 bag or an MCAP file becomes a step 1 recording. Mirrors the options of bag_to_laz / mcap_to_laz. +struct BagSourceConfig +{ + //! PointCloud2 record layout; Auto reads it from each message's fields. + enum class LidarLayout + { + Auto, + Hesai, + Ouster + }; + + std::filesystem::path file; + std::string lidar_topic; //!< sensor_msgs/PointCloud2 or livox_ros_driver/CustomMsg; empty: the file's only one + std::string imu_topic; //!< sensor_msgs/Imu; empty: the file's only one + LidarLayout lidar_layout = LidarLayout::Auto; + bool imu_acc_in_g = true; //!< false: m/s^2 (the sensor_msgs/Imu convention), divided by standard gravity + std::array imu_to_lidar{ 0.0, 0.0, 0.0, 1.0 }; //!< rotation IMU frame -> lidar frame, qx qy qz qw + double chunk_seconds = 10.0; //!< length of one chunk of message log time +}; + +//! One topic of a bag file, for topic pickers. +struct BagChannel +{ + enum class Kind + { + Lidar, + Imu, + Other + }; + + std::string topic; + std::string type; //!< message type as the file names it + uint64_t message_count = 0; //!< 0 when the file carries no counts + Kind kind = Kind::Other; +}; + +//! True for the files open_bag_source reads: .bag (ROS1) and .mcap. +bool is_bag_file(const std::filesystem::path& file); + +//! The file's topics. Returns an empty list and sets error when the file cannot be read. +std::vector list_bag_channels(const std::filesystem::path& file, std::string& error); + +//! Opens a ROS1 bag or an MCAP file as a RecordingSource. Chunks are chunk_seconds windows of message log time, read +//! through the file's chunk index, so lazy loading reads each window on its own. Points keep the lidar frame (lidar id 0, +//! no calibration); IMU samples are rotated into the lidar frame and scaled to g. The working directory is the file's +//! folder. Requires an indexed file. +//! Returns null and sets error when the file cannot be used. +std::shared_ptr open_bag_source(const BagSourceConfig& config, std::string& error); diff --git a/recording_sources/bag_source_ui.cpp b/recording_sources/bag_source_ui.cpp new file mode 100644 index 00000000..91a6049c --- /dev/null +++ b/recording_sources/bag_source_ui.cpp @@ -0,0 +1,123 @@ +#include "bag_source_ui.h" + +#include + +#include +#include + +namespace +{ + std::string channel_label(const BagChannel& c) + { + std::string label = c.topic + " (" + c.type; + if (c.message_count > 0) + label += ", " + std::to_string(c.message_count) + " msgs"; + return label + ")"; + } + + std::vector::const_iterator find_channel(const std::vector& channels, const std::string& topic) + { + return std::find_if( + channels.begin(), + channels.end(), + [&topic](const BagChannel& c) + { + return c.topic == topic; + }); + } + + //! Combo over the channels of one kind; writes the chosen topic. + void topic_combo(const char* label, const std::vector& channels, BagChannel::Kind kind, std::string& topic) + { + const auto current = find_channel(channels, topic); + const std::string preview = current != channels.end() ? channel_label(*current) : ""; + if (ImGui::BeginCombo(label, preview.c_str())) + { + for (const auto& c : channels) + { + if (c.kind != kind) + continue; + const bool selected = c.topic == topic; + if (ImGui::Selectable(channel_label(c).c_str(), selected)) + topic = c.topic; + if (selected) + ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + } + + //! The topic of the only channel of this kind, or an empty string. + std::string only_topic(const std::vector& channels, BagChannel::Kind kind) + { + std::string topic; + for (const auto& c : channels) + { + if (c.kind != kind) + continue; + if (!topic.empty()) + return {}; + topic = c.topic; + } + return topic; + } +} // namespace + +BagSourceConfigUi::BagSourceConfigUi(const std::filesystem::path& file) +{ + config_.file = file; + channels_ = list_bag_channels(file, list_error_); + config_.lidar_topic = only_topic(channels_, BagChannel::Kind::Lidar); + config_.imu_topic = only_topic(channels_, BagChannel::Kind::Imu); +} + +bool BagSourceConfigUi::draw() +{ + ImGui::TextUnformatted(config_.file.filename().string().c_str()); + if (!list_error_.empty()) + { + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", list_error_.c_str()); + return false; + } + + topic_combo("LiDAR topic", channels_, BagChannel::Kind::Lidar, config_.lidar_topic); + topic_combo("IMU topic", channels_, BagChannel::Kind::Imu, config_.imu_topic); + + // the layout presets only apply to PointCloud2; a Livox CustomMsg has a fixed layout + const auto lidar = find_channel(channels_, config_.lidar_topic); + if (lidar != channels_.end() && lidar->type.ends_with("PointCloud2")) + { + const char* layouts[] = { "auto (from the message fields)", "Hesai", "Ouster" }; + int layout = static_cast(config_.lidar_layout); + if (ImGui::Combo("PointCloud2 layout", &layout, layouts, IM_ARRAYSIZE(layouts))) + config_.lidar_layout = static_cast(layout); + } + + int unit = config_.imu_acc_in_g ? 0 : 1; + ImGui::TextUnformatted("IMU acceleration unit:"); + ImGui::SameLine(); + ImGui::RadioButton("g", &unit, 0); + ImGui::SameLine(); + ImGui::RadioButton("m/s^2", &unit, 1); + config_.imu_acc_in_g = unit == 0; + + ImGui::InputScalarN( + "IMU -> lidar rotation (qx qy qz qw)", ImGuiDataType_Double, config_.imu_to_lidar.data(), 4, nullptr, nullptr, "%.6f"); + const auto& q = config_.imu_to_lidar; + const double norm = std::sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]); + const bool unit_quaternion = std::abs(norm - 1.0) < 1e-3; + if (!unit_quaternion) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "the rotation is not a unit quaternion (norm %.6f)", norm); + + ImGui::InputDouble("Chunk length [s]", &config_.chunk_seconds, 1.0, 5.0, "%.1f"); + if (config_.chunk_seconds < 0.0) + config_.chunk_seconds = 0.0; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Length of one chunk of message log time; 0 reads the whole file as one chunk"); + + const bool ready = !config_.lidar_topic.empty() && !config_.imu_topic.empty() && unit_quaternion; + ImGui::BeginDisabled(!ready); + const bool open = ImGui::Button("Open"); + ImGui::EndDisabled(); + return open && ready; +} diff --git a/recording_sources/bag_source_ui.h b/recording_sources/bag_source_ui.h new file mode 100644 index 00000000..b2dbf349 --- /dev/null +++ b/recording_sources/bag_source_ui.h @@ -0,0 +1,31 @@ +#pragma once + +#include "bag_source.h" + +#include +#include +#include + +//! ImGui form that builds the BagSourceConfig of one ROS1 bag or MCAP file: lidar and IMU topic pickers filled from the +//! file's topics (the only one of each type preselected), PointCloud2 layout, IMU acceleration unit and rotation into the +//! lidar frame, and chunk length. +class BagSourceConfigUi +{ +public: + //! Reads the file's topic list. + explicit BagSourceConfigUi(const std::filesystem::path& file); + + //! Draws the form into the current ImGui window. Returns true on the frame the user presses Open with a usable + //! configuration. + bool draw(); + + const BagSourceConfig& config() const + { + return config_; + } + +private: + BagSourceConfig config_; + std::vector channels_; + std::string list_error_; +}; From d31e0997e509e606956d6f22ec95afa820910c3a Mon Sep 17 00:00:00 2001 From: MichalPelka Date: Wed, 25 Nov 2026 02:18:53 +0100 Subject: [PATCH 04/21] Windows: build lz4, zstd and bzip2 so bags can be compressed On Windows mcap was built with MCAP_COMPRESSION_NO_LZ4/NO_ZSTD and rosbags/Ros1Bag compiled its chunk decompression out, so LZ4/Zstd MCAP files and bz2/lz4 ROS1 bags could not be read there. - 3rdparty/lz4 (v1.10.0), 3rdparty/zstd (v1.5.7), 3rdparty/bzip2 (bzip2-1.0.8): shallow submodules. - cmake/dependencies.cmake: on Windows, lz4_static, zstd_static and bz2_static are built from them; mcap and ros1bag_compression link them. Linux and macOS keep the system packages. - Ros1Bag.cpp: the MCAP_COMPRESSION_NO_LZ4 guard around bz2/lz4 is gone. - Test: an MCAP file with LZ4 and with Zstd chunks reads the same as the uncompressed one, on every platform. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0158FTTCHMj7SBbPGtmCBJg8 --- .gitmodules | 12 +++ 3rdparty/bzip2 | 1 + 3rdparty/lz4 | 1 + 3rdparty/mcap/CMakeLists.txt | 13 +--- 3rdparty/zstd | 1 + apps/console_tools/CMakeLists.txt | 3 +- cmake/dependencies.cmake | 40 +++++++++- rosbags/Ros1Bag.cpp | 4 - rosbags/Ros1Bag.h | 1 - rosbags/tests/test_mcap_reader.cpp | 121 +++++++++++++++++++++++++++++ 10 files changed, 177 insertions(+), 20 deletions(-) create mode 160000 3rdparty/bzip2 create mode 160000 3rdparty/lz4 create mode 160000 3rdparty/zstd diff --git a/.gitmodules b/.gitmodules index 21488810..7de2dc52 100644 --- a/.gitmodules +++ b/.gitmodules @@ -65,3 +65,15 @@ [submodule "3rdparty/fbow"] path = 3rdparty/fbow url = https://github.com/rmsalinas/fbow.git +[submodule "3rdparty/lz4"] + path = 3rdparty/lz4 + url = https://github.com/lz4/lz4.git + shallow = true +[submodule "3rdparty/zstd"] + path = 3rdparty/zstd + url = https://github.com/facebook/zstd.git + shallow = true +[submodule "3rdparty/bzip2"] + path = 3rdparty/bzip2 + url = https://gitlab.com/bzip2/bzip2.git + shallow = true diff --git a/3rdparty/bzip2 b/3rdparty/bzip2 new file mode 160000 index 00000000..6a8690fc --- /dev/null +++ b/3rdparty/bzip2 @@ -0,0 +1 @@ +Subproject commit 6a8690fc8d26c815e798c588f796eabe9d684cf0 diff --git a/3rdparty/lz4 b/3rdparty/lz4 new file mode 160000 index 00000000..ebb370ca --- /dev/null +++ b/3rdparty/lz4 @@ -0,0 +1 @@ +Subproject commit ebb370ca83af193212df4dcbadcc5d87bc0de2f0 diff --git a/3rdparty/mcap/CMakeLists.txt b/3rdparty/mcap/CMakeLists.txt index 7b7390a0..162c0c1c 100644 --- a/3rdparty/mcap/CMakeLists.txt +++ b/3rdparty/mcap/CMakeLists.txt @@ -14,16 +14,11 @@ target_include_directories(mcap INTERFACE ${mcap_SOURCE_DIR}/cpp/mcap/include) # even for callers that only ever write Compression::None -- so the symbols # must be linked unconditionally, not just when compression is actually used. # -# On Windows there's no system package manager providing liblz4/libzstd dev -# packages (unlike apt on Linux / Homebrew on macOS), and no vendored/prebuilt -# copy of them here yet -- see 3rdpartyBinary/Proj for that pattern if this -# ever needs revisiting. Until then, disable mcap's LZ4/ZSTD code paths on -# Windows via its own escape hatch: reading uncompressed/other-codec mcaps -# still works, only Compression::Lz4/Zstd at write time become unavailable -- -# fine since this repo's writer (rosbags/McapWriter) only ever writes -# Compression::None. +# Linux and macOS link the system liblz4/libzstd; Windows links the static +# lz4_static/zstd_static built from the lz4 and zstd submodules (see +# cmake/dependencies.cmake). if(WIN32) - target_compile_definitions(mcap INTERFACE MCAP_COMPRESSION_NO_LZ4 MCAP_COMPRESSION_NO_ZSTD) + target_link_libraries(mcap INTERFACE lz4_static zstd_static) else() find_library(MCAP_LZ4_LIBRARY NAMES lz4) find_library(MCAP_ZSTD_LIBRARY NAMES zstd) diff --git a/3rdparty/zstd b/3rdparty/zstd new file mode 160000 index 00000000..f8745da6 --- /dev/null +++ b/3rdparty/zstd @@ -0,0 +1 @@ +Subproject commit f8745da6ff1ad1e7bab384bd1f9d742439278e99 diff --git a/apps/console_tools/CMakeLists.txt b/apps/console_tools/CMakeLists.txt index 9fe0bf19..e09ccc8b 100644 --- a/apps/console_tools/CMakeLists.txt +++ b/apps/console_tools/CMakeLists.txt @@ -119,8 +119,7 @@ endif() # bag_to_laz / laz_to_bag: the ROS1 bag twins of mcap_to_laz / laz_to_mcap, # built from the same sources with a define that swaps the reader (writer) for # rosbags/Ros1Bag -- no ROS installation needed. Reading compressed chunks needs -# ros1bag_compression and mcap (see cmake/dependencies.cmake); on Windows only -# uncompressed bags are read. +# ros1bag_compression and mcap (see cmake/dependencies.cmake). add_executable( bag_to_laz mcap_to_laz.cpp ${REPOSITORY_DIRECTORY}/rosbags/Ros1Bag.h ${REPOSITORY_DIRECTORY}/rosbags/Ros1Bag.cpp diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index b9bb64d9..b1897aab 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -326,14 +326,46 @@ add_subdirectory(${EXTERNAL_LIBRARIES_DIRECTORY}/WGS84toCartesian) message(STATUS "Using external library: WGS84toCartesian") +# Compression libraries of the bag readers: LZ4 and Zstandard for mcap (MCAP chunks), bzip2 and LZ4 for +# rosbags/Ros1Bag (ROS1 bag chunks). Linux and macOS use the system packages (apt, Homebrew). Windows has no package +# manager for them, so they are built here as static libraries from the 3rdparty submodules. +if(WIN32) + add_library(lz4_static STATIC + ${THIRDPARTY_DIRECTORY}/lz4/lib/lz4.c + ${THIRDPARTY_DIRECTORY}/lz4/lib/lz4hc.c + ${THIRDPARTY_DIRECTORY}/lz4/lib/lz4frame.c + ${THIRDPARTY_DIRECTORY}/lz4/lib/xxhash.c) + target_include_directories(lz4_static PUBLIC ${THIRDPARTY_DIRECTORY}/lz4/lib) + + file(GLOB ZSTD_SOURCES + ${THIRDPARTY_DIRECTORY}/zstd/lib/common/*.c + ${THIRDPARTY_DIRECTORY}/zstd/lib/compress/*.c + ${THIRDPARTY_DIRECTORY}/zstd/lib/decompress/*.c) + add_library(zstd_static STATIC ${ZSTD_SOURCES}) + target_include_directories(zstd_static PUBLIC ${THIRDPARTY_DIRECTORY}/zstd/lib) + target_compile_definitions(zstd_static PRIVATE ZSTD_DISABLE_ASM) + + add_library(bz2_static STATIC + ${THIRDPARTY_DIRECTORY}/bzip2/blocksort.c + ${THIRDPARTY_DIRECTORY}/bzip2/huffman.c + ${THIRDPARTY_DIRECTORY}/bzip2/crctable.c + ${THIRDPARTY_DIRECTORY}/bzip2/randtable.c + ${THIRDPARTY_DIRECTORY}/bzip2/compress.c + ${THIRDPARTY_DIRECTORY}/bzip2/decompress.c + ${THIRDPARTY_DIRECTORY}/bzip2/bzlib.c) + target_include_directories(bz2_static PUBLIC ${THIRDPARTY_DIRECTORY}/bzip2) + # bzlib.h includes windows.h: keep its min/max macros out of the C++ that includes it. + target_compile_definitions(bz2_static PUBLIC NOMINMAX WIN32_LEAN_AND_MEAN PRIVATE _CRT_SECURE_NO_WARNINGS) +endif() + # mcap - support for ROS 2 bag export add_subdirectory(${THIRDPARTY_DIRECTORY}/mcap) -# rosbags/Ros1Bag reads bz2 chunks through libbz2. Like mcap's LZ4/ZSTD, this is -# skipped on Windows: no package manager provides it there, so Ros1Bag.cpp compiles out -# all chunk compression on MCAP_COMPRESSION_NO_LZ4 and reads uncompressed bags only. +# rosbags/Ros1Bag reads bz2 and lz4 chunks (lz4 comes with the mcap target). add_library(ros1bag_compression INTERFACE) -if(NOT WIN32) +if(WIN32) + target_link_libraries(ros1bag_compression INTERFACE bz2_static) +else() find_package(BZip2 REQUIRED) target_link_libraries(ros1bag_compression INTERFACE BZip2::BZip2) endif() diff --git a/rosbags/Ros1Bag.cpp b/rosbags/Ros1Bag.cpp index 005fe05e..24270b95 100644 --- a/rosbags/Ros1Bag.cpp +++ b/rosbags/Ros1Bag.cpp @@ -1,9 +1,7 @@ #include "Ros1Bag.h" -#if !defined(MCAP_COMPRESSION_NO_LZ4) // same switch as the mcap target: no compression libraries on Windows #include #include -#endif #include #include @@ -261,7 +259,6 @@ bool decompress(const std::string& compression, const std::vector& in, out = in; return true; } -#if !defined(MCAP_COMPRESSION_NO_LZ4) if(compression == "bz2") { unsigned int dst = static_cast(out_size); @@ -306,7 +303,6 @@ bool decompress(const std::string& compression, const std::vector& in, } return true; } -#endif error = "unsupported chunk compression '" + compression + "'"; return false; } diff --git a/rosbags/Ros1Bag.h b/rosbags/Ros1Bag.h index c8ece478..9b5d4356 100644 --- a/rosbags/Ros1Bag.h +++ b/rosbags/Ros1Bag.h @@ -4,7 +4,6 @@ // ROS1 serialization of sensor_msgs/PointCloud2 and sensor_msgs/Imu. // // Reader: chunk compression none, bz2 and lz4 (roslz4 writes LZ4 frames). -// On Windows only uncompressed chunks are read (MCAP_COMPRESSION_NO_LZ4). // Writer: uncompressed chunks with per-chunk index records and a full index // section, so `rosbag info`, `rosbag play` and the Python rosbags package all // read the result. diff --git a/rosbags/tests/test_mcap_reader.cpp b/rosbags/tests/test_mcap_reader.cpp index c43f1cd3..1d05231e 100644 --- a/rosbags/tests/test_mcap_reader.cpp +++ b/rosbags/tests/test_mcap_reader.cpp @@ -15,12 +15,15 @@ #include "McapWriter.h" #include +#include +#include #include #include #include #include #include +#include #include #include #include @@ -898,3 +901,121 @@ TEST_CASE("decodePc2: an absolute per-point timestamp ignores the header stamp e REQUIRE(points.size() == 1); CHECK(points[0].timestamp == kPointTime); } + +namespace +{ + +// Copies every message of `in` into `out` with chunks of `compression`, small enough to give several chunks. +void recompressMcap(const fs::path& in, const fs::path& out, mcap::Compression compression) +{ + mcap::McapReader reader; + REQUIRE(reader.open(in.string()).ok()); + mcap::McapWriter writer; + mcap::McapWriterOptions options("ros2"); + options.compression = compression; + options.chunkSize = 16 * 1024; + REQUIRE(writer.open(out.string(), options).ok()); + + std::map channels; + const auto onProblem = [](const mcap::Status& status) + { + FAIL(status.message); + }; + for (const auto& view : reader.readMessages(onProblem)) + { + auto it = channels.find(view.channel->id); + if (it == channels.end()) + { + mcap::Schema schema(view.schema->name, view.schema->encoding, view.schema->data); + writer.addSchema(schema); + mcap::Channel channel(view.channel->topic, view.channel->messageEncoding, schema.id, view.channel->metadata); + writer.addChannel(channel); + it = channels.emplace(view.channel->id, channel.id).first; + } + mcap::Message message = view.message; + message.channelId = it->second; + REQUIRE(writer.write(message).ok()); + } + writer.close(); + reader.close(); +} + +std::vector chunkCompressions(const fs::path& path) +{ + mcap::McapReader reader; + REQUIRE(reader.open(path.string()).ok()); + REQUIRE(reader.readSummary(mcap::ReadSummaryMethod::NoFallbackScan).ok()); + std::vector compressions; + for (const auto& index : reader.chunkIndexes()) + compressions.push_back(index.compression); + reader.close(); + return compressions; +} + +struct McapContent +{ + std::vector points; + std::vector imu_timestamps; +}; + +McapContent readMcapContent(const fs::path& path) +{ + McapContent content; + rosbags::McapFileReader reader(path); + REQUIRE_MESSAGE(reader.isOpen(), reader.error()); + rosbags::McapFileReader::Callbacks callbacks; + callbacks.onPointCloud = [&](uint64_t, std::vector&& cloud) + { + content.points.insert(content.points.end(), cloud.begin(), cloud.end()); + }; + callbacks.onImu = [&](const rosbags::McapImuSample& s) + { + content.imu_timestamps.push_back(s.timestamp); + }; + REQUIRE_MESSAGE(reader.read(callbacks), reader.error()); + return content; +} + +} // namespace + +TEST_CASE("McapFileReader: LZ4 and Zstd compressed chunks read the same as uncompressed ones") +{ + const auto plain = tempPath("hdmapping_reader_plain.mcap"); + const double t0 = 3000.0; + { + rosbags::McapFileWriter writer(plain); + REQUIRE(writer.isOpen()); + for (int i = 0; i < 5; ++i) + writer.writePointCloud(static_cast((t0 + i) * 1e9), makeReaderPoints(500, t0 + i)); + writer.writeImu(makeImuSamples(1000, t0)); + } + const McapContent expected = readMcapContent(plain); + REQUIRE(expected.points.size() == 5 * 500); + REQUIRE(expected.imu_timestamps.size() == 1000); + + for (const auto& [compression, name] : + { std::pair{ mcap::Compression::Lz4, std::string("lz4") }, std::pair{ mcap::Compression::Zstd, std::string("zstd") } }) + { + CAPTURE(name); + const auto packed = tempPath(("hdmapping_reader_" + name + ".mcap").c_str()); + recompressMcap(plain, packed, compression); + + const auto compressions = chunkCompressions(packed); + REQUIRE(compressions.size() > 1); + for (const auto& c : compressions) + CHECK(c == name); + + const McapContent got = readMcapContent(packed); + REQUIRE(got.points.size() == expected.points.size()); + for (size_t i = 0; i < got.points.size(); ++i) + { + CHECK(got.points[i].x == expected.points[i].x); + CHECK(got.points[i].y == expected.points[i].y); + CHECK(got.points[i].z == expected.points[i].z); + CHECK(got.points[i].timestamp == expected.points[i].timestamp); + } + CHECK(got.imu_timestamps == expected.imu_timestamps); + fs::remove(packed); + } + fs::remove(plain); +} From 84993682c6d4a9f57511d52d220a4cae7c7168a6 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Thu, 26 Nov 2026 18:30:02 +0100 Subject: [PATCH 05/21] Recording sources: register kinds in a factory, BagSource class in header The apps no longer pick an input type with if/else. Each RecordingSource kind provides static name/accepts/open (and optionally priority, configure, fileFilter) and registers itself with HDMAPPING_REGISTER_RECORDING_SOURCE; RecordingSourceFactory::find(paths) chooses the kind and the GUIs open whatever it returns. - BagSource is declared in bag_source.h; bag_source.cpp defines it and instantiates it for the ROS1 bag and MCAP readers. Its static acceptDroppedFile is specialized per reader (.bag / .mcap, files or folders searched recursively). is_bag_file is internal now. - BagSourceConfigUi implements RecordingSourceConfigUi. - recording_sources.cmake lists the source files shared by the apps. - raw_cloud_loader moves back to lidar_odometry_step_1: it is step 1's chunk cache, not a recording source. Co-Authored-By: Claude Opus 5.5 --- apps/lidar_odometry_step_1/CMakeLists.txt | 18 +- .../lidar_odometry_gui.cpp | 257 +++++++------- .../raw_cloud_loader.cpp | 0 .../lidar_odometry_step_1}/raw_cloud_loader.h | 0 apps/mandeye_raw_data_viewer/CMakeLists.txt | 11 +- .../mandeye_raw_data_viewer.cpp | 138 ++++---- core/include/Core/pfd_wrapper.hpp | 1 - pybind/CMakeLists.txt | 3 +- recording_sources/bag_source.cpp | 324 +++++++++++------- recording_sources/bag_source.h | 54 ++- recording_sources/bag_source_ui.cpp | 10 + recording_sources/bag_source_ui.h | 8 +- recording_sources/laz_csv_source.cpp | 63 ++++ recording_sources/laz_csv_source.h | 12 +- .../recording_source_factory.cpp | 81 +++++ recording_sources/recording_source_factory.h | 119 +++++++ recording_sources/recording_sources.cmake | 23 ++ 17 files changed, 758 insertions(+), 364 deletions(-) rename {recording_sources => apps/lidar_odometry_step_1}/raw_cloud_loader.cpp (100%) rename {recording_sources => apps/lidar_odometry_step_1}/raw_cloud_loader.h (100%) create mode 100644 recording_sources/recording_source_factory.cpp create mode 100644 recording_sources/recording_source_factory.h create mode 100644 recording_sources/recording_sources.cmake diff --git a/apps/lidar_odometry_step_1/CMakeLists.txt b/apps/lidar_odometry_step_1/CMakeLists.txt index f659c238..f6eb766b 100644 --- a/apps/lidar_odometry_step_1/CMakeLists.txt +++ b/apps/lidar_odometry_step_1/CMakeLists.txt @@ -16,6 +16,8 @@ function(target_apply_hdmapping_profiler TARGET) endif() endfunction() +include(${REPOSITORY_DIRECTORY}/recording_sources/recording_sources.cmake) + # Source files set(SOURCES lidar_odometry_utils.h lidar_odometry_utils.cpp @@ -23,9 +25,8 @@ set(SOURCES lidar_odometry.cpp lidar_odometry.h points_global_spill.h points_global_spill.cpp output_folders.h output_folders.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.h ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/raw_cloud_loader.h ${REPOSITORY_DIRECTORY}/recording_sources/raw_cloud_loader.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/recording_source.h + ${RECORDING_SOURCE_CORE_FILES} + raw_cloud_loader.h raw_cloud_loader.cpp toml_io.h toml_io.cpp ) @@ -34,18 +35,9 @@ if(WIN32) list(APPEND SOURCES "resource.rc") endif() -# ROS1 bag / MCAP recordings (bag_source): the rosbags readers. McapWriter.cpp holds the single MCAP_IMPLEMENTATION -# that McapReader.cpp relies on. -set(BAG_SOURCES - ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.h ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/bag_source_ui.h ${REPOSITORY_DIRECTORY}/recording_sources/bag_source_ui.cpp - ${REPOSITORY_DIRECTORY}/rosbags/McapReader.cpp - ${REPOSITORY_DIRECTORY}/rosbags/McapWriter.cpp - ${REPOSITORY_DIRECTORY}/rosbags/Ros1Bag.cpp -) add_executable( - lidar_odometry_step_1 lidar_odometry_gui.cpp ${SOURCES} ${BAG_SOURCES} + lidar_odometry_step_1 lidar_odometry_gui.cpp ${SOURCES} ${RECORDING_SOURCE_FILES} ) target_compile_definitions(lidar_odometry_step_1 PRIVATE WITH_GUI=1) diff --git a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp index 6381f42c..a6020857 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp @@ -15,10 +15,9 @@ #undef ShowCursor #endif -#include "bag_source.h" -#include "bag_source_ui.h" #include "lidar_odometry.h" #include "lidar_odometry_utils.h" +#include "recording_source_factory.h" #include "render_cache.h" #include "trajectory_follow.h" @@ -207,9 +206,22 @@ bool pipelinePending = false; bool pendingCompute = true, pendingSave = true; std::string pendingFolder; void startPipeline(const std::string& folder, bool compute, bool save); -std::shared_ptr pending_recording; //!< set with startPipeline; step1() loads it instead of the folder -std::unique_ptr bag_config_ui; //!< the open ROS bag / MCAP window, if any -std::string bag_open_error; +void openData(const std::string& folder = "", bool compute = true, bool save = true); +// What the next startPipeline() loads: a recording an options window already opened, or paths the kind opens in step1() +std::shared_ptr pending_recording; +std::shared_ptr pending_kind; +std::vector pending_paths; +std::unique_ptr source_config_ui; //!< the open options window of a recording kind, if any +std::string source_open_error; +bool source_config_compute = true, source_config_save = true; //!< startPipeline arguments once the window opens the recording + +//! Folder a recording given as paths is named after: the folder itself, or the folder of the first file. +static fs::path recording_folder(const std::vector& paths) +{ + if (paths.empty()) + return {}; + return fs::is_directory(paths.front()) ? paths.front() : paths.front().parent_path(); +} static void resources_gui() { @@ -701,57 +713,50 @@ Eigen::Vector3d GLWidgetGetOGLPos(int x, int y, const ObservationPicking& observ void step1(const std::string& input_folder_name, const std::atomic& loPause) { trajectory_points_dirty = true; - std::vector input_file_names; - // a recording prepared in the ROS bag / MCAP window is loaded instead of the folder's files - const std::shared_ptr recording = std::exchange(pending_recording, nullptr); + // a recording opened by an options window, or the paths its kind opens here + std::shared_ptr recording = std::exchange(pending_recording, nullptr); + const auto kind = std::exchange(pending_kind, nullptr); + const auto paths = std::exchange(pending_paths, {}); - std::cout << "Selected folder: '" << input_folder_name << std::endl; + std::cout << "Selected recording: '" << input_folder_name << "'" << std::endl; + check_output_folders(input_folder_name, params.session_cache_choice); // before anything is loaded - if (recording || fs::exists(input_folder_name)) + std::string error; + if (!recording && kind) { - check_output_folders(input_folder_name, params.session_cache_choice); // before anything is loaded - bool loaded = false; - if (recording) - { - InputFileSpans spans; - loaded = load_data(recording, params, pointsPerFile, imu_data, spans); - if (loaded) - working_directory = recording->workingDirectory().string(); - } - else - { - RunReport::Scope discovery(params.run_report.get(), RunReport::Stage::Loading); - for (const auto& entry : fs::directory_iterator(input_folder_name)) - if (entry.is_regular_file()) - input_file_names.push_back(entry.path().string()); - - discovery.finish(); - loaded = load_data(input_file_names, params, pointsPerFile, imu_data, full_debug_messages); - if (loaded) - working_directory = fs::path(input_file_names[0]).parent_path().string(); - } + RunReport::Scope discovery(params.run_report.get(), RunReport::Stage::Loading); + std::cout << "Opening as " << kind->name() << std::endl; + recording = kind->open(paths, error); + discovery.finish(); + } + + bool loaded = false; + if (recording) + { + InputFileSpans spans; + loaded = load_data(recording, params, pointsPerFile, imu_data, spans); if (loaded) + working_directory = recording->workingDirectory().string(); + } + if (loaded) + { + calculate_trajectory(trajectory, imu_data, params, full_debug_messages); + if (compute_step_1(pointsPerFile, params, trajectory, worker_data, loPause)) { - calculate_trajectory(trajectory, imu_data, params, full_debug_messages); - if (compute_step_1(pointsPerFile, params, trajectory, worker_data, loPause)) - { - release_raw_clouds(pointsPerFile, params); // nothing after step 1 reads them - step_1_done = true; - publish_trajectory_preview(worker_data, true); - } - else - std::cerr << "Lidar odometry step 1 failed (see the messages above)" << std::endl; + release_raw_clouds(pointsPerFile, params); // nothing after step 1 reads them + step_1_done = true; + publish_trajectory_preview(worker_data, true); } else - { - std::string message_info = "Problem with loading data from folder '" + input_folder_name + - "' (Please check if folder exists). Program will close once You click OK!!!"; - std::cout << message_info << std::endl; - throw std::runtime_error("Input data loading failed: " + input_folder_name); - } + std::cerr << "Lidar odometry step 1 failed (see the messages above)" << std::endl; } else - throw std::runtime_error("Data folder not found: " + input_folder_name); + { + std::string message_info = "Problem with loading data from '" + input_folder_name + "'" + (error.empty() ? "" : ": " + error) + + ". Program will close once You click OK!!!"; + std::cout << message_info << std::endl; + throw std::runtime_error("Input data loading failed: " + input_folder_name + (error.empty() ? "" : ": " + error)); + } } void step2(const std::atomic& loPause) @@ -1260,9 +1265,7 @@ void settings_gui() { if (ImGui::Button("Load data")) { - const auto folder = mandeye::fd::SelectFolder("Select Mandeye data folder"); - if (!folder.empty()) - startPipeline(folder, false, false); + openData("", false, false); } if (ImGui::IsItemHovered()) ImGui::SetTooltip( @@ -1916,13 +1919,47 @@ void progress_window() ImGui::End(); } -//! folder: Mandeye data folder to process; empty asks for one with a folder dialog. +//! Hands paths to the recording kind that reads them: its options window when it has one, otherwise the pipeline, which +//! opens them in the worker. +void openRecording(const std::vector& paths, bool compute = true, bool save = true) +{ + if (paths.empty()) + return; + const auto kind = RecordingSourceFactory::find(paths); + if (!kind) + { + std::lock_guard lock(completionMutex); + completionMessage = + "No recording kind reads '" + paths.front().string() + "'" + (paths.size() > 1 ? " and the other dropped paths" : ""); + return; + } + if (auto ui = kind->configure(paths)) + { + source_open_error.clear(); + source_config_ui = std::move(ui); + source_config_compute = compute; + source_config_save = save; + return; + } + pending_kind = kind; + pending_paths = paths; + startPipeline(recording_folder(paths).string(), compute, save); +} + +//! folder: recording folder to process; empty asks for one with a folder dialog. //! Loading and processing share one owned worker; drawing is suspended only during initial preparation. -void openData(const std::string& folder = "") +void openData(const std::string& folder, bool compute, bool save) { const std::string input_folder_name = folder.empty() ? mandeye::fd::SelectFolder("Select Mandeye data folder") : folder; if (!input_folder_name.empty()) - startPipeline(input_folder_name, true, true); + openRecording({ fs::path(input_folder_name) }, compute, save); +} + +//! Asks for recording files of any registered kind and opens them. +void openRecordingFiles() +{ + const auto files = mandeye::fd::OpenFileDialog("Select recording", RecordingSourceFactory::fileFilters(), true); + openRecording(std::vector(files.begin(), files.end())); } void startPipeline(const std::string& folder, bool compute, bool save) @@ -1935,41 +1972,26 @@ void startPipeline(const std::string& folder, bool compute, bool save) pipelinePending = true; } -//! Opens the window that configures a ROS1 bag or MCAP file; asks for the file when none is given. -void openBag(const std::string& file = "") -{ - std::string path = file; - if (path.empty()) - { - const auto files = mandeye::fd::OpenFileDialog("Select ROS1 bag or MCAP file", mandeye::fd::Bag_filter, false); - if (files.empty()) - return; - path = files.front(); - } - bag_open_error.clear(); - bag_config_ui = std::make_unique(path); -} - -//! Window with the topic choice of the selected bag; Open loads it and starts processing. -static void bag_source_window() +//! Options window of the recording kind being opened; its Open button starts the pipeline. +static void source_config_window() { bool open = true; - ImGui::Begin("Open ROS bag / MCAP", &open, ImGuiWindowFlags_AlwaysAutoResize); - if (bag_config_ui->draw()) + ImGui::Begin(source_config_ui->title().c_str(), &open, ImGuiWindowFlags_AlwaysAutoResize); + if (source_config_ui->draw()) { - auto source = open_bag_source(bag_config_ui->config(), bag_open_error); + auto source = source_config_ui->open(source_open_error); if (source) { pending_recording = std::move(source); - startPipeline(pending_recording->workingDirectory().string(), true, true); + startPipeline(pending_recording->workingDirectory().string(), source_config_compute, source_config_save); open = false; } } - if (!bag_open_error.empty()) - ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", bag_open_error.c_str()); + if (!source_open_error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", source_open_error.c_str()); ImGui::End(); if (!open) - bag_config_ui.reset(); + source_config_ui.reset(); } static void launchPipeline(const std::string& folder, bool compute, bool save) @@ -2091,50 +2113,30 @@ bool step1( std::vector& worker_data, const std::atomic& loPause) { - // a ROS1 bag or MCAP file is read with its only lidar and IMU topics (the GUI lets the user choose) - const bool bag = is_bag_file(folder) && fs::is_regular_file(folder); - const fs::path data_folder = bag ? fs::path(folder).parent_path() : fs::path(folder); - params.run_report = std::make_shared(data_folder, params.points_global_spill_directory, "cli"); - check_output_folders(data_folder, params.session_cache_choice); // before anything is loaded - std::vector input_file_names; + // any registered recording kind, opened with its default options (the GUI lets the user choose them) + const std::vector paths{ fs::path(folder) }; + params.run_report = std::make_shared(recording_folder(paths), params.points_global_spill_directory, "cli"); + check_output_folders(recording_folder(paths), params.session_cache_choice); // before anything is loaded RunReport::Scope discovery(params.run_report.get(), RunReport::Stage::Loading); - bool loaded = false; - if (bag) + const auto kind = RecordingSourceFactory::find(paths); + if (!kind) { - BagSourceConfig config; - config.file = folder; - std::string error; - const auto source = open_bag_source(config, error); - discovery.finish(); - if (!source) - { - std::cerr << "Cannot read '" << folder << "': " << error << std::endl; - return false; - } - InputFileSpans spans; - loaded = load_data(source, params, pointsPerFile, imu_data, spans); - if (loaded) - working_directory = source->workingDirectory().string(); + std::cerr << "No recording kind reads '" << folder << "'" << std::endl; + return false; } - else + std::string error; + const auto source = kind->open(paths, error); + discovery.finish(); + if (!source) { - for (const auto& entry : fs::directory_iterator(folder)) - { - if (!entry.is_directory()) - { - std::cout << entry.path() << std::endl; - input_file_names.push_back(entry.path().string()); - } - } - - discovery.finish(); - loaded = load_data(input_file_names, params, pointsPerFile, imu_data, full_debug_messages); - if (loaded) - working_directory = fs::path(input_file_names[0]).parent_path().string(); + std::cerr << "Cannot read '" << folder << "' as " << kind->name() << ": " << error << std::endl; + return false; } - if (loaded) + InputFileSpans spans; + if (load_data(source, params, pointsPerFile, imu_data, spans)) { + working_directory = source->workingDirectory().string(); calculate_trajectory(trajectory, imu_data, params, full_debug_messages); if (!compute_step_1(pointsPerFile, params, trajectory, worker_data, loPause)) return false; @@ -2550,18 +2552,10 @@ void display() view_kbd_shortcuts(); - // Drag and drop: a Mandeye data folder, or any file in one, is processed like "Load & process scanning"; - // a ROS1 bag or MCAP file opens its window first. + // Drag and drop: the dropped files and folders go to the recording kind that reads them (see openRecording) const auto dropped = takeDroppedFiles(); - if (!dropped.empty() && !loRunning && !pipelinePending && is_bag_file(dropped[0]) && fs::is_regular_file(dropped[0])) - openBag(dropped[0]); - else if (!dropped.empty() && !loRunning && !pipelinePending) - { - fs::path folder(dropped[0]); - if (!fs::is_directory(folder)) - folder = folder.parent_path(); - openData(folder.string()); - } + if (!dropped.empty() && !loRunning && !pipelinePending) + openRecording(std::vector(dropped.begin(), dropped.end())); if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_O, false) && !loRunning && !pipelinePending) { @@ -2841,10 +2835,11 @@ void display() cache_location_menu(); ImGui::SameLine(); - if (ImGui::Button("Load & process ROS bag / MCAP")) - openBag(); + if (ImGui::Button("Load & process recording files")) + openRecordingFiles(); if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Select a ROS1 bag (*.bag) or an MCAP file (*.mcap), choose its topics and start processing"); + ImGui::SetTooltip( + "Select the files of a recording (e.g. a ROS1 bag or an MCAP file), set its options and start processing"); ImGui::SameLine(); ImGui::Dummy(ImVec2(20, 0)); @@ -3012,8 +3007,8 @@ void display() settings_gui(); } - if (!loRunning && bag_config_ui) - bag_source_window(); + if (!loRunning && source_config_ui) + source_config_window(); if (loRunning) progress_window(); @@ -3118,7 +3113,7 @@ int main(int argc, char* argv[]) if (argc == 2) // running from command line { auto path = fs::path(argv[1]); - if (is_directory(path) || (is_bag_file(path) && fs::is_regular_file(path))) + if (RecordingSourceFactory::find({ path })) { // results and failure reports go next to a bag file, or into the data folder const fs::path input_dir = is_directory(path) ? path : path.parent_path(); diff --git a/recording_sources/raw_cloud_loader.cpp b/apps/lidar_odometry_step_1/raw_cloud_loader.cpp similarity index 100% rename from recording_sources/raw_cloud_loader.cpp rename to apps/lidar_odometry_step_1/raw_cloud_loader.cpp diff --git a/recording_sources/raw_cloud_loader.h b/apps/lidar_odometry_step_1/raw_cloud_loader.h similarity index 100% rename from recording_sources/raw_cloud_loader.h rename to apps/lidar_odometry_step_1/raw_cloud_loader.h diff --git a/apps/mandeye_raw_data_viewer/CMakeLists.txt b/apps/mandeye_raw_data_viewer/CMakeLists.txt index fd0ceaca..be7c0eb8 100644 --- a/apps/mandeye_raw_data_viewer/CMakeLists.txt +++ b/apps/mandeye_raw_data_viewer/CMakeLists.txt @@ -2,6 +2,8 @@ cmake_minimum_required(VERSION 4.0.0) project(mandeye_raw_data_viewer) +include(${REPOSITORY_DIRECTORY}/recording_sources/recording_sources.cmake) + # Source files set(SOURCES mandeye_raw_data_viewer.cpp @@ -11,13 +13,8 @@ set(SOURCES ../lidar_odometry_step_1/lidar_odometry_utils_optimizers.cpp ../lidar_odometry_step_1/points_global_spill.cpp ../lidar_odometry_step_1/output_folders.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/raw_cloud_loader.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/bag_source_ui.cpp - ${REPOSITORY_DIRECTORY}/rosbags/McapReader.cpp - ${REPOSITORY_DIRECTORY}/rosbags/McapWriter.cpp - ${REPOSITORY_DIRECTORY}/rosbags/Ros1Bag.cpp + ${RECORDING_SOURCE_FILES} + ../lidar_odometry_step_1/raw_cloud_loader.cpp ) # Windows: add resource file diff --git a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp index a2017eb8..7cf84ff0 100644 --- a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp +++ b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp @@ -27,8 +27,7 @@ #include "../lidar_odometry_step_1/lidar_odometry.h" #include "../lidar_odometry_step_1/lidar_odometry_utils.h" -#include "bag_source.h" -#include "bag_source_ui.h" +#include "recording_source_factory.h" #include #include #include @@ -1100,7 +1099,7 @@ void loadFiles(std::vector input_file_names, const std::shared_ptr< std::string ext = fs::path(fileName).extension().string(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - if (ext == ".laz" || ext == ".las") + if ((ext == ".laz" || ext == ".las") && !source) laz_files.push_back(fileName); else if (ext == ".jpg" || ext == ".jpeg") { @@ -1290,87 +1289,86 @@ void collectFolderFiles(const std::string& input_folder_name, std::vector input_file_names; - input_folder_name = mandeye::fd::SelectFolder("Select Mandeye data folder"); - - spdlog::info("Selected folder: '{}'", input_folder_name); - - collectFolderFiles(input_folder_name, input_file_names); - - loadFiles(input_file_names); -} - -void openBag(const std::string& file = ""); +std::unique_ptr source_config_ui; //!< the open options window of a recording kind, if any +std::vector source_config_files; //!< the picked files and folder contents, for photos, once the window opens +std::string source_open_error; -//! Drag and drop: dropped folders load like "Open folder", dropped files like "Open files", -//! a single dropped ROS1 bag or MCAP file opens its window. -void openDropped(const std::vector& paths) +//! Opens paths (files and folders) through the recording kind that reads them, in its options window when it has one. +//! Photos among the paths, or in the folders and their CAMERA_0, are shown with the recording. +void openRecording(const std::vector& paths) { - if (paths.size() == 1 && is_bag_file(paths.front()) && fs::is_regular_file(paths.front())) + if (paths.empty()) + return; + const std::vector recording_paths(paths.begin(), paths.end()); + const auto kind = RecordingSourceFactory::find(recording_paths); + if (!kind) { - openBag(paths.front()); + spdlog::error("No recording kind reads '{}'", paths.front()); return; } - std::vector input_file_names; + spdlog::info("Opening '{}' as {}", paths.front(), kind->name()); + + // a single file stands for its whole folder, as the kinds open it + std::vector files; + if (paths.size() == 1 && fs::is_regular_file(paths.front())) + collectFolderFiles(fs::path(paths.front()).parent_path().string(), files); for (const auto& path : paths) { if (fs::is_directory(path)) - collectFolderFiles(path, input_file_names); - else - input_file_names.push_back(path); + collectFolderFiles(path, files); + else if (paths.size() > 1) + files.push_back(path); } - if (!input_file_names.empty()) - loadFiles(input_file_names); + if (auto ui = kind->configure(recording_paths)) + { + source_open_error.clear(); + source_config_ui = std::move(ui); + source_config_files = std::move(files); + return; + } + std::string error; + const auto source = kind->open(recording_paths, error); + if (!source) + { + spdlog::error("Cannot read '{}' as {}: {}", paths.front(), kind->name(), error); + return; + } + loadFiles(files, source); } -void openFiles() +void openFolder() { - std::vector input_file_names = mandeye::fd::OpenFileDialog("Load all files", mandeye::fd::All_Filter, true); - - loadFiles(input_file_names); + const std::string input_folder_name = mandeye::fd::SelectFolder("Select Mandeye data folder"); + spdlog::info("Selected folder: '{}'", input_folder_name); + if (!input_folder_name.empty()) + openRecording({ input_folder_name }); } -std::unique_ptr bag_config_ui; //!< the open ROS bag / MCAP window, if any -std::string bag_open_error; - -//! Opens the window that configures a ROS1 bag or MCAP file; asks for the file when none is given. -void openBag(const std::string& file) +void openFiles() { - std::string path = file; - if (path.empty()) - { - const auto files = mandeye::fd::OpenFileDialog("Select ROS1 bag or MCAP file", mandeye::fd::Bag_filter, false); - if (files.empty()) - return; - path = files.front(); - } - bag_open_error.clear(); - bag_config_ui = std::make_unique(path); + openRecording(mandeye::fd::OpenFileDialog("Load all files", RecordingSourceFactory::fileFilters(), true)); } -//! Window with the topic choice of the selected bag; Open loads it. -void bag_source_window() +//! Options window of the recording kind being opened; Open loads the recording. +void source_config_window() { bool open = true; - ImGui::Begin("Open ROS bag / MCAP", &open, ImGuiWindowFlags_AlwaysAutoResize); - if (bag_config_ui->draw()) + ImGui::Begin(source_config_ui->title().c_str(), &open, ImGuiWindowFlags_AlwaysAutoResize); + if (source_config_ui->draw()) { - const auto source = open_bag_source(bag_config_ui->config(), bag_open_error); + const auto source = source_config_ui->open(source_open_error); if (source) { - loadFiles({}, source); + loadFiles(source_config_files, source); open = false; } } - if (!bag_open_error.empty()) - ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", bag_open_error.c_str()); + if (!source_open_error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", source_open_error.c_str()); ImGui::End(); if (!open) - bag_config_ui.reset(); + source_config_ui.reset(); } void imu_data_gui() @@ -2135,7 +2133,7 @@ void display() const auto dropped = takeDroppedFiles(); if (!dropped.empty()) - openDropped(dropped); + openRecording(dropped); if (all_data.size() > 0) { @@ -2179,12 +2177,7 @@ void display() if (ImGui::MenuItem("Open files")) openFiles(); if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Select files for analyze"); - if (ImGui::MenuItem("Open ROS bag / MCAP")) - openBag(); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip( - "Select a ROS1 bag (*.bag) or an MCAP file (*.mcap) and choose its topics, or drop the file on the window"); + ImGui::SetTooltip("Select the files of a recording (Mandeye LAZ/CSV, ROS1 bag, MCAP, ...), or drop them on the window"); ImGui::MenuItem("Skip first file", nullptr, &skip_first_file); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Drop the points of the first LAZ file on the next load, as step 1 does"); @@ -2359,8 +2352,8 @@ void display() if (is_settings_gui) settings_gui(); - if (bag_config_ui) - bag_source_window(); + if (source_config_ui) + source_config_window(); rlImGuiEnd(); } @@ -2407,19 +2400,8 @@ int main(int argc, char* argv[]) initGL(&argc, argv, winTitle, display, mouse); ImPlot::CreateContext(); - if (argc == 2) - { - std::vector input_file_names; - - if (fs::exists(argv[1])) - { - for (const auto& entry : fs::recursive_directory_iterator(argv[1])) - if (entry.is_regular_file()) - input_file_names.push_back(entry.path().string()); - - loadFiles(input_file_names); - } - } + if (argc == 2 && fs::exists(argv[1])) + openRecording({ argv[1] }); mainLoop(); diff --git a/core/include/Core/pfd_wrapper.hpp b/core/include/Core/pfd_wrapper.hpp index ae6c736f..6c7bae70 100644 --- a/core/include/Core/pfd_wrapper.hpp +++ b/core/include/Core/pfd_wrapper.hpp @@ -13,7 +13,6 @@ namespace mandeye::fd const std::vector LAS_LAZ_filter = { "LASzip file (*.laz)", "*.laz", "LAS file (*.las)", "*.las", "All files", "*" }; const std::vector LazFilter = { "LAS/LAZ files (*.laz)", "*.las *.laz" }; const std::vector E57_filter = { "E57 point cloud (*.e57)", "*.e57", "All files", "*" }; - const std::vector Bag_filter = { "ROS1 bag / MCAP (*.bag *.mcap)", "*.bag *.mcap", "All files", "*" }; const std::vector ImageFilter = { "Image files (*.bmp, *.jpg, *.jpeg, *.png)", "*.bmp *.jpg *.jpeg *.png", "All files", "*" }; diff --git a/pybind/CMakeLists.txt b/pybind/CMakeLists.txt index b44d3eb1..07893a4a 100644 --- a/pybind/CMakeLists.txt +++ b/pybind/CMakeLists.txt @@ -77,7 +77,8 @@ target_sources(lidar_odometry_py ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/points_global_spill.cpp ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/output_folders.cpp ${CMAKE_SOURCE_DIR}/recording_sources/laz_csv_source.cpp - ${CMAKE_SOURCE_DIR}/recording_sources/raw_cloud_loader.cpp + ${CMAKE_SOURCE_DIR}/recording_sources/recording_source_factory.cpp + ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/raw_cloud_loader.cpp ${CMAKE_SOURCE_DIR}/apps/lidar_odometry_step_1/toml_io.cpp ) diff --git a/recording_sources/bag_source.cpp b/recording_sources/bag_source.cpp index 5203ae76..a1ce3831 100644 --- a/recording_sources/bag_source.cpp +++ b/recording_sources/bag_source.cpp @@ -4,6 +4,7 @@ #include "Ros1Bag.h" #include "bag_source.h" +#include "bag_source_ui.h" #include #include @@ -35,6 +36,20 @@ namespace return lower_extension(file) == ".bag"; } + //! True for the files open_bag_source reads: .bag (ROS1) and .mcap. + bool is_bag_file(const fs::path& file) + { + const std::string ext = lower_extension(file); + return ext == ".bag" || ext == ".mcap"; + } + + //! True for exactly one regular file with this lower-case extension. + bool single_file_with_extension(const std::vector& paths, std::string_view extension) + { + std::error_code ec; + return paths.size() == 1 && fs::is_regular_file(paths.front(), ec) && lower_extension(paths.front()) == extension; + } + //! Message type without its package, as both readers compare it: "sensor_msgs/msg/Imu" -> "Imu". std::string_view type_name(std::string_view type) { @@ -81,140 +96,181 @@ namespace s.valid = !ec; return s; } +} // namespace - //! A ROS1 bag or MCAP file split into windows of message log time. Every read opens its own reader, so chunks can be - //! loaded from several threads at once. - template - class BagSource final : public RecordingSource +template +BagSource::BagSource(const BagSourceConfig& config, uint64_t start_ns, uint64_t end_ns) + : config_(config) + , start_ns_(start_ns) + , end_ns_(end_ns) +{ + const uint64_t length = end_ns_ - start_ns_; + chunk_ns_ = config_.chunk_seconds > 0.0 ? static_cast(config_.chunk_seconds * 1e9) : length; + chunk_ns_ = std::max(chunk_ns_, 1); + chunk_count_ = std::max(1, static_cast((length + chunk_ns_ - 1) / chunk_ns_)); +} + +template +fs::path BagSource::workingDirectory() const +{ + return config_.file.parent_path(); +} + +template +size_t BagSource::chunkCount() const +{ + return chunk_count_; +} + +template +std::string BagSource::chunkName(size_t i) const +{ + char index[16]; + std::snprintf(index, sizeof(index), "#%04zu", i); + return config_.file.string() + index; +} + +template +std::vector BagSource::loadPoints(size_t i, const PointFilter& filter) const +{ + std::vector points; + Reader reader(config_.file, reader_options(config_)); + if (!reader.isOpen()) { - public: - BagSource(const BagSourceConfig& config, const rosbags::LogTimeRange& span) - : config_(config) - , options_(reader_options(config)) - , imu_transform_(imu_transform(config)) - , span_(span) - { - const uint64_t length = span_.end_ns - span_.start_ns; - chunk_ns_ = config_.chunk_seconds > 0.0 ? static_cast(config_.chunk_seconds * 1e9) : length; - chunk_ns_ = std::max(chunk_ns_, 1); - chunk_count_ = std::max(1, static_cast((length + chunk_ns_ - 1) / chunk_ns_)); - } + std::cerr << "cannot open '" << config_.file.string() << "': " << reader.error() << "\n"; + return points; + } - fs::path workingDirectory() const override + size_t total = 0; + typename Reader::Callbacks callbacks; + callbacks.onPointCloud = [&](uint64_t, std::vector&& cloud) + { + total += cloud.size(); + for (const auto& p : cloud) { - return config_.file.parent_path(); + if (filter.omit_timestamp_zero && p.timestamp == 0.0) + continue; + const double r = std::sqrt(static_cast(p.x) * p.x + static_cast(p.y) * p.y); + if (r <= filter.xy_inner || r >= filter.xy_outer) + continue; + Point3Di q{}; + q.point = Eigen::Vector3d(p.x, p.y, p.z); + q.timestamp = p.timestamp; + q.intensity = p.intensity; + q.lidarid = 0; + points.push_back(q); } + }; + const auto [start_ns, end_ns] = window(i); + rosbags::LogTimeRange range; + range.start_ns = start_ns; + range.end_ns = end_ns; + if (!reader.read(callbacks, range)) + std::cerr << "reading '" << chunkName(i) << "' failed: " << reader.error() << "\n"; + if (!reader.lidarLayoutWarning().empty()) + std::cerr << "'" << config_.file.string() << "': " << reader.lidarLayoutWarning() << "\n"; - size_t chunkCount() const override + std::sort( + points.begin(), + points.end(), + [](const Point3Di& a, const Point3Di& b) { - return chunk_count_; - } + return a.timestamp < b.timestamp; + }); + std::cout << chunkName(i) << ": " << total << " - " << total - points.size() << " = " << points.size() << std::endl; + return points; +} - std::string chunkName(size_t i) const override - { - char index[16]; - std::snprintf(index, sizeof(index), "#%04zu", i); - return config_.file.string() + index; - } +template +ChunkStamp BagSource::stamp(size_t) const +{ + return file_stamp(config_.file); +} - std::vector loadPoints(size_t i, const PointFilter& filter) const override - { - std::vector points; - Reader reader(config_.file, options_); - if (!reader.isOpen()) - { - std::cerr << "cannot open '" << config_.file.string() << "': " << reader.error() << "\n"; - return points; - } +template +void BagSource::loadImu(Imu& imu_data, std::vector& imuSpans) const +{ + std::cout << "loading IMU data from '" << config_.file.string() << "' ..\n"; + Reader reader(config_.file, reader_options(config_)); + if (!reader.isOpen()) + { + std::cerr << "cannot open '" << config_.file.string() << "': " << reader.error() << "\n"; + return; + } + const rosbags::ImuTransform transform = imu_transform(config_); + const size_t first = imu_data.size(); + typename Reader::Callbacks callbacks; + callbacks.onImu = [&](rosbags::McapImuSample s) + { + rosbags::applyImuTransform(transform, s); + imu_data.emplace_back( + std::pair(s.timestamp, 0.0), Eigen::Vector3f(s.gyro_x, s.gyro_y, s.gyro_z), Eigen::Vector3f(s.acc_x, s.acc_y, s.acc_z)); + }; + if (!reader.read(callbacks)) + std::cerr << "reading IMU from '" << config_.file.string() << "' failed: " << reader.error() << "\n"; - size_t total = 0; - typename Reader::Callbacks callbacks; - callbacks.onPointCloud = [&](uint64_t, std::vector&& cloud) - { - total += cloud.size(); - for (const auto& p : cloud) - { - if (filter.omit_timestamp_zero && p.timestamp == 0.0) - continue; - const double r = std::sqrt(static_cast(p.x) * p.x + static_cast(p.y) * p.y); - if (r <= filter.xy_inner || r >= filter.xy_outer) - continue; - Point3Di q{}; - q.point = Eigen::Vector3d(p.x, p.y, p.z); - q.timestamp = p.timestamp; - q.intensity = p.intensity; - q.lidarid = 0; - points.push_back(q); - } - }; - if (!reader.read(callbacks, window(i))) - std::cerr << "reading '" << chunkName(i) << "' failed: " << reader.error() << "\n"; - if (!reader.lidarLayoutWarning().empty()) - std::cerr << "'" << config_.file.string() << "': " << reader.lidarLayoutWarning() << "\n"; - - std::sort( - points.begin(), - points.end(), - [](const Point3Di& a, const Point3Di& b) - { - return a.timestamp < b.timestamp; - }); - std::cout << chunkName(i) << ": " << total << " - " << total - points.size() << " = " << points.size() << std::endl; - return points; - } + InputFileSpan span{ config_.file.string() }; + for (size_t k = first; k < imu_data.size(); ++k) + { + const double t = std::get<0>(imu_data[k]).first; + span.first = span.count == 0 ? t : std::min(span.first, t); + span.last = span.count == 0 ? t : std::max(span.last, t); + span.count++; + } + imuSpans.push_back(span); +} - ChunkStamp stamp(size_t) const override - { - return file_stamp(config_.file); - } +template +std::pair BagSource::window(size_t i) const +{ + const uint64_t start = start_ns_ + i * chunk_ns_; + return { start, i + 1 == chunk_count_ ? end_ns_ : start + chunk_ns_ }; +} - void loadImu(Imu& imu_data, std::vector& imuSpans) const override - { - std::cout << "loading IMU data from '" << config_.file.string() << "' ..\n"; - Reader reader(config_.file, options_); - if (!reader.isOpen()) - { - std::cerr << "cannot open '" << config_.file.string() << "': " << reader.error() << "\n"; - return; - } - const size_t first = imu_data.size(); - typename Reader::Callbacks callbacks; - callbacks.onImu = [&](rosbags::McapImuSample s) - { - rosbags::applyImuTransform(imu_transform_, s); - imu_data.emplace_back( - std::pair(s.timestamp, 0.0), Eigen::Vector3f(s.gyro_x, s.gyro_y, s.gyro_z), Eigen::Vector3f(s.acc_x, s.acc_y, s.acc_z)); - }; - if (!reader.read(callbacks)) - std::cerr << "reading IMU from '" << config_.file.string() << "' failed: " << reader.error() << "\n"; - - InputFileSpan span{ config_.file.string() }; - for (size_t k = first; k < imu_data.size(); ++k) - { - const double t = std::get<0>(imu_data[k]).first; - span.first = span.count == 0 ? t : std::min(span.first, t); - span.last = span.count == 0 ? t : std::max(span.last, t); - span.count++; - } - imuSpans.push_back(span); - } +template<> +std::string BagSource::name() +{ + return "ROS1 bag"; +} - private: - rosbags::LogTimeRange window(size_t i) const - { - rosbags::LogTimeRange w; - w.start_ns = span_.start_ns + i * chunk_ns_; - w.end_ns = i + 1 == chunk_count_ ? span_.end_ns : w.start_ns + chunk_ns_; - return w; - } +template<> +std::string BagSource::name() +{ + return "MCAP"; +} - BagSourceConfig config_; - rosbags::McapReaderOptions options_; - rosbags::ImuTransform imu_transform_; - rosbags::LogTimeRange span_; - uint64_t chunk_ns_ = 1; - size_t chunk_count_ = 1; - }; +template<> +bool BagSource::accepts(const std::vector& paths) +{ + return single_file_with_extension(paths, ".bag"); +} + +template<> +bool BagSource::accepts(const std::vector& paths) +{ + return single_file_with_extension(paths, ".mcap"); +} + +template<> +std::vector BagSource::fileFilter() +{ + return { "ROS1 bag (*.bag)", "*.bag" }; +} + +template<> +std::vector BagSource::fileFilter() +{ + return { "MCAP (*.mcap)", "*.mcap" }; +} + +template +int BagSource::priority() +{ + return 10; +} + +namespace +{ template std::shared_ptr open_with(const BagSourceConfig& config, std::string& error) @@ -242,7 +298,7 @@ namespace "ROS1 bag, `mcap recover` for an MCAP file)"; return nullptr; } - return std::make_shared>(config, *span); + return std::make_shared>(config, span->start_ns, span->end_ns); } template @@ -267,12 +323,6 @@ namespace } } // namespace -bool is_bag_file(const fs::path& file) -{ - const std::string ext = lower_extension(file); - return ext == ".bag" || ext == ".mcap"; -} - std::vector list_bag_channels(const fs::path& file, std::string& error) { error.clear(); @@ -295,3 +345,23 @@ std::shared_ptr open_bag_source(const BagSourceConfig& config, return is_ros1_bag(config.file) ? open_with(config, error) : open_with(config, error); } + +template +std::shared_ptr BagSource::open(const std::vector& paths, std::string& error) +{ + BagSourceConfig config; + config.file = paths.empty() ? fs::path{} : paths.front(); + return open_bag_source(config, error); +} + +template +std::unique_ptr BagSource::configure(const std::vector& paths) +{ + return std::make_unique(paths.empty() ? fs::path{} : paths.front()); +} + +template class BagSource; +template class BagSource; + +HDMAPPING_REGISTER_RECORDING_SOURCE(Ros1BagSource) +HDMAPPING_REGISTER_RECORDING_SOURCE(McapSource) diff --git a/recording_sources/bag_source.h b/recording_sources/bag_source.h index 9c9bf821..66bfa619 100644 --- a/recording_sources/bag_source.h +++ b/recording_sources/bag_source.h @@ -1,12 +1,13 @@ #pragma once -#include "recording_source.h" +#include "recording_source_factory.h" #include #include #include #include #include +#include #include // No rosbags header here: they re-enable std::byte on MSVC and must come before any standard header (see @@ -48,8 +49,55 @@ struct BagChannel Kind kind = Kind::Other; }; -//! True for the files open_bag_source reads: .bag (ROS1) and .mcap. -bool is_bag_file(const std::filesystem::path& file); +namespace rosbags +{ + class Ros1BagFileReader; + class McapFileReader; +} // namespace rosbags + +//! A ROS1 bag or MCAP file split into windows of message log time. Every read opens its own Reader, so chunks can be +//! loaded from several threads at once. Defined and instantiated in bag_source.cpp for Ros1BagSource and McapSource, +//! which register themselves as recording kinds (see RecordingSourceFactoryFor). +template +class BagSource final : public RecordingSource +{ +public: + //! The recording [start_ns, end_ns) of message log time in config.file, split into config.chunk_seconds windows. + BagSource(const BagSourceConfig& config, uint64_t start_ns, uint64_t end_ns); + + std::filesystem::path workingDirectory() const override; + size_t chunkCount() const override; + std::string chunkName(size_t i) const override; + std::vector loadPoints(size_t i, const PointFilter& filter) const override; + ChunkStamp stamp(size_t i) const override; + void loadImu(Imu& imu_data, std::vector& imuSpans) const override; + + //! "ROS1 bag" or "MCAP". + static std::string name(); + //! Above the Mandeye LAZ/CSV kind, which accepts any folder. + static int priority(); + //! True for exactly one file of this format (.bag or .mcap). + static bool accepts(const std::vector& paths); + //! Opens paths.front() with the default BagSourceConfig: the file's only lidar and IMU topics. + static std::shared_ptr open(const std::vector& paths, std::string& error); + //! The topic and option form for paths.front(). + static std::unique_ptr configure(const std::vector& paths); + //! File dialog filter of this format. + static std::vector fileFilter(); + +private: + //! Log time window [start, end) of chunk i in nanoseconds. + std::pair window(size_t i) const; + + BagSourceConfig config_; + uint64_t start_ns_ = 0; + uint64_t end_ns_ = 0; + uint64_t chunk_ns_ = 1; + size_t chunk_count_ = 1; +}; + +using Ros1BagSource = BagSource; +using McapSource = BagSource; //! The file's topics. Returns an empty list and sets error when the file cannot be read. std::vector list_bag_channels(const std::filesystem::path& file, std::string& error); diff --git a/recording_sources/bag_source_ui.cpp b/recording_sources/bag_source_ui.cpp index 91a6049c..9b00d6f4 100644 --- a/recording_sources/bag_source_ui.cpp +++ b/recording_sources/bag_source_ui.cpp @@ -121,3 +121,13 @@ bool BagSourceConfigUi::draw() ImGui::EndDisabled(); return open && ready; } + +std::string BagSourceConfigUi::title() const +{ + return "Open ROS bag / MCAP"; +} + +std::shared_ptr BagSourceConfigUi::open(std::string& error) const +{ + return open_bag_source(config_, error); +} diff --git a/recording_sources/bag_source_ui.h b/recording_sources/bag_source_ui.h index b2dbf349..45c0a122 100644 --- a/recording_sources/bag_source_ui.h +++ b/recording_sources/bag_source_ui.h @@ -1,6 +1,7 @@ #pragma once #include "bag_source.h" +#include "recording_source_factory.h" #include #include @@ -9,15 +10,18 @@ //! ImGui form that builds the BagSourceConfig of one ROS1 bag or MCAP file: lidar and IMU topic pickers filled from the //! file's topics (the only one of each type preselected), PointCloud2 layout, IMU acceleration unit and rotation into the //! lidar frame, and chunk length. -class BagSourceConfigUi +class BagSourceConfigUi final : public RecordingSourceConfigUi { public: //! Reads the file's topic list. explicit BagSourceConfigUi(const std::filesystem::path& file); + std::string title() const override; //! Draws the form into the current ImGui window. Returns true on the frame the user presses Open with a usable //! configuration. - bool draw(); + bool draw() override; + //! open_bag_source with the chosen configuration. + std::shared_ptr open(std::string& error) const override; const BagSourceConfig& config() const { diff --git a/recording_sources/laz_csv_source.cpp b/recording_sources/laz_csv_source.cpp index c3c0a1fe..e21a5bfb 100644 --- a/recording_sources/laz_csv_source.cpp +++ b/recording_sources/laz_csv_source.cpp @@ -10,6 +10,24 @@ namespace fs = std::filesystem; +namespace +{ + bool is_mandeye_file(const fs::path& file) + { + std::string ext = file.extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + return ext == ".laz" || ext == ".las" || ext == ".csv" || ext == ".json" || ext == ".mjc" || ext == ".sn"; + } + + void append_folder_files(const fs::path& folder, std::vector& files) + { + std::error_code ec; + for (fs::directory_iterator it(folder, ec), end; !ec && it != end; it.increment(ec)) + if (it->is_regular_file(ec)) + files.push_back(it->path().string()); + } +} // namespace + //! Time span and sample count of one IMU file's samples. static InputFileSpan imu_file_span(const std::string& file, const Imu& samples) { @@ -356,3 +374,48 @@ void LazCsvSource::loadImu(Imu& imu_data, std::vector& imuSpans) imu_data.insert(imu_data.end(), std::make_move_iterator(chunk.begin()), std::make_move_iterator(chunk.end())); } } + +std::string LazCsvSource::name() +{ + return "Mandeye LAZ/CSV"; +} + +bool LazCsvSource::accepts(const std::vector& paths) +{ + for (const auto& path : paths) + { + std::error_code ec; + if (fs::is_directory(path, ec) || (fs::is_regular_file(path, ec) && is_mandeye_file(path))) + return true; + } + return false; +} + +std::shared_ptr LazCsvSource::open(const std::vector& paths, std::string& error) +{ + std::vector files; + std::error_code ec; + if (paths.size() == 1 && fs::is_regular_file(paths.front(), ec)) + append_folder_files(paths.front().parent_path(), files); // one chunk is no recording: take its whole folder + else + { + for (const auto& path : paths) + { + if (fs::is_directory(path, ec)) + append_folder_files(path, files); + else + files.push_back(path.string()); + } + } + std::shared_ptr source = open(files, false); + if (!source) + error = "not a Mandeye recording: no LAZ and CSV files to pair, or the folder is missing"; + return source; +} + +std::vector LazCsvSource::fileFilter() +{ + return { "Mandeye recording (*.laz *.las *.csv *.json *.mjc *.sn)", "*.laz *.las *.csv *.json *.mjc *.sn" }; +} + +HDMAPPING_REGISTER_RECORDING_SOURCE(LazCsvSource) diff --git a/recording_sources/laz_csv_source.h b/recording_sources/laz_csv_source.h index 358533f4..054d6ac5 100644 --- a/recording_sources/laz_csv_source.h +++ b/recording_sources/laz_csv_source.h @@ -1,6 +1,6 @@ #pragma once -#include "recording_source.h" +#include "recording_source_factory.h" #include #include @@ -16,6 +16,16 @@ class LazCsvSource : public RecordingSource //! calibration file, as load_data always did. Returns null when there are not enough files or the folder is missing. static std::unique_ptr open(std::vector& input_file_names, bool debugMsg); + //! "Mandeye LAZ/CSV". + static std::string name(); + //! True when a path is a folder or a file of a Mandeye recording (.laz .las .csv .json .mjc .sn); open() ignores + //! the other files. + static bool accepts(const std::vector& paths); + //! Opens folders with their top-level files, a single file with the files of its folder, several files as given. + static std::shared_ptr open(const std::vector& paths, std::string& error); + //! File dialog filter of the files of a Mandeye recording. + static std::vector fileFilter(); + std::filesystem::path workingDirectory() const override; size_t chunkCount() const override; std::string chunkName(size_t i) const override; diff --git a/recording_sources/recording_source_factory.cpp b/recording_sources/recording_source_factory.cpp new file mode 100644 index 00000000..36757034 --- /dev/null +++ b/recording_sources/recording_source_factory.cpp @@ -0,0 +1,81 @@ +#include "recording_source_factory.h" + +#include +#include + +namespace +{ + struct Registry + { + std::mutex mutex; + std::vector> factories; //!< highest priority first + }; + + //! Created on first use, so registrations from any translation unit or DLL find it whatever their order. + Registry& registry() + { + static Registry r; + return r; + } +} // namespace + +void RecordingSourceFactory::registerFactory(std::shared_ptr factory) +{ + if (!factory) + return; + auto& r = registry(); + std::scoped_lock lock(r.mutex); + // stable: kinds of equal priority keep their registration order + const auto at = std::upper_bound( + r.factories.begin(), + r.factories.end(), + factory->priority(), + [](int priority, const std::shared_ptr& f) + { + return priority > f->priority(); + }); + r.factories.insert(at, std::move(factory)); +} + +std::vector> RecordingSourceFactory::factories() +{ + auto& r = registry(); + std::scoped_lock lock(r.mutex); + return r.factories; +} + +std::shared_ptr RecordingSourceFactory::find(const std::vector& paths) +{ + if (paths.empty()) + return nullptr; + for (const auto& factory : factories()) + if (factory->accepts(paths)) + return factory; + return nullptr; +} + +std::vector RecordingSourceFactory::fileFilters() +{ + std::vector perKind; + std::string allPatterns; + for (const auto& factory : factories()) + { + const auto filter = factory->fileFilter(); + for (size_t i = 0; i + 1 < filter.size(); i += 2) + { + perKind.push_back(filter[i]); + perKind.push_back(filter[i + 1]); + allPatterns += (allPatterns.empty() ? "" : " ") + filter[i + 1]; + } + } + std::vector filters; + if (!allPatterns.empty()) + { + filters.push_back("All supported recordings"); + filters.push_back(allPatterns); + } + filters.insert(filters.end(), perKind.begin(), perKind.end()); + filters.push_back("All files"); + filters.push_back("*"); + return filters; +} diff --git a/recording_sources/recording_source_factory.h b/recording_sources/recording_source_factory.h new file mode 100644 index 00000000..9f5ac895 --- /dev/null +++ b/recording_sources/recording_source_factory.h @@ -0,0 +1,119 @@ +#pragma once + +#include "recording_source.h" + +#include +#include +#include +#include + +//! Options form a recording kind shows before it opens (e.g. bag topics). The GUI owns the window; draw() fills it. +class RecordingSourceConfigUi +{ +public: + virtual ~RecordingSourceConfigUi() = default; + + //! Title of the window that holds the form. + virtual std::string title() const = 0; + //! Draws the form into the current ImGui window. Returns true on the frame the user asks to open the recording. + virtual bool draw() = 0; + //! Opens the recording with the chosen options. Returns null and sets error when it cannot. + virtual std::shared_ptr open(std::string& error) const = 0; +}; + +//! One kind of recording (Mandeye LAZ/CSV, ROS1 bag, MCAP, ...): recognises its inputs and opens them as a RecordingSource. +//! Every kind registers itself in one per-process registry, which the static members reach; the apps choose through +//! find() and never name a concrete source. +class RecordingSourceFactory +{ +public: + virtual ~RecordingSourceFactory() = default; + + //! Name of the kind, for logs and dialogs. + virtual std::string name() const = 0; + //! Kinds with a higher priority are asked first when several accept the same paths. + virtual int priority() const = 0; + //! True when this kind reads paths (files and folders as the user picked or dropped them). + virtual bool accepts(const std::vector& paths) const = 0; + //! Opens paths with default options. Returns null and sets error when it cannot. + virtual std::shared_ptr open(const std::vector& paths, std::string& error) const = 0; + //! Options form to show before opening paths; null when the kind needs none and open() can be called directly. + virtual std::unique_ptr configure(const std::vector& paths) const = 0; + //! File dialog filter pairs (description, patterns) of the files this kind opens; empty for folder-only kinds. + virtual std::vector fileFilter() const = 0; + + //! Adds a kind to the registry. Thread safe; usually called through HDMAPPING_REGISTER_RECORDING_SOURCE. + static void registerFactory(std::shared_ptr factory); + //! Every registered kind, highest priority first. + static std::vector> factories(); + //! The highest-priority kind that accepts paths; null when none does. + static std::shared_ptr find(const std::vector& paths); + //! Filter pairs for a file dialog that opens any registered kind: one entry for all of them, one per kind, then + //! "All files". + static std::vector fileFilters(); +}; + +//! Adapts the static members of Source to RecordingSourceFactory. Source provides +//! static std::string name(); +//! static bool accepts(const std::vector& paths); +//! static std::shared_ptr open(const std::vector& paths, std::string& error); +//! and optionally +//! static int priority(); // default 0 +//! static std::unique_ptr configure(const std::vector& paths); +//! static std::vector fileFilter(); +template +class RecordingSourceFactoryFor final : public RecordingSourceFactory +{ +public: + std::string name() const override + { + return Source::name(); + } + + int priority() const override + { + if constexpr (requires { Source::priority(); }) + return Source::priority(); + else + return 0; + } + + bool accepts(const std::vector& paths) const override + { + return Source::accepts(paths); + } + + std::shared_ptr open(const std::vector& paths, std::string& error) const override + { + return Source::open(paths, error); + } + + std::unique_ptr configure(const std::vector& paths) const override + { + if constexpr (requires { Source::configure(paths); }) + return Source::configure(paths); + else + return nullptr; + } + + std::vector fileFilter() const override + { + if constexpr (requires { Source::fileFilter(); }) + return Source::fileFilter(); + else + return {}; + } +}; + +#define HDMAPPING_RECORDING_SOURCE_CONCAT_(a, b) a##b +#define HDMAPPING_RECORDING_SOURCE_CONCAT(a, b) HDMAPPING_RECORDING_SOURCE_CONCAT_(a, b) + +//! Registers the recording kind Source (see RecordingSourceFactoryFor) when the program, or the DLL holding this line, +//! starts. Use it once per kind at namespace scope in the kind's .cpp. That .cpp must be compiled into the executable or +//! DLL: in a static library the linker drops the unreferenced registration and the kind silently never appears. +#define HDMAPPING_REGISTER_RECORDING_SOURCE(Source) \ + namespace \ + { \ + [[maybe_unused]] const bool HDMAPPING_RECORDING_SOURCE_CONCAT(recording_source_registered_, __LINE__) = \ + (RecordingSourceFactory::registerFactory(std::make_shared>()), true); \ + } diff --git a/recording_sources/recording_sources.cmake b/recording_sources/recording_sources.cmake new file mode 100644 index 00000000..5a3081d3 --- /dev/null +++ b/recording_sources/recording_sources.cmake @@ -0,0 +1,23 @@ +# Recording kinds (RecordingSource + HDMAPPING_REGISTER_RECORDING_SOURCE) compiled into the apps that load recordings. +# Each kind registers itself from its own .cpp, so these files must be compiled into the executable, not a static +# library. A new kind is added to RECORDING_SOURCE_FILES and needs no change in the apps. + +# The registry and the Mandeye LAZ/CSV kind, which load_data(file names) uses directly. +set(RECORDING_SOURCE_CORE_FILES + ${REPOSITORY_DIRECTORY}/recording_sources/recording_source.h + ${REPOSITORY_DIRECTORY}/recording_sources/recording_source_factory.h + ${REPOSITORY_DIRECTORY}/recording_sources/recording_source_factory.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.h + ${REPOSITORY_DIRECTORY}/recording_sources/laz_csv_source.cpp +) + +# Every kind. ROS1 bag / MCAP: the rosbags readers; McapWriter.cpp holds the single MCAP_IMPLEMENTATION that +# McapReader.cpp relies on. +set(RECORDING_SOURCE_FILES + ${RECORDING_SOURCE_CORE_FILES} + ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.h ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/bag_source_ui.h ${REPOSITORY_DIRECTORY}/recording_sources/bag_source_ui.cpp + ${REPOSITORY_DIRECTORY}/rosbags/McapReader.cpp + ${REPOSITORY_DIRECTORY}/rosbags/McapWriter.cpp + ${REPOSITORY_DIRECTORY}/rosbags/Ros1Bag.cpp +) From 672ea7215bb8e0ede2058a508ba4be2dfdf9a21a Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 13:34:30 +0100 Subject: [PATCH 06/21] Open several ROS1 bags or MCAP files as one recording Dropping several .bag or .mcap files, or folders holding them (searched recursively), opens them as one recording. The files are ordered by log time and must be of one format and must not overlap; each file is split into its own chunk windows. IMU samples come from every file, one span per file. The topics and options chosen for the first file apply to all. The working directory is the deepest folder holding every file. A folder with Mandeye LAZ/LAS files at its top level stays a Mandeye recording even when a bag sits below it. A folder with bags and no LAZ/LAS files at its top level now opens as a bag recording (drag and drop, and lidar_odometry_step_1 ). Co-Authored-By: Claude Opus 5.5 --- recording_sources/bag_source.cpp | 282 ++++++++++++++++++++-------- recording_sources/bag_source.h | 56 +++--- recording_sources/bag_source_ui.cpp | 25 ++- recording_sources/bag_source_ui.h | 8 +- 4 files changed, 258 insertions(+), 113 deletions(-) diff --git a/recording_sources/bag_source.cpp b/recording_sources/bag_source.cpp index a1ce3831..4c53aeff 100644 --- a/recording_sources/bag_source.cpp +++ b/recording_sources/bag_source.cpp @@ -43,11 +43,66 @@ namespace return ext == ".bag" || ext == ".mcap"; } - //! True for exactly one regular file with this lower-case extension. - bool single_file_with_extension(const std::vector& paths, std::string_view extension) + //! True when folder holds Mandeye LAZ/LAS files at its top level: such a folder is a Mandeye recording even when an + //! exported bag sits below it. + bool has_mandeye_files(const fs::path& folder) { std::error_code ec; - return paths.size() == 1 && fs::is_regular_file(paths.front(), ec) && lower_extension(paths.front()) == extension; + for (fs::directory_iterator it(folder, fs::directory_options::skip_permission_denied, ec), end; !ec && it != end; it.increment(ec)) + { + const std::string ext = lower_extension(it->path()); + if ((ext == ".laz" || ext == ".las") && it->is_regular_file(ec)) + return true; + } + return false; + } + + //! Files with this lower-case extension among paths: the files themselves and every one below a folder (a folder + //! with Mandeye files at its top level holds none), sorted by path. Empty when a path holds none. + std::vector files_with_extension(const std::vector& paths, std::string_view extension) + { + std::vector files; + for (const auto& path : paths) + { + std::error_code ec; + const size_t before = files.size(); + if (fs::is_regular_file(path, ec)) + { + if (lower_extension(path) == extension) + files.push_back(path); + } + else if (fs::is_directory(path, ec) && !has_mandeye_files(path)) + { + for (fs::recursive_directory_iterator it(path, fs::directory_options::skip_permission_denied, ec), end; !ec && it != end; + it.increment(ec)) + { + if (lower_extension(it->path()) == extension && it->is_regular_file(ec)) + files.push_back(it->path()); + } + } + if (files.size() == before) + return {}; + } + std::sort(files.begin(), files.end()); + files.erase(std::unique(files.begin(), files.end()), files.end()); + return files; + } + + //! The deepest folder that holds every file. + fs::path common_folder(const std::vector& files) + { + if (files.empty()) + return {}; + fs::path common = files.front().parent_path(); + for (const auto& file : files) + { + const fs::path folder = file.parent_path(); + fs::path shared; + for (auto a = common.begin(), b = folder.begin(); a != common.end() && b != folder.end() && *a == *b; ++a, ++b) + shared /= *a; + common = shared; + } + return common; } //! Message type without its package, as both readers compare it: "sensor_msgs/msg/Imu" -> "Imu". @@ -99,45 +154,55 @@ namespace } // namespace template -BagSource::BagSource(const BagSourceConfig& config, uint64_t start_ns, uint64_t end_ns) +BagSource::BagSource(const BagSourceConfig& config, const std::vector>& spans) : config_(config) - , start_ns_(start_ns) - , end_ns_(end_ns) { - const uint64_t length = end_ns_ - start_ns_; - chunk_ns_ = config_.chunk_seconds > 0.0 ? static_cast(config_.chunk_seconds * 1e9) : length; - chunk_ns_ = std::max(chunk_ns_, 1); - chunk_count_ = std::max(1, static_cast((length + chunk_ns_ - 1) / chunk_ns_)); + for (size_t f = 0; f < spans.size(); ++f) + { + const auto [start_ns, end_ns] = spans[f]; + const uint64_t length = end_ns - start_ns; + uint64_t chunk_ns = config_.chunk_seconds > 0.0 ? static_cast(config_.chunk_seconds * 1e9) : length; + chunk_ns = std::max(chunk_ns, 1); + const size_t count = std::max(1, static_cast((length + chunk_ns - 1) / chunk_ns)); + for (size_t i = 0; i < count; ++i) + { + const uint64_t window_start = start_ns + i * chunk_ns; + windows_.push_back({ f, i, window_start, i + 1 == count ? end_ns : window_start + chunk_ns }); + } + } } template fs::path BagSource::workingDirectory() const { - return config_.file.parent_path(); + return common_folder(config_.files); } template size_t BagSource::chunkCount() const { - return chunk_count_; + return windows_.size(); } template std::string BagSource::chunkName(size_t i) const { + const Window& w = windows_[i]; char index[16]; - std::snprintf(index, sizeof(index), "#%04zu", i); - return config_.file.string() + index; + std::snprintf(index, sizeof(index), "#%04zu", w.index); + return config_.files[w.file].string() + index; } template std::vector BagSource::loadPoints(size_t i, const PointFilter& filter) const { + const Window& w = windows_[i]; + const fs::path& file = config_.files[w.file]; std::vector points; - Reader reader(config_.file, reader_options(config_)); + Reader reader(file, reader_options(config_)); if (!reader.isOpen()) { - std::cerr << "cannot open '" << config_.file.string() << "': " << reader.error() << "\n"; + std::cerr << "cannot open '" << file.string() << "': " << reader.error() << "\n"; return points; } @@ -161,14 +226,13 @@ std::vector BagSource::loadPoints(size_t i, const PointFilter& points.push_back(q); } }; - const auto [start_ns, end_ns] = window(i); rosbags::LogTimeRange range; - range.start_ns = start_ns; - range.end_ns = end_ns; + range.start_ns = w.start_ns; + range.end_ns = w.end_ns; if (!reader.read(callbacks, range)) std::cerr << "reading '" << chunkName(i) << "' failed: " << reader.error() << "\n"; if (!reader.lidarLayoutWarning().empty()) - std::cerr << "'" << config_.file.string() << "': " << reader.lidarLayoutWarning() << "\n"; + std::cerr << "'" << file.string() << "': " << reader.lidarLayoutWarning() << "\n"; std::sort( points.begin(), @@ -182,49 +246,45 @@ std::vector BagSource::loadPoints(size_t i, const PointFilter& } template -ChunkStamp BagSource::stamp(size_t) const +ChunkStamp BagSource::stamp(size_t i) const { - return file_stamp(config_.file); + return file_stamp(config_.files[windows_[i].file]); } template void BagSource::loadImu(Imu& imu_data, std::vector& imuSpans) const { - std::cout << "loading IMU data from '" << config_.file.string() << "' ..\n"; - Reader reader(config_.file, reader_options(config_)); - if (!reader.isOpen()) - { - std::cerr << "cannot open '" << config_.file.string() << "': " << reader.error() << "\n"; - return; - } const rosbags::ImuTransform transform = imu_transform(config_); - const size_t first = imu_data.size(); - typename Reader::Callbacks callbacks; - callbacks.onImu = [&](rosbags::McapImuSample s) + for (const auto& file : config_.files) { - rosbags::applyImuTransform(transform, s); - imu_data.emplace_back( - std::pair(s.timestamp, 0.0), Eigen::Vector3f(s.gyro_x, s.gyro_y, s.gyro_z), Eigen::Vector3f(s.acc_x, s.acc_y, s.acc_z)); - }; - if (!reader.read(callbacks)) - std::cerr << "reading IMU from '" << config_.file.string() << "' failed: " << reader.error() << "\n"; - - InputFileSpan span{ config_.file.string() }; - for (size_t k = first; k < imu_data.size(); ++k) - { - const double t = std::get<0>(imu_data[k]).first; - span.first = span.count == 0 ? t : std::min(span.first, t); - span.last = span.count == 0 ? t : std::max(span.last, t); - span.count++; + std::cout << "loading IMU data from '" << file.string() << "' ..\n"; + Reader reader(file, reader_options(config_)); + if (!reader.isOpen()) + { + std::cerr << "cannot open '" << file.string() << "': " << reader.error() << "\n"; + continue; + } + const size_t first = imu_data.size(); + typename Reader::Callbacks callbacks; + callbacks.onImu = [&](rosbags::McapImuSample s) + { + rosbags::applyImuTransform(transform, s); + imu_data.emplace_back( + std::pair(s.timestamp, 0.0), Eigen::Vector3f(s.gyro_x, s.gyro_y, s.gyro_z), Eigen::Vector3f(s.acc_x, s.acc_y, s.acc_z)); + }; + if (!reader.read(callbacks)) + std::cerr << "reading IMU from '" << file.string() << "' failed: " << reader.error() << "\n"; + + InputFileSpan span{ file.string() }; + for (size_t k = first; k < imu_data.size(); ++k) + { + const double t = std::get<0>(imu_data[k]).first; + span.first = span.count == 0 ? t : std::min(span.first, t); + span.last = span.count == 0 ? t : std::max(span.last, t); + span.count++; + } + imuSpans.push_back(span); } - imuSpans.push_back(span); -} - -template -std::pair BagSource::window(size_t i) const -{ - const uint64_t start = start_ns_ + i * chunk_ns_; - return { start, i + 1 == chunk_count_ ? end_ns_ : start + chunk_ns_ }; } template<> @@ -240,15 +300,21 @@ std::string BagSource::name() } template<> -bool BagSource::accepts(const std::vector& paths) +std::vector BagSource::files(const std::vector& paths) { - return single_file_with_extension(paths, ".bag"); + return files_with_extension(paths, ".bag"); } template<> -bool BagSource::accepts(const std::vector& paths) +std::vector BagSource::files(const std::vector& paths) +{ + return files_with_extension(paths, ".mcap"); +} + +template +bool BagSource::accepts(const std::vector& paths) { - return single_file_with_extension(paths, ".mcap"); + return !files(paths).empty(); } template<> @@ -273,32 +339,71 @@ namespace { template - std::shared_ptr open_with(const BagSourceConfig& config, std::string& error) + std::shared_ptr open_with(BagSourceConfig config, std::string& error) { - Reader reader(config.file, reader_options(config)); - if (!reader.isOpen()) + struct FileSpan { - error = reader.error(); - return nullptr; - } - if (reader.topics().lidar.empty()) + fs::path file; + uint64_t start_ns = 0; + uint64_t end_ns = 0; + }; + std::vector spans; + for (const auto& file : config.files) { - error = "no lidar topic (sensor_msgs/PointCloud2 or livox_ros_driver/CustomMsg) in the file"; - return nullptr; + const std::string where = "'" + file.string() + "': "; + Reader reader(file, reader_options(config)); + if (!reader.isOpen()) + { + error = where + reader.error(); + return nullptr; + } + if (reader.topics().lidar.empty()) + { + error = where + "no lidar topic (sensor_msgs/PointCloud2 or livox_ros_driver/CustomMsg) in the file"; + return nullptr; + } + if (reader.topics().imu.empty()) + { + error = where + "no IMU topic (sensor_msgs/Imu) in the file"; + return nullptr; + } + const auto span = reader.logTimeSpan(); + if (!span) + { + error = where + + "the file has no index, so its time windows cannot be read on their own (reindex it: `rosbag " + "reindex` for a ROS1 bag, `mcap recover` for an MCAP file)"; + return nullptr; + } + spans.push_back({ file, span->start_ns, span->end_ns }); } - if (reader.topics().imu.empty()) + + std::stable_sort( + spans.begin(), + spans.end(), + [](const FileSpan& a, const FileSpan& b) + { + return a.start_ns < b.start_ns; + }); + // end_ns is one past the last message: a file may start at the time the previous one ended + for (size_t k = 1; k < spans.size(); ++k) { - error = "no IMU topic (sensor_msgs/Imu) in the file"; - return nullptr; + if (spans[k].start_ns + 1 < spans[k - 1].end_ns) + { + error = "'" + spans[k - 1].file.string() + "' and '" + spans[k].file.string() + + "' overlap in log time; only files recorded one after another form one recording"; + return nullptr; + } } - const auto span = reader.logTimeSpan(); - if (!span) + + config.files.clear(); + std::vector> windows; + for (const auto& span : spans) { - error = "the file has no index, so its time windows cannot be read on their own (reindex it: `rosbag reindex` for a " - "ROS1 bag, `mcap recover` for an MCAP file)"; - return nullptr; + config.files.push_back(span.file); + windows.emplace_back(span.start_ns, span.end_ns); } - return std::make_shared>(config, span->start_ns, span->end_ns); + return std::make_shared>(config, windows); } template @@ -332,32 +437,45 @@ std::vector list_bag_channels(const fs::path& file, std::string& err std::shared_ptr open_bag_source(const BagSourceConfig& config, std::string& error) { error.clear(); - if (!is_bag_file(config.file)) + if (config.files.empty()) { - error = "not a .bag or .mcap file: " + config.file.string(); + error = "no .bag or .mcap file"; return nullptr; } + for (const auto& file : config.files) + { + if (!is_bag_file(file)) + { + error = "not a .bag or .mcap file: " + file.string(); + return nullptr; + } + if (is_ros1_bag(file) != is_ros1_bag(config.files.front())) + { + error = "ROS1 bags and MCAP files cannot be mixed in one recording"; + return nullptr; + } + } if (config.chunk_seconds < 0.0) { error = "chunk length must not be negative"; return nullptr; } - return is_ros1_bag(config.file) ? open_with(config, error) - : open_with(config, error); + return is_ros1_bag(config.files.front()) ? open_with(config, error) + : open_with(config, error); } template std::shared_ptr BagSource::open(const std::vector& paths, std::string& error) { BagSourceConfig config; - config.file = paths.empty() ? fs::path{} : paths.front(); + config.files = files(paths); return open_bag_source(config, error); } template std::unique_ptr BagSource::configure(const std::vector& paths) { - return std::make_unique(paths.empty() ? fs::path{} : paths.front()); + return std::make_unique(files(paths)); } template class BagSource; diff --git a/recording_sources/bag_source.h b/recording_sources/bag_source.h index 66bfa619..b3af9496 100644 --- a/recording_sources/bag_source.h +++ b/recording_sources/bag_source.h @@ -13,7 +13,8 @@ // No rosbags header here: they re-enable std::byte on MSVC and must come before any standard header (see // rosbags/McapWriter.h), which a header included by GUI code cannot guarantee. -//! How a ROS1 bag or an MCAP file becomes a step 1 recording. Mirrors the options of bag_to_laz / mcap_to_laz. +//! How ROS1 bags or MCAP files become a step 1 recording. Mirrors the options of bag_to_laz / mcap_to_laz. Several files +//! (a split recording) are one recording read in log time order; the topics and options apply to every file. struct BagSourceConfig { //! PointCloud2 record layout; Auto reads it from each message's fields. @@ -24,9 +25,9 @@ struct BagSourceConfig Ouster }; - std::filesystem::path file; - std::string lidar_topic; //!< sensor_msgs/PointCloud2 or livox_ros_driver/CustomMsg; empty: the file's only one - std::string imu_topic; //!< sensor_msgs/Imu; empty: the file's only one + std::vector files; //!< all .bag or all .mcap, in any order; must not overlap in log time + std::string lidar_topic; //!< sensor_msgs/PointCloud2 or livox_ros_driver/CustomMsg; empty: each file's only one + std::string imu_topic; //!< sensor_msgs/Imu; empty: each file's only one LidarLayout lidar_layout = LidarLayout::Auto; bool imu_acc_in_g = true; //!< false: m/s^2 (the sensor_msgs/Imu convention), divided by standard gravity std::array imu_to_lidar{ 0.0, 0.0, 0.0, 1.0 }; //!< rotation IMU frame -> lidar frame, qx qy qz qw @@ -55,15 +56,16 @@ namespace rosbags class McapFileReader; } // namespace rosbags -//! A ROS1 bag or MCAP file split into windows of message log time. Every read opens its own Reader, so chunks can be -//! loaded from several threads at once. Defined and instantiated in bag_source.cpp for Ros1BagSource and McapSource, -//! which register themselves as recording kinds (see RecordingSourceFactoryFor). +//! ROS1 bags or MCAP files split into windows of message log time, the files one after another. Every read opens its own +//! Reader, so chunks can be loaded from several threads at once. Defined and instantiated in bag_source.cpp for Ros1BagSource and +//! McapSource, which register themselves as recording kinds (see RecordingSourceFactoryFor). template class BagSource final : public RecordingSource { public: - //! The recording [start_ns, end_ns) of message log time in config.file, split into config.chunk_seconds windows. - BagSource(const BagSourceConfig& config, uint64_t start_ns, uint64_t end_ns); + //! Splits each file's log time span [start_ns, end_ns) into config.chunk_seconds windows. spans[k] belongs to + //! config.files[k]; the files are in log time order. + BagSource(const BagSourceConfig& config, const std::vector>& spans); std::filesystem::path workingDirectory() const override; size_t chunkCount() const override; @@ -76,24 +78,31 @@ class BagSource final : public RecordingSource static std::string name(); //! Above the Mandeye LAZ/CSV kind, which accepts any folder. static int priority(); - //! True for exactly one file of this format (.bag or .mcap). + //! True when every path is a file of this format (.bag or .mcap) or a folder with such files below it and no + //! Mandeye LAZ/LAS files at its top level. static bool accepts(const std::vector& paths); - //! Opens paths.front() with the default BagSourceConfig: the file's only lidar and IMU topics. + //! Opens the files of paths (see files()) with the default BagSourceConfig: each file's only lidar and IMU topics. static std::shared_ptr open(const std::vector& paths, std::string& error); - //! The topic and option form for paths.front(). + //! The files of this format among paths: the files themselves and every one below a folder, sorted by path; empty + //! when a path is neither. + static std::vector files(const std::vector& paths); + //! The topic and option form for the files of paths. static std::unique_ptr configure(const std::vector& paths); //! File dialog filter of this format. static std::vector fileFilter(); private: - //! Log time window [start, end) of chunk i in nanoseconds. - std::pair window(size_t i) const; + //! One chunk: a log time window [start_ns, end_ns) of one file. + struct Window + { + size_t file = 0; //!< index into config_.files + size_t index = 0; //!< the window's number within its file + uint64_t start_ns = 0; + uint64_t end_ns = 0; + }; BagSourceConfig config_; - uint64_t start_ns_ = 0; - uint64_t end_ns_ = 0; - uint64_t chunk_ns_ = 1; - size_t chunk_count_ = 1; + std::vector windows_; }; using Ros1BagSource = BagSource; @@ -102,9 +111,10 @@ using McapSource = BagSource; //! The file's topics. Returns an empty list and sets error when the file cannot be read. std::vector list_bag_channels(const std::filesystem::path& file, std::string& error); -//! Opens a ROS1 bag or an MCAP file as a RecordingSource. Chunks are chunk_seconds windows of message log time, read -//! through the file's chunk index, so lazy loading reads each window on its own. Points keep the lidar frame (lidar id 0, -//! no calibration); IMU samples are rotated into the lidar frame and scaled to g. The working directory is the file's -//! folder. Requires an indexed file. -//! Returns null and sets error when the file cannot be used. +//! Opens ROS1 bags or MCAP files as one RecordingSource, the files ordered by log time. Chunks are chunk_seconds windows +//! of message log time within one file, read through the file's chunk index, so lazy loading reads each window on its +//! own. Points keep the lidar frame (lidar id 0, no calibration); IMU samples are rotated into the lidar frame and scaled +//! to g. The working directory is the deepest folder that holds every file. Requires indexed files with the lidar and IMU +//! topics, all of one format and not overlapping in log time. +//! Returns null and sets error when the files cannot be used. std::shared_ptr open_bag_source(const BagSourceConfig& config, std::string& error); diff --git a/recording_sources/bag_source_ui.cpp b/recording_sources/bag_source_ui.cpp index 9b00d6f4..e888d158 100644 --- a/recording_sources/bag_source_ui.cpp +++ b/recording_sources/bag_source_ui.cpp @@ -63,17 +63,34 @@ namespace } } // namespace -BagSourceConfigUi::BagSourceConfigUi(const std::filesystem::path& file) +BagSourceConfigUi::BagSourceConfigUi(const std::vector& files) { - config_.file = file; - channels_ = list_bag_channels(file, list_error_); + config_.files = files; + if (files.empty()) + { + list_error_ = "no .bag or .mcap file"; + return; + } + channels_ = list_bag_channels(files.front(), list_error_); config_.lidar_topic = only_topic(channels_, BagChannel::Kind::Lidar); config_.imu_topic = only_topic(channels_, BagChannel::Kind::Imu); } bool BagSourceConfigUi::draw() { - ImGui::TextUnformatted(config_.file.filename().string().c_str()); + if (config_.files.size() == 1) + ImGui::TextUnformatted(config_.files.front().filename().string().c_str()); + else if (!config_.files.empty()) + { + ImGui::Text("%zu files, topics from %s", config_.files.size(), config_.files.front().filename().string().c_str()); + if (ImGui::IsItemHovered()) + { + std::string list; + for (const auto& file : config_.files) + list += file.string() + "\n"; + ImGui::SetTooltip("%s", list.c_str()); + } + } if (!list_error_.empty()) { ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", list_error_.c_str()); diff --git a/recording_sources/bag_source_ui.h b/recording_sources/bag_source_ui.h index 45c0a122..c7669615 100644 --- a/recording_sources/bag_source_ui.h +++ b/recording_sources/bag_source_ui.h @@ -7,14 +7,14 @@ #include #include -//! ImGui form that builds the BagSourceConfig of one ROS1 bag or MCAP file: lidar and IMU topic pickers filled from the -//! file's topics (the only one of each type preselected), PointCloud2 layout, IMU acceleration unit and rotation into the +//! ImGui form that builds the BagSourceConfig of ROS1 bags or MCAP files: lidar and IMU topic pickers filled from the +//! first file's topics (the only one of each type preselected), PointCloud2 layout, IMU acceleration unit and rotation into the //! lidar frame, and chunk length. class BagSourceConfigUi final : public RecordingSourceConfigUi { public: - //! Reads the file's topic list. - explicit BagSourceConfigUi(const std::filesystem::path& file); + //! Reads the topic list of the first file; the chosen topics apply to every file. + explicit BagSourceConfigUi(const std::vector& files); std::string title() const override; //! Draws the form into the current ImGui window. Returns true on the frame the user presses Open with a usable From 977c866a3e278f6a01e6be4af1befb34896f7036 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 13:34:30 +0100 Subject: [PATCH 07/21] Show loading progress of ROS1 bags and MCAP files A compressed bag can take minutes to load, most of it in the IMU pass, which reads the whole recording on one thread. - The rosbags readers report each message's log time (onProgress), and RecordingSource::loadImu passes the fraction read to a callback. - load_data logs the IMU progress with time left every 2 s (ConsoleProgress), one line per point chunk, and the IMU sample count, and publishes the progress to LidarOdometryParams::load_progress. - Step 1's "Loading data" window shows IMU and point cloud progress bars. - Opening a bz2-compressed ROS1 bag prints a warning, also shown in the bag options window, that decompressing it (rosbag decompress) makes loading much faster. Co-Authored-By: Claude Opus 5.5 --- apps/lidar_odometry_step_1/lidar_odometry.cpp | 42 +++++++++++++- .../lidar_odometry_gui.cpp | 20 +++++++ .../lidar_odometry_utils.h | 2 + recording_sources/bag_source.cpp | 56 ++++++++++++++++++- recording_sources/bag_source.h | 6 +- recording_sources/bag_source_ui.cpp | 8 +++ recording_sources/bag_source_ui.h | 1 + recording_sources/laz_csv_source.cpp | 2 +- recording_sources/laz_csv_source.h | 2 +- recording_sources/recording_source.h | 15 ++++- rosbags/McapReader.cpp | 2 + rosbags/McapReader.h | 2 + rosbags/Ros1Bag.cpp | 22 ++++++++ rosbags/Ros1Bag.h | 7 +++ 14 files changed, 179 insertions(+), 8 deletions(-) diff --git a/apps/lidar_odometry_step_1/lidar_odometry.cpp b/apps/lidar_odometry_step_1/lidar_odometry.cpp index 9c1ee0ac..69b7881a 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry.cpp @@ -1,4 +1,5 @@ #include "lidar_odometry.h" +#include "../console_tools/console_progress.h" #include "hdmapping_profiler.hpp" #include "laz_csv_source.h" #include "raw_cloud_loader.h" @@ -131,7 +132,28 @@ static bool load_from_source( InputFileSpans& fileSpans) { const fs::path working_directory = source->workingDirectory(); - source->loadImu(imu_data, fileSpans.imu); + LoadProgress* progress = params.load_progress.get(); + if (progress) + { + progress->imu = 0.0; + progress->chunks_done = 0; + progress->chunks_total = 0; + } + // a long read (a compressed bag) logs its progress in per mille, so the console shows it is still going + constexpr uint64_t kImuSteps = 1000; + ConsoleProgress imu_console("IMU data", kImuSteps); + source->loadImu( + imu_data, + fileSpans.imu, + [&](double fraction) + { + if (progress) + progress->imu = fraction; + imu_console.update(static_cast(fraction * kImuSteps)); + }); + if (progress) + progress->imu = 1.0; + std::cout << "IMU samples: " << imu_data.size() << std::endl; // Sort once after merging std::sort( @@ -175,6 +197,16 @@ static bool load_from_source( // the first file's points are dropped unless params.skip_first_file is off const size_t firstUsedFile = params.skip_first_file ? 1 : 0; + std::atomic chunks_done{ 0 }; + const ConsoleProgress chunks_console("Point clouds", minSize); + const auto chunk_loaded = [&](size_t i) + { + const size_t done = ++chunks_done; + if (progress) + progress->chunks_done = done; + spdlog::info("{} loaded ({})", source->chunkName(i), chunks_console.status(done)); + }; + // --- Working directories fs::path wdp = working_directory / "preview"; @@ -209,12 +241,17 @@ static bool load_from_source( L.loaded.assign(minSize, 0); L.done.assign(minSize, 0); std::vector> gaps_in_file(minSize); + // a skipped file's cloud is never read: it counts as done + chunks_done = std::min(firstUsedFile, minSize); + if (progress) + progress->chunks_total = minSize; tbb::parallel_for( std::min(firstUsedFile, minSize), // a skipped file's cloud is never used minSize, [&](size_t i) { auto data = source->loadPoints(i, filter); + chunk_loaded(i); // after the read: a cloud drive may report other metadata once it has downloaded the file L.stamp[i] = source->stamp(i); L.n[i] = data.size(); @@ -241,12 +278,15 @@ static bool load_from_source( std::vector> gaps_in_file(minSize); std::vector t_first(minSize, 0.0); std::vector t_last(minSize, 0.0); + if (progress) + progress->chunks_total = minSize; tbb::parallel_for( size_t(0), minSize, [&](size_t i) { auto data = source->loadPoints(i, filter); + chunk_loaded(i); // Optional calibration validation (first file only) if ((i == 0) && params.save_calibration_validation) diff --git a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp index a6020857..b3fd7670 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp @@ -223,6 +223,24 @@ static fs::path recording_folder(const std::vector& paths) return fs::is_directory(paths.front()) ? paths.front() : paths.front().parent_path(); } +//! Progress bars of load_data: the IMU read, then the point chunks. +static void load_progress_gui() +{ + const auto progress = params.load_progress; + if (!progress) + return; + const float imu = static_cast(progress->imu.load()); + char text[64]; + std::snprintf(text, sizeof(text), "IMU data %.0f %%", imu * 100.0f); + ImGui::ProgressBar(imu, ImVec2(400.0f, 0.0f), text); + const size_t total = progress->chunks_total.load(); + if (total == 0) + return; + const size_t done = std::min(progress->chunks_done.load(), total); + std::snprintf(text, sizeof(text), "Point clouds %zu / %zu", done, total); + ImGui::ProgressBar(static_cast(done) / static_cast(total), ImVec2(400.0f, 0.0f), text); +} + static void resources_gui() { if (!params.run_report || !ImGui::CollapsingHeader("Resources", ImGuiTreeNodeFlags_DefaultOpen)) @@ -2018,6 +2036,7 @@ static void launchPipeline(const std::string& folder, bool compute, bool save) if (params.run_report && !params.working_directory_cache.empty()) remove_cache(params); params.run_report = std::make_shared(folder, params.points_global_spill_directory, "gui"); + params.load_progress = std::make_shared(); step_1_done = step_2_done = false; calculations_failed = false; pendingLoadFolder = folder; @@ -2303,6 +2322,7 @@ void display() if (ImGui::SmallButton("Controls / Help (F1)")) info_gui = true; ImGui::Text("Loading and preparing: %s", pendingLoadFolder.c_str()); + load_progress_gui(); recording_span_gui(); resources_gui(); ImGui::End(); diff --git a/apps/lidar_odometry_step_1/lidar_odometry_utils.h b/apps/lidar_odometry_step_1/lidar_odometry_utils.h index 7f61e683..a28624ea 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_utils.h +++ b/apps/lidar_odometry_step_1/lidar_odometry_utils.h @@ -50,6 +50,7 @@ inline std::string get_software_version() } struct RawCloudLoader; // raw_cloud_loader.h: raw point clouds loaded per file during step 1 +struct LoadProgress; // recording_source.h: progress of load_data class RunReport; class PointsGlobalSpill; // points_global_spill.h: step 2's map buffer kept in a file @@ -76,6 +77,7 @@ struct LidarOdometryParams std::shared_ptr raw_cloud_loader; PointsGlobalSpill* points_global_spill = nullptr; std::shared_ptr run_report; // runtime accounting, never a processing parameter + std::shared_ptr load_progress; // optional: load_data publishes its progress here for a GUI // Optional GUI observer, called by the producer only at safe trajectory boundaries. std::function&, bool)> publish_trajectory; diff --git a/recording_sources/bag_source.cpp b/recording_sources/bag_source.cpp index 4c53aeff..9eac812e 100644 --- a/recording_sources/bag_source.cpp +++ b/recording_sources/bag_source.cpp @@ -252,20 +252,43 @@ ChunkStamp BagSource::stamp(size_t i) const } template -void BagSource::loadImu(Imu& imu_data, std::vector& imuSpans) const +void BagSource::loadImu(Imu& imu_data, std::vector& imuSpans, const std::function& progress) const { + // progress is the share of the files' log time read: the IMU messages are spread over the whole recording + std::vector file_start(config_.files.size(), 0), file_end(config_.files.size(), 0); + for (const Window& w : windows_) + { + if (w.index == 0) + file_start[w.file] = w.start_ns; + file_end[w.file] = w.end_ns; + } + uint64_t total_ns = 0; + for (size_t f = 0; f < config_.files.size(); ++f) + total_ns += file_end[f] - file_start[f]; + uint64_t done_ns = 0; + const rosbags::ImuTransform transform = imu_transform(config_); - for (const auto& file : config_.files) + for (size_t f = 0; f < config_.files.size(); ++f) { + const fs::path& file = config_.files[f]; std::cout << "loading IMU data from '" << file.string() << "' ..\n"; Reader reader(file, reader_options(config_)); if (!reader.isOpen()) { std::cerr << "cannot open '" << file.string() << "': " << reader.error() << "\n"; + done_ns += file_end[f] - file_start[f]; continue; } const size_t first = imu_data.size(); typename Reader::Callbacks callbacks; + if (progress && total_ns > 0) + { + callbacks.onProgress = [&, f](uint64_t log_time_ns) + { + const uint64_t in_file = std::clamp(log_time_ns, file_start[f], file_end[f]) - file_start[f]; + progress(static_cast(done_ns + in_file) / static_cast(total_ns)); + }; + } callbacks.onImu = [&](rosbags::McapImuSample s) { rosbags::applyImuTransform(transform, s); @@ -274,6 +297,9 @@ void BagSource::loadImu(Imu& imu_data, std::vector& imuSp }; if (!reader.read(callbacks)) std::cerr << "reading IMU from '" << file.string() << "' failed: " << reader.error() << "\n"; + done_ns += file_end[f] - file_start[f]; + if (progress && total_ns > 0) + progress(static_cast(done_ns) / static_cast(total_ns)); InputFileSpan span{ file.string() }; for (size_t k = first; k < imu_data.size(); ++k) @@ -428,6 +454,30 @@ namespace } } // namespace +std::string bag_compression_hint(const std::vector& files) +{ + size_t bz2 = 0; + fs::path example; + for (const auto& file : files) + { + if (!is_ros1_bag(file)) + continue; + rosbags::Ros1BagReader reader(file); + if (reader.isOpen() && reader.chunkCompression() == "bz2") + { + if (bz2++ == 0) + example = file; + } + } + if (bz2 == 0) + return {}; + const std::string which = bz2 == 1 ? "'" + example.filename().string() + "' is" : std::to_string(bz2) + " of the bags are"; + return which + + " bz2-compressed, which loads much slower than an uncompressed bag. For faster loading, decompress it first: " + "rosbag decompress " + + example.filename().string(); +} + std::vector list_bag_channels(const fs::path& file, std::string& error) { error.clear(); @@ -460,6 +510,8 @@ std::shared_ptr open_bag_source(const BagSourceConfig& config, error = "chunk length must not be negative"; return nullptr; } + if (const std::string hint = bag_compression_hint(config.files); !hint.empty()) + std::cerr << "WARNING: " << hint << std::endl; return is_ros1_bag(config.files.front()) ? open_with(config, error) : open_with(config, error); } diff --git a/recording_sources/bag_source.h b/recording_sources/bag_source.h index b3af9496..cd829d91 100644 --- a/recording_sources/bag_source.h +++ b/recording_sources/bag_source.h @@ -72,7 +72,7 @@ class BagSource final : public RecordingSource std::string chunkName(size_t i) const override; std::vector loadPoints(size_t i, const PointFilter& filter) const override; ChunkStamp stamp(size_t i) const override; - void loadImu(Imu& imu_data, std::vector& imuSpans) const override; + void loadImu(Imu& imu_data, std::vector& imuSpans, const std::function& progress) const override; //! "ROS1 bag" or "MCAP". static std::string name(); @@ -108,6 +108,10 @@ class BagSource final : public RecordingSource using Ros1BagSource = BagSource; using McapSource = BagSource; +//! Advice for ROS1 bags among files that use bz2 chunk compression, which loads tens of times slower than lz4 or none +//! because the IMU data is read in one pass over the whole bag; empty when no file does. +std::string bag_compression_hint(const std::vector& files); + //! The file's topics. Returns an empty list and sets error when the file cannot be read. std::vector list_bag_channels(const std::filesystem::path& file, std::string& error); diff --git a/recording_sources/bag_source_ui.cpp b/recording_sources/bag_source_ui.cpp index e888d158..752442be 100644 --- a/recording_sources/bag_source_ui.cpp +++ b/recording_sources/bag_source_ui.cpp @@ -72,6 +72,7 @@ BagSourceConfigUi::BagSourceConfigUi(const std::vector& f return; } channels_ = list_bag_channels(files.front(), list_error_); + compression_hint_ = bag_compression_hint(files); config_.lidar_topic = only_topic(channels_, BagChannel::Kind::Lidar); config_.imu_topic = only_topic(channels_, BagChannel::Kind::Imu); } @@ -97,6 +98,13 @@ bool BagSourceConfigUi::draw() return false; } + if (!compression_hint_.empty()) + { + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 40.0f); + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.3f, 1.0f), "%s", compression_hint_.c_str()); + ImGui::PopTextWrapPos(); + } + topic_combo("LiDAR topic", channels_, BagChannel::Kind::Lidar, config_.lidar_topic); topic_combo("IMU topic", channels_, BagChannel::Kind::Imu, config_.imu_topic); diff --git a/recording_sources/bag_source_ui.h b/recording_sources/bag_source_ui.h index c7669615..ffcad2fe 100644 --- a/recording_sources/bag_source_ui.h +++ b/recording_sources/bag_source_ui.h @@ -32,4 +32,5 @@ class BagSourceConfigUi final : public RecordingSourceConfigUi BagSourceConfig config_; std::vector channels_; std::string list_error_; + std::string compression_hint_; //!< bag_compression_hint of the files }; diff --git a/recording_sources/laz_csv_source.cpp b/recording_sources/laz_csv_source.cpp index e21a5bfb..b6e8c170 100644 --- a/recording_sources/laz_csv_source.cpp +++ b/recording_sources/laz_csv_source.cpp @@ -316,7 +316,7 @@ ChunkStamp LazCsvSource::stamp(size_t i) const return s; } -void LazCsvSource::loadImu(Imu& imu_data, std::vector& imuSpans) const +void LazCsvSource::loadImu(Imu& imu_data, std::vector& imuSpans, const std::function&) const { // --- Load IMU data (still sequential, could parallelize later) std::cout << "loading IMU data from 'imu****.csv' using ID " << imu_number_to_use_ << " from reference '" << sn_file_ << "' ..\n"; diff --git a/recording_sources/laz_csv_source.h b/recording_sources/laz_csv_source.h index 054d6ac5..69adaad9 100644 --- a/recording_sources/laz_csv_source.h +++ b/recording_sources/laz_csv_source.h @@ -31,7 +31,7 @@ class LazCsvSource : public RecordingSource std::string chunkName(size_t i) const override; std::vector loadPoints(size_t i, const PointFilter& filter) const override; ChunkStamp stamp(size_t i) const override; - void loadImu(Imu& imu_data, std::vector& imuSpans) const override; + void loadImu(Imu& imu_data, std::vector& imuSpans, const std::function& progress) const override; private: LazCsvSource() = default; diff --git a/recording_sources/recording_source.h b/recording_sources/recording_source.h index 4389e9a6..d6f16f08 100644 --- a/recording_sources/recording_source.h +++ b/recording_sources/recording_source.h @@ -2,8 +2,10 @@ #include "lidar_odometry_utils.h" +#include #include #include +#include #include #include #include @@ -36,6 +38,14 @@ struct ChunkStamp std::filesystem::file_time_type time{}; }; +//! Progress of load_data, written by the loading threads and read by a GUI. +struct LoadProgress +{ + std::atomic imu{ 0.0 }; //!< fraction of the IMU data read, 0 to 1 + std::atomic chunks_done{ 0 }; //!< point chunks read + std::atomic chunks_total{ 0 }; //!< point chunks to read; 0 until the IMU data is read +}; + //! A recording as step 1 reads it: an IMU stream plus raw LiDAR points split into time-ordered chunks. //! load_data() and the lazy raw cloud loader read input data only through this interface. class RecordingSource @@ -53,6 +63,7 @@ class RecordingSource virtual std::vector loadPoints(size_t i, const PointFilter& filter) const = 0; //! Current state of chunk i's backing data. virtual ChunkStamp stamp(size_t i) const = 0; - //! Appends every IMU sample, unsorted, to imu_data; imuSpans receives one span per IMU input file. - virtual void loadImu(Imu& imu_data, std::vector& imuSpans) const = 0; + //! Appends every IMU sample, unsorted, to imu_data; imuSpans receives one span per IMU input file. Calls progress + //! with the fraction read so far (0 to 1) when reading takes long enough to report. + virtual void loadImu(Imu& imu_data, std::vector& imuSpans, const std::function& progress) const = 0; }; diff --git a/rosbags/McapReader.cpp b/rosbags/McapReader.cpp index 77a5b66f..bdb96d2f 100644 --- a/rosbags/McapReader.cpp +++ b/rosbags/McapReader.cpp @@ -254,6 +254,8 @@ bool McapFileReader::read(const Callbacks& callbacks, const LogTimeRange& range) auto messages = impl_->reader.readMessages(onProblem, read_options); for(const auto& view : messages) { + if(callbacks.onProgress) + callbacks.onProgress(view.message.logTime); const auto* data = reinterpret_cast(view.message.data); const size_t size = view.message.dataSize; const std::string& topic = view.channel->topic; diff --git a/rosbags/McapReader.h b/rosbags/McapReader.h index ec105aa1..7b658703 100644 --- a/rosbags/McapReader.h +++ b/rosbags/McapReader.h @@ -119,6 +119,8 @@ class McapFileReader std::function&&)> onPointCloud; std::function onImu; std::function onSn; + // Called with the log time of every message read, before it is decoded; for progress reports. + std::function onProgress; }; // Streams the messages whose log time lies in `range` (by default the whole diff --git a/rosbags/Ros1Bag.cpp b/rosbags/Ros1Bag.cpp index 24270b95..cc19befe 100644 --- a/rosbags/Ros1Bag.cpp +++ b/rosbags/Ros1Bag.cpp @@ -505,6 +505,21 @@ bool Ros1BagReader::parseRecords(const uint8_t* data, size_t size, const Message return true; } +std::string Ros1BagReader::chunkCompression() +{ + if(!isOpen() || chunks_.empty()) + return {}; + file_.clear(); + file_.seekg(static_cast(chunks_.front().pos)); + HeaderFields header; + std::vector data; + std::string error; + if(!readRecord(file_, header, data, error)) + return {}; + const auto compression = header.find("compression"); + return compression == header.end() ? std::string{} : compression->second; +} + std::optional Ros1BagReader::recordTimeSpan() const { if(chunks_.empty()) @@ -1081,6 +1096,11 @@ std::optional Ros1BagFileReader::logTimeSpan() const return reader_.recordTimeSpan(); } +std::string Ros1BagFileReader::compression() +{ + return reader_.chunkCompression(); +} + bool Ros1BagFileReader::read(const Callbacks& callbacks, const LogTimeRange& range) { if(!open_) @@ -1090,6 +1110,8 @@ bool Ros1BagFileReader::read(const Callbacks& callbacks, const LogTimeRange& ran const bool ok = reader_.forEachMessage( [&](const Ros1Connection& c, uint64_t time_ns, const uint8_t* data, size_t size) { + if(callbacks.onProgress) + callbacks.onProgress(time_ns); if(c.topic == topics_.lidar && callbacks.onPointCloud) { std::vector points; diff --git a/rosbags/Ros1Bag.h b/rosbags/Ros1Bag.h index 9b5d4356..1b3fa791 100644 --- a/rosbags/Ros1Bag.h +++ b/rosbags/Ros1Bag.h @@ -62,6 +62,10 @@ class Ros1BagReader // unindexed bag. std::optional recordTimeSpan() const; + // Compression of the first chunk ("none", "bz2" or "lz4"), as rosbag writes + // one for the whole bag; empty for an unindexed bag or a read error. + std::string chunkCompression(); + private: struct IndexedChunk { @@ -216,6 +220,9 @@ class Ros1BagFileReader // Record times covered by the bag's chunks; nullopt for an unindexed bag. std::optional logTimeSpan() const; + // Chunk compression of the bag ("none", "bz2", "lz4"); empty when unknown. + std::string compression(); + private: Ros1BagReader reader_; McapReaderOptions options_; From 7ca1cdabd6a59c571edfd7d6131c91e585da6d42 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 13:34:30 +0100 Subject: [PATCH 08/21] Add a loading test campaign for ROS1 bags and MCAP files scripts/bag_loading_campaign.sh downloads public lidar + IMU recordings from Hugging Face and Zenodo, writes each one as MCAP (none, lz4, zstd), ROS1 bag (none, bz2, lz4) and as a recording split into three files, times lidar_odometry_step_1 loading every variant and checks that all variants of a recording load the same points and IMU samples. Runs in bash on Linux, macOS and MSYS2 (with the python.org Python on Windows). Co-Authored-By: Claude Opus 5.5 --- scripts/README.md | 8 + scripts/bag_loading_campaign.py | 457 ++++++++++++++++++++++++++++++++ scripts/bag_loading_campaign.sh | 56 ++++ 3 files changed, 521 insertions(+) create mode 100755 scripts/bag_loading_campaign.py create mode 100755 scripts/bag_loading_campaign.sh diff --git a/scripts/README.md b/scripts/README.md index c3fe7c17..69da329f 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -38,6 +38,14 @@ python3 scripts/lio_to_tum.py /path/to/lio_result_0 trajectory.tum ``` +* `bag_loading_campaign.sh` (with `bag_loading_campaign.py`) — loading test campaign for ROS1 bags and MCAP files. Downloads public lidar + IMU recordings from Hugging Face and Zenodo, writes each in every format step 1 reads (MCAP none/lz4/zstd, ROS1 bag none/bz2/lz4, a recording split into several files), times `lidar_odometry_step_1` loading each one and checks that all variants load the same points and IMU samples. Runs in bash on Linux, macOS and MSYS2 (on Windows with the python.org Python); keeps its Python environment, downloads (about 2.8 GB, 9 GB with `--large`) and results in `~/hdmapping_bag_campaign`: + + ``` + scripts/bag_loading_campaign.sh --list + scripts/bag_loading_campaign.sh --step1 build/bin/lidar_odometry_step_1 + scripts/bag_loading_campaign.sh run --variants ros1_bz2 mcap_zstd + ``` + * `lio_ate.py` — absolute trajectory error of a TUM trajectory against a golden one: poses paired in order with timestamps within `--max-dt-s` (default 10 µs), position RMSE without alignment. Exits 0 when the RMSE is within `--max-ate-m` (default 0.001 m), 1 when it is not, 2 when the poses or timestamps differ. Standard library only: ``` diff --git a/scripts/bag_loading_campaign.py b/scripts/bag_loading_campaign.py new file mode 100755 index 00000000..479fb640 --- /dev/null +++ b/scripts/bag_loading_campaign.py @@ -0,0 +1,457 @@ +#!/usr/bin/env python3 +"""Loading test campaign for ROS1 bags and MCAP files in lidar_odometry_step_1. + +Downloads public lidar + IMU recordings from Hugging Face and Zenodo, rewrites each one into every container and +compression step 1 reads (MCAP none/lz4/zstd, ROS1 bag none/bz2/lz4, and recordings split into several files), then +runs lidar_odometry_step_1 on every variant and times its loading. All variants of one recording must load the same +number of points and IMU samples; a difference is reported as a mismatch. + +Run it through bag_loading_campaign.sh, which sets up a Python environment with rosbags, mcap, lz4 and zstandard. + +Steps (default: all of them): + download fetch the recordings into /downloads (resumes partial downloads) + prepare write the variants into /variants//// + run load every variant with lidar_odometry_step_1, write /results.csv and /results.md +""" + +from __future__ import annotations + +import argparse +import csv +import datetime +import os +import platform +import re +import shutil +import subprocess +import sys +import tarfile +import time +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path + + +@dataclass +class Recording: + """A public recording with a lidar and an IMU topic.""" + + name: str + url: str + size_mb: int + license: str + note: str + archive: bool = False # a .tar.gz holding several bags; the smallest one is used + large: bool = False # downloaded only with --large + imu_topic: str = "" # empty: the IMU topic with the most messages + + +RECORDINGS = [ + Recording( + name="fastlivo_hku2", + url="https://huggingface.co/datasets/DapengFeng/MCAP/resolve/main/FAST-LIVO/hku2/hku2_0.mcap", + size_mb=885, + license="CC-BY-NC-4.0", + note="FAST-LIVO hku2 as ROS 2 MCAP (CDR): Livox Avia livox_ros_driver/CustomMsg + IMU, 105 s", + ), + Recording( + name="koide_livox_ros1", + url="https://zenodo.org/api/records/7780490/files/livox_ros1.tar.gz/content", + size_mb=1945, + license="CC-BY-4.0", + note="Koide LiDAR-camera calibration dataset (Zenodo 7780490), ROS1 bag: Livox Avia PointCloud2 and CustomMsg + IMU", + archive=True, + ), + Recording( + name="hilti2022_exp14", + url="https://huggingface.co/datasets/Hilti-Research/hilti-slam-challenge-2022/resolve/main/rosbags/exp14_basement_2.bag", + size_mb=6260, + license="CC-BY-NC-SA-3.0", + note="Hilti SLAM Challenge 2022 exp14, ROS1 bag: Hesai PandarXT-32 PointCloud2 + IMU, cameras dropped", + large=True, + ), +] + +LIDAR_TYPES = {"PointCloud2": "pc2", "CustomMsg": "custommsg"} +SPLIT_PARTS = 3 + + +# -------------------------------------------------------------------------------------------------------------------- +# download + + +def log(message: str) -> None: + print(f"[{datetime.datetime.now():%H:%M:%S}] {message}", flush=True) + + +def download(url: str, target: Path) -> None: + """Downloads url to target, resuming a partial file; a complete file is kept.""" + target.parent.mkdir(parents=True, exist_ok=True) + partial = target.with_name(target.name + ".part") + if target.exists(): + log(f"{target.name}: already downloaded") + return + offset = partial.stat().st_size if partial.exists() else 0 + request = urllib.request.Request(url, headers={"User-Agent": "hdmapping-bag-campaign"}) + if offset: + request.add_header("Range", f"bytes={offset}-") + with urllib.request.urlopen(request) as response: + if offset and response.status != 206: + offset = 0 # the server ignored the range: start over + total = offset + int(response.headers.get("Content-Length", 0)) + done = offset + last = 0.0 + with open(partial, "ab" if offset else "wb") as out: + while chunk := response.read(1 << 20): + out.write(chunk) + done += len(chunk) + if time.monotonic() - last > 5: + last = time.monotonic() + percent = f"{100 * done / total:.0f}%" if total else "?" + log(f"{target.name}: {done >> 20} / {total >> 20} MB ({percent})") + partial.rename(target) + log(f"{target.name}: downloaded {done >> 20} MB") + + +def source_file(recording: Recording, data: Path) -> Path: + """The downloaded recording, extracted from its archive when it is one.""" + downloads = data / "downloads" / recording.name + if not recording.archive: + return downloads / Path(recording.url).name + extracted = downloads / "extracted" + bags = sorted(extracted.rglob("*.bag"), key=lambda p: p.stat().st_size) if extracted.exists() else [] + if not bags: + raise RuntimeError(f"{recording.name}: no .bag in {extracted}; run the download step") + return bags[0] + + +def download_recording(recording: Recording, data: Path) -> None: + downloads = data / "downloads" / recording.name + if not recording.archive: + download(recording.url, downloads / Path(recording.url).name) + return + archive = downloads / f"{recording.name}.tar.gz" + extracted = downloads / "extracted" + if extracted.exists() and any(extracted.rglob("*.bag")): + log(f"{recording.name}: already extracted") + return + download(recording.url, archive) + log(f"{recording.name}: extracting {archive.name}") + with tarfile.open(archive) as tar: + tar.extractall(extracted, filter="data") + + +# -------------------------------------------------------------------------------------------------------------------- +# prepare + + +@dataclass +class Topics: + imu: str + lidars: dict[str, str] = field(default_factory=dict) # label (pc2, custommsg) -> topic + start_ns: int = 0 + end_ns: int = 0 + + +def find_topics(path: Path, imu_topic: str) -> Topics: + from rosbags.highlevel import AnyReader + + with AnyReader([path]) as reader: + imus = [c for c in reader.connections if c.msgtype.endswith("/Imu")] + if imu_topic: + imus = [c for c in imus if c.topic == imu_topic] + if not imus: + raise RuntimeError(f"{path}: no sensor_msgs/Imu topic") + imu = max(imus, key=lambda c: c.msgcount) + topics = Topics(imu=imu.topic, start_ns=reader.start_time, end_ns=reader.end_time) + for c in sorted(reader.connections, key=lambda c: -c.msgcount): + label = LIDAR_TYPES.get(c.msgtype.rsplit("/", 1)[-1]) + if label and label not in topics.lidars: + topics.lidars[label] = c.topic + if not topics.lidars: + raise RuntimeError(f"{path}: no PointCloud2 or CustomMsg topic") + return topics + + +def rosbags_convert(sources: list[Path], dst: Path, *args: str) -> None: + """python -m rosbags.convert; dst ending in .bag is a ROS1 bag, otherwise a rosbag2 folder.""" + command = [sys.executable, "-m", "rosbags.convert", "--src", *map(str, sources), "--dst", str(dst), *args] + subprocess.run(command, check=True) + + +def to_mcap(sources: list[Path], target: Path, topics: list[str]) -> None: + """The topics of sources as one uncompressed ROS 2 MCAP file at target.""" + folder = target.with_suffix(".rosbag2") + shutil.rmtree(folder, ignore_errors=True) + rosbags_convert(sources, folder, "--dst-storage", "mcap", "--include-topic", *topics) + (mcap,) = folder.glob("*.mcap") + target.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(mcap), target) + shutil.rmtree(folder) + + +def rewrite_mcap(source: Path, target: Path, compression: str, start_ns: int = 0, end_ns: int | None = None) -> None: + """Copies the messages of source with log time in [start_ns, end_ns) into target with this chunk compression.""" + from mcap.reader import make_reader + from mcap.writer import CompressionType, Writer + + target.parent.mkdir(parents=True, exist_ok=True) + with open(source, "rb") as src, open(target, "wb") as out: + reader = make_reader(src) + header = reader.get_header() + writer = Writer(out, compression=CompressionType[compression.upper()]) + writer.start(profile=header.profile, library="hdmapping-bag-campaign") + schemas: dict[int, int] = {} + channels: dict[int, int] = {} + for schema, channel, message in reader.iter_messages(start_time=start_ns, ending_before=end_ns, log_time_order=True): + if schema and schema.id not in schemas: + schemas[schema.id] = writer.register_schema(schema.name, schema.encoding, schema.data) + if channel.id not in channels: + channels[channel.id] = writer.register_channel( + channel.topic, channel.message_encoding, schemas.get(channel.schema_id, 0), channel.metadata + ) + writer.add_message(channels[channel.id], message.log_time, message.data, message.publish_time, message.sequence) + writer.finish() + + +def prepare_recording(recording: Recording, data: Path) -> None: + source = source_file(recording, data) + topics = find_topics(source, recording.imu_topic) + log(f"{recording.name}: IMU {topics.imu}, lidar {topics.lidars}") + for label, lidar in topics.lidars.items(): + base = data / "variants" / recording.name / label + if (base / ".complete").exists(): + log(f"{recording.name}/{label}: variants already prepared") + continue + shutil.rmtree(base, ignore_errors=True) + name = recording.name + plain = base / "mcap_none" / f"{name}.mcap" + log(f"{recording.name}/{label}: MCAP, uncompressed") + to_mcap([source], plain, [lidar, topics.imu]) + for compression in ("lz4", "zstd"): + log(f"{recording.name}/{label}: MCAP, {compression}") + rewrite_mcap(plain, base / f"mcap_{compression}" / f"{name}.mcap", compression) + for compression in ("none", "bz2", "lz4"): + log(f"{recording.name}/{label}: ROS1 bag, {compression}") + target = base / f"ros1_{compression}" / f"{name}.bag" + target.parent.mkdir(parents=True, exist_ok=True) + rosbags_convert([plain], target, *([] if compression == "none" else ["--compress", compression])) + + # one recording in several files, the last part in a subfolder: dropped folders are searched recursively + log(f"{recording.name}/{label}: split into {SPLIT_PARTS} files (MCAP zstd, ROS1 bz2)") + step = (topics.end_ns - topics.start_ns) // SPLIT_PARTS + 1 + for k in range(SPLIT_PARTS): + sub = f"part_{k}" if k == SPLIT_PARTS - 1 else "" + start = topics.start_ns + k * step + part = base / f"split{SPLIT_PARTS}_mcap_zstd" / sub / f"{name}_{k}.mcap" + rewrite_mcap(plain, part, "zstd", start, start + step) + bag = base / f"split{SPLIT_PARTS}_ros1_bz2" / sub / f"{name}_{k}.bag" + bag.parent.mkdir(parents=True, exist_ok=True) + rosbags_convert([part], bag, "--compress", "bz2") + (base / ".complete").write_text(f"lidar {lidar}\nimu {topics.imu}\nsource {source}\n") + + +# -------------------------------------------------------------------------------------------------------------------- +# run + + +@dataclass +class Result: + recording: str + lidar: str + variant: str + files: int + size_mb: float + imu_s: float | None = None + points_s: float | None = None + total_s: float | None = None + imu_samples: int | None = None + points: int | None = None + status: str = "" + + +def variant_input(folder: Path) -> tuple[Path, int, float]: + """The path step 1 opens for a variant (the file, or the folder of a split recording), its file count and size.""" + files = sorted(p for p in folder.rglob("*") if p.suffix in (".bag", ".mcap")) + size = sum(p.stat().st_size for p in files) / 1e6 + return (files[0] if len(files) == 1 else folder), len(files), size + + +def campaign_params(step1: Path, data: Path) -> Path: + """Step 1's default parameters with skip_first_file off: with it on, step 1 drops the first chunk's points, and a + recording split into files shorter than a chunk drops a different share, so the point counts would not compare.""" + params = data / "params_campaign.toml" + subprocess.run([str(step1), "--dump-default-params", str(params)], check=True, stdout=subprocess.DEVNULL) + text = params.read_text(encoding="utf-8") + if "skip_first_file = true" not in text: + raise RuntimeError(f"{params}: no 'skip_first_file = true' to turn off") + params.write_text(text.replace("skip_first_file = true", "skip_first_file = false"), encoding="utf-8") + return params + + +def run_step1(step1: Path, params: Path | None, folder: Path, timeout_s: float, full: bool, logs: Path) -> Result: + recording, lidar, variant = folder.parts[-3:] + path, files, size = variant_input(folder) + result = Result(recording, lidar, variant, files, round(size, 1)) + before = set(folder.iterdir()) + log_file = logs / f"{recording}__{lidar}__{variant}.log" + log(f"{recording}/{lidar}/{variant}: loading {files} file(s), {size:.0f} MB") + + start = time.monotonic() + with open(log_file, "w", encoding="utf-8", errors="replace") as out: + # with a parameter file step 1 also needs an output folder; it is inside the variant's folder, removed below + command = [str(step1), str(path)] + ([str(params), str(folder / "campaign_output")] if params else []) + process = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + cwd=folder, + ) + assert process.stdout + try: + for line in process.stdout: + out.write(line) + now = time.monotonic() - start + if result.imu_s is None and line.startswith("Loading point clouds"): + result.imu_s = round(now, 2) + if match := re.match(r"IMU samples: (\d+)", line): + result.imu_samples = int(match.group(1)) + if match := re.match(r"TOTAL: (\d+)", line): + result.points = int(match.group(1)) + if "loading finished" in line: + result.total_s = round(now, 2) + if result.imu_s is not None: + result.points_s = round(result.total_s - result.imu_s, 2) + if not full: + break + if now > timeout_s: + result.status = f"timeout after {timeout_s:.0f} s" + break + finally: + if process.poll() is None: + process.kill() + process.wait() + if full and not result.status: + result.status = f"exit {process.returncode} after {time.monotonic() - start:.0f} s" + elif not result.status: + result.status = "loaded" if result.total_s is not None else f"failed (exit {process.returncode}), see {log_file.name}" + + if not full: # the run's lio_result_*, preview/ and cache/ + for entry in set(folder.iterdir()) - before: + shutil.rmtree(entry, ignore_errors=True) if entry.is_dir() else entry.unlink(missing_ok=True) + log(f" {result.status}: total {result.total_s} s (IMU {result.imu_s} s), {result.points} points, {result.imu_samples} IMU samples") + return result + + +def check_consistency(results: list[Result]) -> list[str]: + """Variants of one recording and lidar topic that load different point or IMU sample counts.""" + problems = [] + groups: dict[tuple[str, str], list[Result]] = {} + for r in results: + groups.setdefault((r.recording, r.lidar), []).append(r) + for (recording, lidar), group in groups.items(): + for key in ("points", "imu_samples"): + values = {getattr(r, key) for r in group if r.status == "loaded"} + if len(values) > 1: + detail = ", ".join(f"{r.variant}={getattr(r, key)}" for r in group if r.status == "loaded") + problems.append(f"{recording}/{lidar}: {key} differ: {detail}") + return problems + + +def write_results(results: list[Result], problems: list[str], data: Path, step1: Path, params: Path | None) -> None: + with open(data / "results.csv", "w", newline="") as f: + writer = csv.writer(f) + writer.writerow(Result.__dataclass_fields__.keys()) + for r in results: + writer.writerow(r.__dict__.values()) + lines = [ + f"# Bag loading campaign, {datetime.datetime.now():%Y-%m-%d %H:%M}", + "", + f"- step 1: `{step1}`" + ("" if params else " (default parameters)"), + f"- machine: {platform.platform()}, {os.cpu_count()} logical CPUs", + "", + "| recording | lidar | variant | files | MB | IMU s | points s | total s | points | IMU samples | status |", + "|---|---|---|---:|---:|---:|---:|---:|---:|---:|---|", + ] + for r in results: + lines.append( + f"| {r.recording} | {r.lidar} | {r.variant} | {r.files} | {r.size_mb} | {r.imu_s} | {r.points_s} | {r.total_s} " + f"| {r.points} | {r.imu_samples} | {r.status} |" + ) + lines += ["", "## Consistency", ""] + ([f"- {p}" for p in problems] or ["- every variant loads the same data"]) + (data / "results.md").write_text("\n".join(lines) + "\n", encoding="utf-8") + print("\n".join(lines)) + + +def find_step1(explicit: str | None) -> Path: + if explicit: # absolute: step 1 runs in each variant's folder + return Path(explicit).resolve() + repository = Path(__file__).resolve().parent.parent + names = ["lidar_odometry_step_1.exe", "lidar_odometry_step_1"] + for folder in ["build/bin", "build/bin/Release", "build/bin/RelWithDebInfo", "build/Release", "build"]: + for name in names: + candidate = repository / folder / name + if candidate.is_file(): + return candidate + on_path = shutil.which("lidar_odometry_step_1") + if on_path: + return Path(on_path) + raise SystemExit("lidar_odometry_step_1 not found; pass --step1 ") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("steps", nargs="*", help="download, prepare, run (default: all three)") + parser.add_argument("--data", default=str(Path.home() / "hdmapping_bag_campaign"), help="working folder (default: %(default)s)") + parser.add_argument("--step1", help="lidar_odometry_step_1 executable (default: found in build/)") + parser.add_argument("--large", action="store_true", help="include the large recordings (Hilti 2022, 6.3 GB download)") + parser.add_argument("--only", nargs="+", help="only these recordings (names as in --list)") + parser.add_argument("--variants", nargs="+", help="only these variants, e.g. ros1_bz2 mcap_zstd") + parser.add_argument("--full", action="store_true", help="let step 1 process every variant to the end instead of stopping after loading") + parser.add_argument( + "--default-params", action="store_true", help="run step 1 with its defaults (skip_first_file on: split recordings then load fewer points)" + ) + parser.add_argument("--timeout", type=float, default=3600, help="seconds one variant may take (default: %(default)s)") + parser.add_argument("--list", action="store_true", help="list the recordings and exit") + args = parser.parse_args() + + recordings = [r for r in RECORDINGS if (args.large or not r.large) and (not args.only or r.name in args.only)] + if args.list: + for r in RECORDINGS: + print(f"{r.name:20} {r.size_mb:6} MB {r.license:16} {'(--large) ' if r.large else ''}{r.note}\n{'':20} {r.url}") + return 0 + steps = args.steps or ["download", "prepare", "run"] + if unknown := set(steps) - {"download", "prepare", "run"}: + parser.error(f"unknown step(s): {', '.join(sorted(unknown))}") + data = Path(args.data).resolve() + data.mkdir(parents=True, exist_ok=True) + + if "download" in steps: + for r in recordings: + download_recording(r, data) + if "prepare" in steps: + for r in recordings: + prepare_recording(r, data) + if "run" in steps: + step1 = find_step1(args.step1) + params = None if args.default_params else campaign_params(step1, data) + logs = data / "logs" + logs.mkdir(exist_ok=True) + results = [] + for r in recordings: + for lidar in sorted((data / "variants" / r.name).glob("*")): + for folder in sorted(p for p in lidar.iterdir() if p.is_dir()): + if args.variants and folder.name not in args.variants: + continue + results.append(run_step1(step1, params, folder, args.timeout, args.full, logs)) + problems = check_consistency(results) + write_results(results, problems, data, step1, params) + return 1 if problems or any(r.status not in ("loaded",) and not args.full for r in results) else 0 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/bag_loading_campaign.sh b/scripts/bag_loading_campaign.sh new file mode 100755 index 00000000..d1fe2e40 --- /dev/null +++ b/scripts/bag_loading_campaign.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Loading test campaign for ROS1 bags and MCAP files in lidar_odometry_step_1: downloads public recordings, writes them +# in every container and compression, and times step 1's loading of each. See bag_loading_campaign.py --help. +# +# Runs in bash on Linux, macOS and MSYS2 on Windows. Needs Python 3.10 or newer; on Windows the python.org Python +# (the "py" launcher) is used, because native executables need Windows paths and wheels exist for its packages. +# +# scripts/bag_loading_campaign.sh # download, prepare and run, data in ~/hdmapping_bag_campaign +# scripts/bag_loading_campaign.sh --data /d/campaign run --variants ros1_bz2 mcap_zstd +# scripts/bag_loading_campaign.sh --list +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# the Python environment lives in the data folder, next to the downloads +data="$HOME/hdmapping_bag_campaign" +args=("$@") +for ((i = 0; i < ${#args[@]}; i++)); do + if [[ "${args[$i]}" == "--data" && $((i + 1)) -lt ${#args[@]} ]]; then + data="${args[$((i + 1))]}" + fi +done +mkdir -p "$data" + +case "$(uname -s)" in + MINGW* | MSYS* | CYGWIN*) candidates=("py -3" python python3) ;; + *) candidates=(python3 python) ;; +esac +python="" +for candidate in "${candidates[@]}"; do + if $candidate -c 'import sys; sys.exit(sys.version_info < (3, 10))' 2>/dev/null; then + python="$candidate" + break + fi +done +if [[ -z "$python" ]]; then + echo "Python 3.10 or newer not found (on Windows install it from python.org)" >&2 + exit 1 +fi + +venv="$data/.venv" +if [[ ! -d "$venv" ]]; then + echo "Creating a Python environment in $venv" + $python -m venv "$venv" +fi +if [[ -x "$venv/Scripts/python.exe" ]]; then + venv_python="$venv/Scripts/python.exe" +else + venv_python="$venv/bin/python" +fi +if ! "$venv_python" -c 'import rosbags, mcap, lz4, zstandard' 2>/dev/null; then + "$venv_python" -m pip install --quiet --upgrade pip + "$venv_python" -m pip install --quiet rosbags mcap lz4 zstandard +fi + +exec "$venv_python" "$here/bag_loading_campaign.py" "$@" From be86294743151bd5a570862ff56542a27bf08b6b Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 13:34:30 +0100 Subject: [PATCH 09/21] step 1: --gui opens the GUI with the given inputs lidar_odometry_step_1 --gui [...] opens the GUI even when inputs are given; the inputs open as if dropped on the window (a bag opens its options window). Without --gui the command line is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../lidar_odometry_gui.cpp | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp index b3fd7670..06529d18 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry_gui.cpp @@ -3087,6 +3087,7 @@ int main(int argc, char* argv[]) << "USAGE:\n" << std::filesystem::path(argv[0]).stem().string() << " /?\n" << std::filesystem::path(argv[0]).stem().string() << " \n" + << std::filesystem::path(argv[0]).stem().string() << " --gui [...]\n" << std::filesystem::path(argv[0]).stem().string() << " --dump-default-params \n\n" << "where\n" << " Path where scan files are located (*.csv, *.laz, *.sn), or a ROS1 bag\n" @@ -3096,6 +3097,8 @@ int main(int argc, char* argv[]) << " (with alone, default parameters are used and the\n" << " session is stored in the next free /lio_result_N,\n" << " as the GUI does)\n" + << " --gui [...] Open the GUI even with inputs given; the inputs (folders, files,\n" + << " bags) open as if dropped on the window\n" << " --dump-default-params \n" << " Write the default parameters to and exit\n" << " -h, /h, --help, /? Show this help and exit\n\n"; @@ -3130,7 +3133,24 @@ int main(int argc, char* argv[]) } } - if (argc == 2) // running from command line + // --gui opens the GUI whatever else is given; the remaining arguments are recordings to open in it + std::vector gui_args{ argv[0] }; + bool force_gui = false; + for (int i = 1; i < argc; ++i) + { + if (std::string(argv[i]) == "--gui") + force_gui = true; + else + gui_args.push_back(argv[i]); + } + if (force_gui) + { + argc = static_cast(gui_args.size()); + gui_args.push_back(nullptr); + argv = gui_args.data(); + } + + if (argc == 2 && !force_gui) // running from command line { auto path = fs::path(argv[1]); if (RecordingSourceFactory::find({ path })) @@ -3173,7 +3193,7 @@ int main(int argc, char* argv[]) std::cout << "Results and run report saved to: '" << result_dir.string() << "'\n"; } } - else if (argc == 4) // runnning from command line with custom params + else if (argc == 4 && !force_gui) // runnning from command line with custom params { // Load parameters from file using original TomlIO class TomlIO toml_io; @@ -3214,6 +3234,8 @@ int main(int argc, char* argv[]) params.publish_processing_head = publish_processing_head; initGL(&argc, argv, winTitle, display, mouse); trajectory_renderer.init(); + if (force_gui && argc > 1) + openRecording(std::vector(argv + 1, argv + argc)); #ifdef _WIN32 InitTaskbarProgress(); From cf9f76f98b6f198964a5cd15d5232c11d006d8fa Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 14:52:45 +0100 Subject: [PATCH 10/21] rosbags: read uncompressed ROS1 chunks with a wrong size field Some writers put a wrong "size" in the header of an uncompressed chunk (the Livox ROS1 bags of Zenodo record 7780490 have size 1). The record data is the chunk, and rosbag ignores the field too, so the reader no longer rejects such chunks with "uncompressed chunk size mismatch", and no longer allocates the claimed size before copying the data. Co-Authored-By: Claude Opus 5.5 --- rosbags/Ros1Bag.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/rosbags/Ros1Bag.cpp b/rosbags/Ros1Bag.cpp index cc19befe..7d400ec5 100644 --- a/rosbags/Ros1Bag.cpp +++ b/rosbags/Ros1Bag.cpp @@ -248,17 +248,14 @@ void appendConnectionRecord(std::vector& out, const Ros1Connection& c) bool decompress(const std::string& compression, const std::vector& in, size_t out_size, std::vector& out, std::string& error) { - out.resize(out_size); if(compression == "none") { - if(in.size() != out_size) - { - error = "uncompressed chunk size mismatch"; - return false; - } + // The record data is the chunk; some writers put a wrong "size" in the header + // of an uncompressed chunk (e.g. 1), which rosbag itself ignores too. out = in; return true; } + out.resize(out_size); if(compression == "bz2") { unsigned int dst = static_cast(out_size); From 9b22c6857a05702dc608f29f4ec8c17762ea7965 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 14:52:45 +0100 Subject: [PATCH 11/21] bag_loading_campaign: more PointCloud2 lidars, zip archives, MCAP recovery - New recordings from Zenodo: Ouster OS0-32 and a Livox Mid-360, and with --large an Ouster OS0-64 and a Velodyne recorded from a drone (zip). - Archives may be .tar.gz or .zip and may hold .bag or .mcap files. - An MCAP file cut short (no footer, so no index, as the Mid-360 upload) is recovered into an indexed copy, as `mcap recover` does. Co-Authored-By: Claude Opus 5.5 --- scripts/bag_loading_campaign.py | 128 ++++++++++++++++++++++++++++---- 1 file changed, 114 insertions(+), 14 deletions(-) diff --git a/scripts/bag_loading_campaign.py b/scripts/bag_loading_campaign.py index 479fb640..c59e3df0 100755 --- a/scripts/bag_loading_campaign.py +++ b/scripts/bag_loading_campaign.py @@ -28,6 +28,7 @@ import tarfile import time import urllib.request +import zipfile from dataclasses import dataclass, field from pathlib import Path @@ -41,7 +42,7 @@ class Recording: size_mb: int license: str note: str - archive: bool = False # a .tar.gz holding several bags; the smallest one is used + archive: str = "" # "tar.gz" or "zip" holding several recordings; the smallest .bag or .mcap is used large: bool = False # downloaded only with --large imu_topic: str = "" # empty: the IMU topic with the most messages @@ -60,7 +61,39 @@ class Recording: size_mb=1945, license="CC-BY-4.0", note="Koide LiDAR-camera calibration dataset (Zenodo 7780490), ROS1 bag: Livox Avia PointCloud2 and CustomMsg + IMU", - archive=True, + archive="tar.gz", + ), + Recording( + name="koide_os0_32", + url="https://zenodo.org/api/records/6864654/files/os0-32.bag/content", + size_mb=747, + license="CC-BY-4.0", + note="LiDAR-IMU mapping test (Zenodo 6864654), ROS1 bag: Ouster OS0-32 PointCloud2 + IMU", + ), + Recording( + name="koide_mid360", + url="https://zenodo.org/api/records/21486938/files/mid360_01.tar.gz/content", + size_mb=160, + license="CC-BY-4.0", + note="LiDAR-IMU mapping test (Zenodo 21486938): Livox Mid-360 + IMU", + archive="tar.gz", + ), + Recording( + name="koide_os0_64", + url="https://zenodo.org/api/records/6864654/files/os0-64.bag/content", + size_mb=1745, + license="CC-BY-4.0", + note="LiDAR-IMU mapping test (Zenodo 6864654), ROS1 bag: Ouster OS0-64 PointCloud2 + IMU", + large=True, + ), + Recording( + name="aeroarms_velodyne", + url="https://zenodo.org/api/records/2648635/files/USE_AEROARMS_Multisensor_Dataset.zip/content", + size_mb=2936, + license="CC-BY-4.0", + note="AEROARMS multi-sensor dataset (Zenodo 2648635), ROS1 bag from a drone: Velodyne PointCloud2 + IMU", + archive="zip", + large=True, ), Recording( name="hilti2022_exp14", @@ -113,32 +146,49 @@ def download(url: str, target: Path) -> None: log(f"{target.name}: downloaded {done >> 20} MB") +def download_name(recording: Recording) -> str: + """File name of the download: Zenodo URLs end in .../files//content.""" + parts = Path(recording.url).parts + return parts[-2] if parts[-1] == "content" else parts[-1] + + +def recordings_in(folder: Path) -> list[Path]: + """The .bag and .mcap files below folder, smallest first.""" + if not folder.exists(): + return [] + files = [p for p in folder.rglob("*") if p.suffix in (".bag", ".mcap") and p.is_file() and not p.stem.endswith("_recovered")] + return sorted(files, key=lambda p: p.stat().st_size) + + def source_file(recording: Recording, data: Path) -> Path: """The downloaded recording, extracted from its archive when it is one.""" downloads = data / "downloads" / recording.name if not recording.archive: - return downloads / Path(recording.url).name - extracted = downloads / "extracted" - bags = sorted(extracted.rglob("*.bag"), key=lambda p: p.stat().st_size) if extracted.exists() else [] - if not bags: - raise RuntimeError(f"{recording.name}: no .bag in {extracted}; run the download step") - return bags[0] + return downloads / download_name(recording) + extracted = recordings_in(downloads / "extracted") + if not extracted: + raise RuntimeError(f"{recording.name}: no .bag or .mcap in {downloads / 'extracted'}; run the download step") + return extracted[0] def download_recording(recording: Recording, data: Path) -> None: downloads = data / "downloads" / recording.name if not recording.archive: - download(recording.url, downloads / Path(recording.url).name) + download(recording.url, downloads / download_name(recording)) return - archive = downloads / f"{recording.name}.tar.gz" + archive = downloads / f"{recording.name}.{recording.archive}" extracted = downloads / "extracted" - if extracted.exists() and any(extracted.rglob("*.bag")): + if recordings_in(extracted): log(f"{recording.name}: already extracted") return download(recording.url, archive) log(f"{recording.name}: extracting {archive.name}") - with tarfile.open(archive) as tar: - tar.extractall(extracted, filter="data") + if recording.archive == "zip": + with zipfile.ZipFile(archive) as zip_file: + zip_file.extractall(extracted) + else: + with tarfile.open(archive) as tar: + tar.extractall(extracted, filter="data") # -------------------------------------------------------------------------------------------------------------------- @@ -214,8 +264,58 @@ def rewrite_mcap(source: Path, target: Path, compression: str, start_ns: int = 0 writer.finish() -def prepare_recording(recording: Recording, data: Path) -> None: +def recover_mcap(source: Path, target: Path) -> int: + """Copies the messages of a truncated MCAP file (no footer, so no index) into an indexed one, as `mcap recover` does: + the records are read in file order up to the cut. Returns the number of messages recovered.""" + from mcap.records import Channel, Message, Schema + from mcap.stream_reader import StreamReader + from mcap.writer import CompressionType, Writer + + partial = target.with_name(target.name + ".part") + count = 0 + with open(source, "rb") as src, open(partial, "wb") as out: + writer = Writer(out, compression=CompressionType.NONE) + writer.start(profile="ros2", library="hdmapping-bag-campaign recover") + schemas: dict[int, int] = {} + channels: dict[int, int] = {} + try: + for record in StreamReader(src).records: + if isinstance(record, Schema): + schemas[record.id] = writer.register_schema(record.name, record.encoding, record.data) + elif isinstance(record, Channel): + channels[record.id] = writer.register_channel( + record.topic, record.message_encoding, schemas.get(record.schema_id, 0), record.metadata + ) + elif isinstance(record, Message) and record.channel_id in channels: + writer.add_message(channels[record.channel_id], record.log_time, record.data, record.publish_time, record.sequence) + count += 1 + except Exception as error: # the cut: a record or chunk that ends early + log(f"{source.name}: stopped at the cut ({type(error).__name__}: {error})") + writer.finish() + partial.rename(target) + return count + + +def readable_source(recording: Recording, data: Path) -> Path: + """The recording's file, or a recovered copy of a truncated MCAP file.""" + from rosbags.highlevel import AnyReader + source = source_file(recording, data) + try: + with AnyReader([source]): + return source + except Exception as error: + if source.suffix != ".mcap": + raise + recovered = source.with_name(source.stem + "_recovered.mcap") + if not recovered.exists(): + log(f"{recording.name}: {source.name} cannot be read ({error}); recovering it as `mcap recover` would") + log(f"{recording.name}: recovered {recover_mcap(source, recovered)} messages into {recovered.name}") + return recovered + + +def prepare_recording(recording: Recording, data: Path) -> None: + source = readable_source(recording, data) topics = find_topics(source, recording.imu_topic) log(f"{recording.name}: IMU {topics.imu}, lidar {topics.lidars}") for label, lidar in topics.lidars.items(): From f7d4f687a643827a06afaf84d3c6528480c83083 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 16:27:04 +0100 Subject: [PATCH 12/21] Add hesai_pcap_to_laz: Hesai pcap / lidar_recorder session -> mandeye session Converts Hesai captures (.pcap, or zstd-compressed .pcap.zst as lidar_recorder writes them) into a mandeye session directory, like mcap_to_laz and ouster_pcap_to_laz. A lidar_recorder session directory stands for its lidarNNNN.pcap.zst chunks, and its gnssNNNN.nmea files are copied next to the result. - 3rdparty/HesaiLidar_SDK_2.0 (v2.0.11, shallow submodule) decodes the packets with the lidar's angle correction. It is built with BUILD_WITH_CLI_TOOLS only and without PTCS (no OpenSSL needed). On macOS cmake/hesai_macos_compat supplies and the Linux serial ioctls the SDK names. - rosbags/PcapUdpReader: the pcap layer of OusterPcapReader (link types, IPv4 fragment reassembly) moved into its own class, which also reads zstd-compressed captures. OusterPcapReader uses it; its tests pass unchanged. - rosbags/MandeyeSessionChunker: mcap_to_laz's chunking (absolute time bins, IMU samples routed into the chunk open at their time) as a class on top of MandeyeSessionWriter. - Points keep the ring as the LAS "ring" attribute; IMU acceleration is in g and angular velocity is converted to rad/s, as mandeye_controller's Hesai client does. Tested on a JT128 lidar_recorder session: the same 24.6 M points and 13,875 IMU samples as the prototype converter, and lidar_odometry_step_1 runs through on the result. Co-Authored-By: Claude Opus 5.5 --- .gitmodules | 4 + 3rdparty/HesaiLidar_SDK_2.0 | 1 + apps/console_tools/CMakeLists.txt | 26 + apps/console_tools/hesai_pcap_to_laz.cpp | 352 ++++++++++++++ cmake/dependencies.cmake | 32 ++ cmake/hesai_macos_compat/endian.h | 15 + cmake/hesai_macos_compat/hesai_macos_compat.h | 8 + deploy_mandeye.bat | 2 +- rosbags/MandeyeSessionChunker.cpp | 99 ++++ rosbags/MandeyeSessionChunker.h | 66 +++ rosbags/OusterPcapReader.cpp | 294 ++---------- rosbags/PcapUdpReader.cpp | 450 ++++++++++++++++++ rosbags/PcapUdpReader.h | 68 +++ rosbags/tests/CMakeLists.txt | 6 +- rosbags/tests/pcap_test_frames.h | 90 ++++ rosbags/tests/test_ouster_pcap_reader.cpp | 73 +-- rosbags/tests/test_pcap_udp_reader.cpp | 142 ++++++ 17 files changed, 1402 insertions(+), 326 deletions(-) create mode 160000 3rdparty/HesaiLidar_SDK_2.0 create mode 100644 apps/console_tools/hesai_pcap_to_laz.cpp create mode 100644 cmake/hesai_macos_compat/endian.h create mode 100644 cmake/hesai_macos_compat/hesai_macos_compat.h create mode 100644 rosbags/MandeyeSessionChunker.cpp create mode 100644 rosbags/MandeyeSessionChunker.h create mode 100644 rosbags/PcapUdpReader.cpp create mode 100644 rosbags/PcapUdpReader.h create mode 100644 rosbags/tests/pcap_test_frames.h create mode 100644 rosbags/tests/test_pcap_udp_reader.cpp diff --git a/.gitmodules b/.gitmodules index 7de2dc52..d07f140f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -77,3 +77,7 @@ path = 3rdparty/bzip2 url = https://gitlab.com/bzip2/bzip2.git shallow = true +[submodule "3rdparty/HesaiLidar_SDK_2.0"] + path = 3rdparty/HesaiLidar_SDK_2.0 + url = https://github.com/HesaiTechnology/HesaiLidar_SDK_2.0.git + shallow = true diff --git a/3rdparty/HesaiLidar_SDK_2.0 b/3rdparty/HesaiLidar_SDK_2.0 new file mode 160000 index 00000000..3346e74c --- /dev/null +++ b/3rdparty/HesaiLidar_SDK_2.0 @@ -0,0 +1 @@ +Subproject commit 3346e74cd8a756e2834e9e085028bfea8b8296df diff --git a/apps/console_tools/CMakeLists.txt b/apps/console_tools/CMakeLists.txt index e09ccc8b..7828e2dd 100644 --- a/apps/console_tools/CMakeLists.txt +++ b/apps/console_tools/CMakeLists.txt @@ -184,6 +184,7 @@ endif() add_executable( ouster_pcap_to_laz ouster_pcap_to_laz.cpp ${REPOSITORY_DIRECTORY}/rosbags/OusterPcapReader.h ${REPOSITORY_DIRECTORY}/rosbags/OusterPcapReader.cpp + ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.h ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.cpp ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionWriter.h ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionWriter.cpp ) @@ -197,6 +198,7 @@ target_link_libraries( ouster_pcap_to_laz PRIVATE spdlog::spdlog + hdmapping_zstd ${PLATFORM_LASZIP_LIB} ${PLATFORM_MISCELLANEOUS_LIBS}) @@ -204,6 +206,29 @@ if (MSVC) target_compile_options(laz_to_mcap PRIVATE /bigobj) endif() +# hesai_pcap_to_laz: Hesai pcap (or a lidar_recorder session of .pcap.zst chunks) -> mandeye session directory. +# Same writer and chunking as mcap_to_laz; the packets are decoded by the Hesai LiDAR SDK (3rdparty/HesaiLidar_SDK_2.0). +add_executable( + hesai_pcap_to_laz hesai_pcap_to_laz.cpp + ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.h ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.cpp + ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionWriter.h ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionWriter.cpp + ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionChunker.h ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionChunker.cpp +) + +target_include_directories( + hesai_pcap_to_laz + PRIVATE ${REPOSITORY_DIRECTORY}/rosbags + ${LASZIP_INCLUDE_DIR}/LASzip/include) + +target_link_libraries( + hesai_pcap_to_laz + PRIVATE + hesai_sdk + hdmapping_zstd + spdlog::spdlog + ${PLATFORM_LASZIP_LIB} + ${PLATFORM_MISCELLANEOUS_LIBS}) + # bow_loop_closure_detect: headless verification tool for the automatic # image-based (fbow) loop closure detector shared with step 2's GUI -- # loads a step-2 session + a CAMERA_0 folder and prints candidate pairs as @@ -336,5 +361,6 @@ hdmapping_install_app( laz_to_mcap mcap_to_laz ouster_pcap_to_laz + hesai_pcap_to_laz session_intensity_panoramas session_to_mcap) diff --git a/apps/console_tools/hesai_pcap_to_laz.cpp b/apps/console_tools/hesai_pcap_to_laz.cpp new file mode 100644 index 00000000..3f8f295c --- /dev/null +++ b/apps/console_tools/hesai_pcap_to_laz.cpp @@ -0,0 +1,352 @@ +// hesai_pcap_to_laz: Hesai pcap captures (.pcap, or zstd-compressed .pcap.zst as lidar_recorder writes them) -> +// mandeye session directory, as mcap_to_laz and ouster_pcap_to_laz write one. +// +// UDP payloads are pushed straight into the Hesai LiDAR SDK's decoder with the lidar's angle correction; points and IMU +// samples come out on the lidar clock and are converted as mandeye_controller's Hesai client does (acceleration in g, +// angular velocity deg/s -> rad/s). A lidar_recorder session directory stands for its lidarNNNN.pcap.zst chunks, and +// its gnssNNNN.nmea files (lidar-clock times, already in the mandeye format) are copied next to the result. + +// See rosbags/McapWriter.h: the rosbags headers come before any standard header. +#include "MandeyeSessionChunker.h" +#include "MandeyeSessionWriter.h" +#include "PcapUdpReader.h" + +#include "hesai_lidar_sdk.hpp" + +#include "console_progress.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using namespace hesai::lidar; + +namespace +{ + // lidarNNNN.pcap.zst (or .pcap when there is no .zst of the same chunk) of a lidar_recorder session, in order. + // Incomplete .part chunks are skipped. + std::vector sessionChunks(const fs::path& dir) + { + std::vector zst, plain; + for (const auto& e : fs::directory_iterator(dir)) + { + const std::string n = e.path().filename().string(); + if (n.rfind("lidar", 0) != 0) + continue; + if (n.ends_with(".pcap.zst")) + zst.push_back(e.path()); + else if (n.ends_with(".pcap")) + plain.push_back(e.path()); + else if (n.ends_with(".part")) + spdlog::warn("Skipping incomplete chunk {}", n); + } + for (const auto& p : plain) + if (std::find(zst.begin(), zst.end(), fs::path(p.string() + ".zst")) == zst.end()) + zst.push_back(p); + std::sort(zst.begin(), zst.end()); + return zst; + } + + void print_usage(const char* argv0) + { + spdlog::error("Usage: {} [ ...] [options]", argv0); + spdlog::error(" input a Hesai capture (classic pcap, optionally zstd-compressed as a whole), or a"); + spdlog::error(" lidar_recorder session directory (its lidarNNNN.pcap.zst chunks, in order);"); + spdlog::error(" several inputs are read in the order given into one session"); + spdlog::error(" output_session_dir written as mandeye lidarNNNN.laz + imuNNNN.csv chunk pairs,"); + spdlog::error(" ready to open in lidar_odometry_step_1"); + spdlog::error("Options:"); + spdlog::error(" --chunk-seconds chunk length in seconds (default: 10, mandeye's own"); + spdlog::error(" cadence; 0 = one single chunk)"); + spdlog::error(" --correction the lidar's angle correction (default: correction.dat next to"); + spdlog::error(" the first input)"); + spdlog::error(" --udp-port point cloud UDP destination port (default: 2368)"); + spdlog::error(""); + spdlog::error("The lidar ring is kept as the LAS extra-bytes attribute 'ring'. No calibration.json or .sn"); + spdlog::error("file is written, so lidar_odometry_step_1 applies no extrinsics to the result."); + } +} // namespace + +int main(const int argc, const char** argv) +{ + std::vector positionals; + double chunk_seconds = 10.0; + fs::path correction; + int udp_port = 2368; + + for (int i = 1; i < argc; ++i) + { + const std::string arg = argv[i]; + const bool hasValue = i + 1 < argc; + if (arg == "--chunk-seconds" && hasValue) + { + const std::string value = argv[++i]; + try + { + chunk_seconds = std::stod(value); + } catch (const std::exception&) + { + spdlog::error("Invalid --chunk-seconds '{}' (expected a number)", value); + return EXIT_FAILURE; + } + if (!std::isfinite(chunk_seconds) || chunk_seconds < 0.0) + { + spdlog::error("Invalid --chunk-seconds '{}' (expected >= 0; 0 = one single chunk)", value); + return EXIT_FAILURE; + } + } + else if (arg == "--correction" && hasValue) + correction = argv[++i]; + else if (arg == "--udp-port" && hasValue) + { + const std::string value = argv[++i]; + try + { + udp_port = std::stoi(value); + } catch (const std::exception&) + { + spdlog::error("Invalid --udp-port '{}' (expected a number)", value); + return EXIT_FAILURE; + } + } + else if (!arg.starts_with("--")) + positionals.push_back(arg); + else + { + spdlog::error("Unrecognized argument '{}'", arg); + print_usage(argv[0]); + return EXIT_FAILURE; + } + } + + // Every positional is an input except the last, the session dir. + if (positionals.size() < 2) + { + print_usage(argv[0]); + return EXIT_FAILURE; + } + const fs::path session_dir = positionals.back(); + positionals.pop_back(); + + // A lidar_recorder session directory stands for its chunks; its metadata and GNSS files live next to them. + std::vector inputs; + std::vector recorder_dirs; + for (const auto& input : positionals) + { + if (fs::is_directory(input)) + { + const auto chunks = sessionChunks(input); + if (chunks.empty()) + { + spdlog::error("No lidarNNNN.pcap.zst or .pcap in {}", input); + return EXIT_FAILURE; + } + inputs.insert(inputs.end(), chunks.begin(), chunks.end()); + recorder_dirs.emplace_back(input); + } + else if (!fs::exists(input)) + { + spdlog::error("Input file {} does not exist", input); + return EXIT_FAILURE; + } + else + inputs.emplace_back(input); + } + if (correction.empty()) + correction = + (fs::is_directory(positionals.front()) ? fs::path(positionals.front()) : inputs.front().parent_path()) / "correction.dat"; + if (!fs::is_regular_file(correction)) + { + spdlog::error("No angle correction at {} - pass --correction", correction.string()); + return EXIT_FAILURE; + } + + rosbags::MandeyeSessionWriter writer(session_dir, /*with_rgb=*/false, /*with_ring=*/true); + if (!writer.isOpen()) + { + spdlog::error("Cannot write session directory: {}", writer.error()); + return EXIT_FAILURE; + } + rosbags::MandeyeSessionChunker chunker(writer, chunk_seconds); + spdlog::info("Reading {} input(s) with angle correction {}", inputs.size(), correction.string()); + + // Both SDK callbacks run on the SDK's single processing thread, so the chunker needs no locking. + std::atomic write_ok{ true }; + uint64_t frames = 0; + std::vector points; + HesaiLidarSdk sdk; + sdk.RegRecvCallback( + std::function&)>( + [&](const LidarDecodedFrame& frame) + { + points.clear(); + points.reserve(frame.points_num); + for (uint32_t i = 0; i < frame.points_num; ++i) + { + const auto& p = frame.points[i]; + if (p.x == 0.f && p.y == 0.f && p.z == 0.f) + continue; // a "no return" slot, which the SDK still emits at the origin + rosbags::McapPoint out; + out.x = p.x; + out.y = p.y; + out.z = p.z; + out.intensity = static_cast(p.intensity); + out.ring = p.ring; + out.timestamp = p.timestamp; + points.push_back(out); + } + if (!points.empty() && write_ok && !chunker.addPoints(points)) + write_ok = false; + ++frames; + })); + sdk.RegRecvCallback( + std::function( + [&](const LidarImuData& d) + { + // SDK units: acceleration in g, angular velocity in deg/s; mandeye stores g and rad/s. + constexpr double kDegToRad = std::numbers::pi / 180.0; + rosbags::McapImuSample s; + s.timestamp = d.timestamp; + s.acc_x = static_cast(d.imu_accel_x); + s.acc_y = static_cast(d.imu_accel_y); + s.acc_z = static_cast(d.imu_accel_z); + s.gyro_x = static_cast(d.imu_ang_vel_x * kDegToRad); + s.gyro_y = static_cast(d.imu_ang_vel_y * kDegToRad); + s.gyro_z = static_cast(d.imu_ang_vel_z * kDegToRad); + chunker.addImu(s); + })); + + DriverParam param; + param.input_param.source_type = DATA_FROM_ROS_PACKET; // packets are pushed in below + param.input_param.correction_file_path = correction.string(); + param.decoder_param.pcap_play_in_loop = false; + sdk.Init(param); // returns at once; its init thread takes the first packet to detect the model + + // Reader: pushes the point cloud UDP payloads into the SDK's packet ring, waiting while it is full. + std::atomic read_ok{ true }; + uint64_t pushed = 0; + std::thread reader( + [&] + { + uint64_t input_bytes = 0; + for (const auto& path : inputs) + { + std::error_code ec; + input_bytes += fs::file_size(path, ec); + } + ConsoleProgress progress("Reading pcap (bytes)", input_bytes); + uint64_t bytes_before = 0; + for (const auto& path : inputs) + { + rosbags::PcapUdpReader pcap(path); + if (!pcap.isOpen()) + { + spdlog::error("Cannot read {}: {}", path.string(), pcap.error()); + read_ok = false; + continue; + } + const bool ok = pcap.read( + [&](const rosbags::UdpDatagram& d) + { + progress.update(bytes_before + pcap.stats().compressed_bytes_read); + if (d.dst_port != udp_port) + return; + while (sdk.OriginPacketIsBufferFull()) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + sdk.PushOriginPacketBuffer(d.payload, static_cast(d.size), static_cast(d.capture_time_ns / 1000)); + ++pushed; + }); + if (!ok) + { + spdlog::warn("{}: {} - kept what was read", path.string(), pcap.error()); + read_ok = false; + } + if (pcap.stats().dropped_fragments > 0) + spdlog::warn( + "{}: {} IP fragment(s) dropped: their datagram never completed (packet loss during capture)", + path.string(), + pcap.stats().dropped_fragments); + bytes_before += pcap.stats().compressed_bytes_read; + } + progress.finish(bytes_before); + }); + + sdk.Start(); // blocks until the decoder is initialised + reader.join(); + if (sdk.lidar_ptr_->GetInitFinish(FailInit)) + { + spdlog::error("The Hesai SDK failed to initialise (no point packets on UDP port {}?)", udp_port); + sdk.Stop(); + return EXIT_FAILURE; + } + // Let the decoder drain the ring, then give the parser a moment for the last frame. + while (!sdk.lidar_ptr_->origin_packets_buffer_.empty()) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + sdk.Stop(); + + if (!write_ok) + { + spdlog::error("Failed writing lidar chunks: {}", writer.error()); + return EXIT_FAILURE; + } + if (chunker.chunks() == 0) + { + spdlog::error("No points decoded from {} packet(s) on UDP port {} - nothing to write", pushed, udp_port); + return EXIT_FAILURE; + } + if (!chunker.finish()) + { + spdlog::error("Failed writing IMU chunks: {}", writer.error()); + return EXIT_FAILURE; + } + + spdlog::info( + "Wrote {} chunk(s) to {}: {} point(s) from {} frame(s), {} IMU sample(s)", + chunker.chunks(), + session_dir.string(), + writer.pointsWritten(), + frames, + writer.imuSamplesWritten()); + if (chunker.outOfOrder()) + spdlog::warn("Frames were not in ascending time order - chunk boundaries may not be monotonic"); + // lidar_odometry_step_1's load_data() needs more than two input files and then discards the first chunk's points + // outright, so a session of one or two chunks contributes little or nothing there. + if (chunker.chunks() < 3) + spdlog::warn( + "Only {} chunk(s): lidar_odometry_step_1 requires more than two files and discards the first chunk's points - " + "use a smaller --chunk-seconds", + chunker.chunks()); + + // lidar_recorder's GNSS files (gnssNNNN.nmea, lidar-clock times) are already in the mandeye format. + int nmea = 0; + for (const auto& dir : recorder_dirs) + { + std::error_code ec; + for (const auto& e : fs::directory_iterator(dir, ec)) + { + const auto name = e.path().filename().string(); + if (e.is_regular_file() && name.rfind("gnss", 0) == 0 && e.path().extension() == ".nmea") + { + fs::copy_file(e.path(), session_dir / name, fs::copy_options::overwrite_existing, ec); + if (ec) + spdlog::warn("Cannot copy {}: {}", e.path().string(), ec.message()); + else + ++nmea; + } + } + } + if (nmea > 0) + spdlog::info("Copied {} gnssNNNN.nmea file(s) to {}", nmea, session_dir.string()); + return read_ok ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index b1897aab..060f921f 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -361,6 +361,15 @@ endif() # mcap - support for ROS 2 bag export add_subdirectory(${THIRDPARTY_DIRECTORY}/mcap) +# rosbags/PcapUdpReader reads zstd-compressed captures (.pcap.zst): the same libzstd as mcap. +add_library(hdmapping_zstd INTERFACE) +if(WIN32) + target_link_libraries(hdmapping_zstd INTERFACE zstd_static) +else() + target_link_libraries(hdmapping_zstd INTERFACE ${MCAP_ZSTD_LIBRARY}) + target_include_directories(hdmapping_zstd INTERFACE ${MCAP_ZSTD_INCLUDE_DIR}) +endif() + # rosbags/Ros1Bag reads bz2 and lz4 chunks (lz4 comes with the mcap target). add_library(ros1bag_compression INTERFACE) if(WIN32) @@ -370,5 +379,28 @@ else() target_link_libraries(ros1bag_compression INTERFACE BZip2::BZip2) endif() +# Hesai LiDAR SDK 2.0 (hesai_pcap_to_laz): decodes Hesai point and IMU packets with the lidar's angle correction. +# Built without PTCS (TLS to a live sensor, which needs OpenSSL): reading captures needs no connection. The SDK +# supports Linux and Windows; on macOS cmake/hesai_macos_compat supplies and the Linux serial ioctls it +# names, force-included into the SDK and, through the hesai_sdk target, into the files that use it. +if(BUILD_WITH_CLI_TOOLS) + set(WITH_PTCS_USE OFF CACHE BOOL "Hesai SDK: TLS connection to a live sensor (needs OpenSSL)" FORCE) + set(DISENABLE_TEST_CC ON CACHE BOOL "Hesai SDK: skip its sample programs" FORCE) + set(HESAI_SDK_DIRECTORY ${THIRDPARTY_DIRECTORY}/HesaiLidar_SDK_2.0) + if(APPLE) + set(HESAI_MACOS_COMPAT ${CMAKE_SOURCE_DIR}/cmake/hesai_macos_compat) + set(HESAI_MACOS_FLAGS -I${HESAI_MACOS_COMPAT} -include ${HESAI_MACOS_COMPAT}/hesai_macos_compat.h) + endif() + get_directory_property(_hesai_saved_compile_options COMPILE_OPTIONS) + add_compile_options(${HESAI_MACOS_FLAGS}) + add_subdirectory(${HESAI_SDK_DIRECTORY} ${CMAKE_BINARY_DIR}/3rdparty/HesaiLidar_SDK_2.0 EXCLUDE_FROM_ALL) + set_directory_properties(PROPERTIES COMPILE_OPTIONS "${_hesai_saved_compile_options}") + + add_library(hesai_sdk INTERFACE) + target_link_libraries(hesai_sdk INTERFACE hesai_sdk_lib) + target_include_directories(hesai_sdk INTERFACE ${HESAI_SDK_DIRECTORY}/driver ${HESAI_SDK_DIRECTORY}/libhesai ${HESAI_SDK_DIRECTORY}) + target_compile_options(hesai_sdk INTERFACE ${HESAI_MACOS_FLAGS}) +endif() + message(STATUS "==== Dependencies Configuration Complete ====") diff --git a/cmake/hesai_macos_compat/endian.h b/cmake/hesai_macos_compat/endian.h new file mode 100644 index 00000000..80d35956 --- /dev/null +++ b/cmake/hesai_macos_compat/endian.h @@ -0,0 +1,15 @@ +// macOS stand-in for glibc's , which the Hesai LiDAR SDK 2.0 includes. +#pragma once +#include +#define htobe16(x) OSSwapHostToBigInt16(x) +#define htole16(x) OSSwapHostToLittleInt16(x) +#define be16toh(x) OSSwapBigToHostInt16(x) +#define le16toh(x) OSSwapLittleToHostInt16(x) +#define htobe32(x) OSSwapHostToBigInt32(x) +#define htole32(x) OSSwapHostToLittleInt32(x) +#define be32toh(x) OSSwapBigToHostInt32(x) +#define le32toh(x) OSSwapLittleToHostInt32(x) +#define htobe64(x) OSSwapHostToBigInt64(x) +#define htole64(x) OSSwapHostToLittleInt64(x) +#define be64toh(x) OSSwapBigToHostInt64(x) +#define le64toh(x) OSSwapLittleToHostInt64(x) diff --git a/cmake/hesai_macos_compat/hesai_macos_compat.h b/cmake/hesai_macos_compat/hesai_macos_compat.h new file mode 100644 index 00000000..99a43f8d --- /dev/null +++ b/cmake/hesai_macos_compat/hesai_macos_compat.h @@ -0,0 +1,8 @@ +// Force-included into the Hesai LiDAR SDK 2.0 and the files that use it on macOS (see cmake/dependencies.cmake). +#pragma once +#include "endian.h" +// Linux termios2 serial ioctls, used only by the SDK's RS485 client (JT16). Defined so the SDK builds; the ioctl +// then fails at run time. Reading captures never uses them. +#define TCGETS2 0 +#define TCSETS2 0 +#define CBAUD 0 diff --git a/deploy_mandeye.bat b/deploy_mandeye.bat index 71db3e37..cf9ce7ce 100644 --- a/deploy_mandeye.bat +++ b/deploy_mandeye.bat @@ -60,7 +60,7 @@ rem This list has to be kept in sync by hand with the hdmapping_install_app() rem calls in apps/*/CMakeLists.txt. hd_mapper is deliberately absent: it is rem gated behind BUILD_WITH_HD_MAPPER_APPLICATION, which defaults to OFF, so rem listing it would warn on every normal build. -set "EXPECTED=camera_lidar_calibration.exe camera_lidar_intrinsics_calib.exe camera_lidar_trajectory_viewer.exe concatenate_multi_livox.exe drag_folder_with_mandeye_data_and_drop_here-precision_forestry.exe laz_to_mcap.exe laz_to_pcd.exe laz_to_ply.exe laz_to_txt.exe lidar_odometry_step_1.exe livox_mid_360_intrinsic_calibration.exe mandeye_compare_trajectories.exe mandeye_mission_recorder_calibration.exe mandeye_raw_data_viewer.exe mandeye_single_session_viewer.exe matrix_mul.exe mcap_to_laz.exe multiply_timestamps_session_point_cloud_laz.exe multiply_timestamps_session_trajectory_csv.exe multi_session_registration_step_3.exe multi_view_tls_registration_step_2.exe ouster_pcap_to_laz.exe pcd_to_laz.exe precision_forestry_tools.exe session_intensity_panoramas.exe session_to_mcap.exe split_multi_livox.exe freeglut.dll laszip3.dll opencv_world4130.dll proj_9_3.dll tbb12.dll z.dll" +set "EXPECTED=camera_lidar_calibration.exe camera_lidar_intrinsics_calib.exe camera_lidar_trajectory_viewer.exe concatenate_multi_livox.exe drag_folder_with_mandeye_data_and_drop_here-precision_forestry.exe laz_to_mcap.exe laz_to_pcd.exe laz_to_ply.exe laz_to_txt.exe lidar_odometry_step_1.exe livox_mid_360_intrinsic_calibration.exe mandeye_compare_trajectories.exe mandeye_mission_recorder_calibration.exe mandeye_raw_data_viewer.exe mandeye_single_session_viewer.exe matrix_mul.exe mcap_to_laz.exe multiply_timestamps_session_point_cloud_laz.exe multiply_timestamps_session_trajectory_csv.exe multi_session_registration_step_3.exe multi_view_tls_registration_step_2.exe ouster_pcap_to_laz.exe hesai_pcap_to_laz.exe pcd_to_laz.exe precision_forestry_tools.exe session_intensity_panoramas.exe session_to_mcap.exe split_multi_livox.exe freeglut.dll laszip3.dll opencv_world4130.dll proj_9_3.dll tbb12.dll z.dll" set "MISSING=" for %%F in (%EXPECTED%) do ( diff --git a/rosbags/MandeyeSessionChunker.cpp b/rosbags/MandeyeSessionChunker.cpp new file mode 100644 index 00000000..524a952f --- /dev/null +++ b/rosbags/MandeyeSessionChunker.cpp @@ -0,0 +1,99 @@ +#include "MandeyeSessionChunker.h" + +#include +#include +#include +#include +#include + +namespace rosbags +{ + +MandeyeSessionChunker::MandeyeSessionChunker(MandeyeSessionWriter& writer, double chunk_seconds) + : writer_(writer) + , chunk_seconds_(chunk_seconds) + , last_stamp_(-std::numeric_limits::infinity()) +{ +} + +int64_t MandeyeSessionChunker::timeBin(double timestamp_s) const +{ + if (chunk_seconds_ <= 0.0) + return 0; // splitting disabled: everything lands in one chunk + return static_cast(std::floor(timestamp_s / chunk_seconds_)); +} + +bool MandeyeSessionChunker::addPoints(const std::vector& points) +{ + if (points.empty()) + return true; + const double stamp_s = points.front().timestamp; + if (stamp_s < last_stamp_) + out_of_order_ = true; + last_stamp_ = stamp_s; + + const int64_t bin = timeBin(stamp_s); + if (chunk_bins_.empty() || bin != chunk_bins_.back()) + { + if (!writer_.beginChunk(static_cast(chunk_bins_.size()))) + return false; + chunk_bins_.push_back(bin); + } + return writer_.addPoints(points); +} + +void MandeyeSessionChunker::addImu(const McapImuSample& sample) +{ + imu_.push_back(sample); +} + +bool MandeyeSessionChunker::finish() +{ + if (!chunk_bins_.empty() && !writer_.endChunk()) + return false; + if (chunk_bins_.empty()) + return true; + + // chunk_bins_ is ascending when clouds arrive in time order, but an out-of-order input (a file-order read, a clock + // step) can break that, and upper_bound on an unsorted range would route samples arbitrarily: search a sorted + // (bin, chunk index) view instead. + std::vector> bin_to_chunk; + bin_to_chunk.reserve(chunk_bins_.size()); + for (size_t i = 0; i < chunk_bins_.size(); ++i) + bin_to_chunk.emplace_back(chunk_bins_[i], i); + std::sort(bin_to_chunk.begin(), bin_to_chunk.end()); + + std::vector> per_chunk(chunk_bins_.size()); + for (const auto& sample : imu_) + { + const int64_t bin = timeBin(sample.timestamp); + const auto it = std::upper_bound( + bin_to_chunk.begin(), + bin_to_chunk.end(), + bin, + [](int64_t value, const std::pair& entry) + { + return value < entry.first; + }); + const size_t index = (it == bin_to_chunk.begin()) ? bin_to_chunk.front().second : std::prev(it)->second; + per_chunk[index].push_back(sample); + } + for (size_t i = 0; i < per_chunk.size(); ++i) + { + if (!writer_.writeImuChunk(static_cast(i), per_chunk[i])) + return false; + } + return true; +} + +size_t MandeyeSessionChunker::chunks() const +{ + return chunk_bins_.size(); +} + +bool MandeyeSessionChunker::outOfOrder() const +{ + return out_of_order_; +} + +} // namespace rosbags diff --git a/rosbags/MandeyeSessionChunker.h b/rosbags/MandeyeSessionChunker.h new file mode 100644 index 00000000..4d165919 --- /dev/null +++ b/rosbags/MandeyeSessionChunker.h @@ -0,0 +1,66 @@ +#pragma once + +#include "MandeyeSessionWriter.h" // McapPoint, McapImuSample (via McapWriter.h) -- first, see McapWriter.h + +#include +#include + +namespace rosbags +{ + +/** + * @brief Splits a stream of point clouds and IMU samples into the chunks of a Mandeye session, as the bag and pcap + * converters write them. + * + * Chunks follow an absolute time grid: a timestamp t belongs to bin floor(t / chunk_seconds), so lidar and IMU bin + * identically without agreeing on a time origin. A cloud is never split: it lands in the bin of its first point. IMU + * samples are kept until finish(), then each goes into the chunk that was open at its time (the last chunk whose bin is + * not after the sample's, the first chunk for samples before all lidar data). No sample is dropped. + */ +class MandeyeSessionChunker +{ +public: + /** + * @brief Writes through `writer`, which must outlive the chunker. + * @param writer The session writer. + * @param chunk_seconds Chunk length in seconds; 0 or less writes one chunk. + */ + MandeyeSessionChunker(MandeyeSessionWriter& writer, double chunk_seconds); + + /** + * @brief Writes one cloud, opening a new chunk when its first point starts a new time bin. + * @param points Points with absolute timestamps in seconds. + * @return False on a write error (see the writer's error()). + */ + bool addPoints(const std::vector& points); + + /** + * @brief Keeps one IMU sample for finish(). + * @param sample Sample with an absolute timestamp in seconds. + */ + void addImu(const McapImuSample& sample); + + /** + * @brief Closes the last chunk and writes every chunk's imuNNNN.csv. + * @return False on a write error (see the writer's error()). + */ + bool finish(); + + /** @return Chunks written so far. */ + size_t chunks() const; + + /** @return True when a cloud started earlier than the one before it. */ + bool outOfOrder() const; + +private: + int64_t timeBin(double timestamp_s) const; + + MandeyeSessionWriter& writer_; + double chunk_seconds_; + std::vector chunk_bins_; + std::vector imu_; + double last_stamp_; + bool out_of_order_ = false; +}; + +} // namespace rosbags diff --git a/rosbags/OusterPcapReader.cpp b/rosbags/OusterPcapReader.cpp index 1a6fa5fe..a168145a 100644 --- a/rosbags/OusterPcapReader.cpp +++ b/rosbags/OusterPcapReader.cpp @@ -1,14 +1,13 @@ #include "OusterPcapReader.h" +#include "PcapUdpReader.h" #include #include #include #include -#include #include #include -#include namespace rosbags { @@ -46,23 +45,6 @@ constexpr KnownProfile kKnownProfiles[] = { {"RNG19_RFL8_SIG16_NIR16_R16_G16_B16", 20, true}, }; -// pcap link-layer types handled by linkPayload(). -constexpr uint32_t kLinkNull = 0; -constexpr uint32_t kLinkEthernet = 1; -constexpr uint32_t kLinkRaw = 101; -constexpr uint32_t kLinkLoop = 108; -constexpr uint32_t kLinkLinuxSll = 113; -constexpr uint32_t kLinkIpv4 = 228; -constexpr uint32_t kLinkLinuxSll2 = 276; - -// Anything bigger is a corrupt record header, not a packet: the largest Ouster -// lidar packet is ~33 kB and a reassembled IPv4 datagram is at most 64 kB. -constexpr uint32_t kMaxRecordBytes = 256 * 1024; -// Datagrams being reassembled at once; Ouster streams interleave at most a -// lidar and an IMU datagram, so anything beyond this is fragments whose -// siblings were never captured. -constexpr size_t kMaxPendingDatagrams = 64; - uint16_t le16(const uint8_t* p) { return static_cast(p[0] | (p[1] << 8)); @@ -85,21 +67,6 @@ float leFloat(const uint8_t* p) return v; } -uint16_t be16(const uint8_t* p) -{ - return static_cast((p[0] << 8) | p[1]); -} - -uint32_t be32(const uint8_t* p) -{ - return (static_cast(p[0]) << 24) | (static_cast(p[1]) << 16) | (static_cast(p[2]) << 8) | p[3]; -} - -uint32_t swap32(uint32_t v) -{ - return ((v & 0xFF) << 24) | ((v & 0xFF00) << 8) | ((v >> 8) & 0xFF00) | (v >> 24); -} - // Little-endian bit field of a channel data block, as pixel_data_format // describes it (bit 0 = LSB of byte 0). uint32_t bitField(const uint8_t* pixel, int start_bit, int width) @@ -355,11 +322,8 @@ struct OusterPcapReader::Impl bool stop = false; bool have_lidar_timestamp = false; - std::ifstream in; - std::vector buffer; - bool swapped = false; - bool nanoseconds = false; - uint32_t linktype = 0; + std::unique_ptr pcap; + uint64_t unrelated_datagrams = 0; // UDP on a port that is neither lidar nor IMU, or too short uint64_t prod_sn = 0; bool check_sn = false; @@ -371,17 +335,6 @@ struct OusterPcapReader::Impl std::vector lut_offset; std::array imu_rotation{}; - struct PendingDatagram - { - std::map> parts; // byte offset -> payload - uint32_t total = 0; // known once the last fragment arrives - uint64_t age = 0; - }; - std::map, PendingDatagram> pending; - uint64_t pending_clock = 0; - - std::vector record; - std::vector datagram; std::vector points; std::vector> rgb; @@ -390,7 +343,7 @@ struct OusterPcapReader::Impl if(error.empty()) error = std::move(message); // Release the file: a rejected capture must not stay locked (Windows) for the reader's lifetime. - in.close(); + pcap.reset(); open = false; return false; } @@ -432,70 +385,28 @@ struct OusterPcapReader::Impl } } - uint32_t u32(const uint8_t* p) const - { - uint32_t v; - std::memcpy(&v, p, sizeof(v)); - return swapped ? swap32(v) : v; - } - - // Locates the IPv4 header inside a captured frame. Returns false for anything - // that is not IPv4 (ARP, IPv6, ...). - bool linkPayload(const uint8_t* frame, size_t size, size_t& ip_offset) const + void handleDatagram(const UdpDatagram& udp) { - switch(linktype) - { - case kLinkEthernet: - { - size_t off = 12; - if(size < off + 2) - return false; - uint16_t ethertype = be16(frame + off); - while(ethertype == 0x8100 || ethertype == 0x88A8 || ethertype == 0x9100) // VLAN / QinQ tags - { - off += 4; - if(size < off + 2) - return false; - ethertype = be16(frame + off); - } - ip_offset = off + 2; - return ethertype == 0x0800; - } - case kLinkLinuxSll: - ip_offset = 16; - return size >= 16 && be16(frame + 14) == 0x0800; - case kLinkLinuxSll2: - ip_offset = 20; - return size >= 20 && be16(frame) == 0x0800; - case kLinkNull: - case kLinkLoop: - ip_offset = 4; - return size >= 4 && (u32(frame) == 2 || swap32(u32(frame)) == 2); // AF_INET, host order of the capturing machine - default: // kLinkRaw, kLinkIpv4 - ip_offset = 0; - return size >= 1 && (frame[0] >> 4) == 4; - } + if(udp.dst_port == options.lidar_port) + handleLidar(udp.payload, udp.size); + else if(udp.dst_port == options.imu_port && meta.udp_profile_imu == "LEGACY") + handleLegacyImu(udp.payload, udp.size); + else if(udp.dst_port == options.imu_port && meta.udp_profile_imu == "ACCEL32_GYRO32_NMEA") + handleAccel32Gyro32NmeaImu(udp.payload, udp.size); + else + ++unrelated_datagrams; + syncPcapStats(); } - void handleUdp(const uint8_t* udp, size_t size) + // The capture-level counters come from the pcap reader. + void syncPcapStats() { - if(size < 8) - { - ++stats.other_packets; - return; - } - const uint16_t dport = be16(udp + 2); - const size_t length = std::min(std::max(be16(udp + 4), 8), size) - 8; - const uint8_t* payload = udp + 8; - - if(dport == options.lidar_port) - handleLidar(payload, length); - else if(dport == options.imu_port && meta.udp_profile_imu == "LEGACY") - handleLegacyImu(payload, length); - else if(dport == options.imu_port && meta.udp_profile_imu == "ACCEL32_GYRO32_NMEA") - handleAccel32Gyro32NmeaImu(payload, length); - else - ++stats.other_packets; + const PcapUdpStats& p = pcap->stats(); + stats.bytes_read = p.bytes_read; + stats.records = p.records; + stats.other_packets = p.non_udp + unrelated_datagrams; + stats.reassembled_datagrams = p.reassembled_datagrams; + stats.dropped_fragments = p.dropped_fragments; } // Packet header init_id / serial number differ from the metadata's. @@ -649,85 +560,6 @@ struct OusterPcapReader::Impl } } - // Feeds one IPv4 fragment in; once every byte of its datagram has arrived, - // hands the reassembled UDP datagram on and forgets it. - void handleFragment(const uint8_t* ip, size_t ihl, size_t ip_length) - { - const auto key = std::make_tuple(be32(ip + 12), be32(ip + 16), be16(ip + 4)); - const uint16_t flags_offset = be16(ip + 6); - const bool more_fragments = (flags_offset & 0x2000) != 0; - const uint32_t offset = static_cast(flags_offset & 0x1FFF) * 8; - const size_t length = ip_length - ihl; - - auto [it, inserted] = pending.try_emplace(key); - PendingDatagram& d = it->second; - if(inserted) - d.age = pending_clock++; - d.parts[offset].assign(ip + ihl, ip + ihl + length); - if(!more_fragments) - d.total = offset + static_cast(length); - - if(d.total != 0) - { - uint32_t covered = 0; - for(const auto& [part_offset, bytes] : d.parts) - { - if(part_offset > covered) - break; // hole - covered = std::max(covered, part_offset + static_cast(bytes.size())); - } - if(covered >= d.total) - { - datagram.assign(d.total, 0); - for(const auto& [part_offset, bytes] : d.parts) - { - if(part_offset >= d.total) - break; - std::memcpy(datagram.data() + part_offset, bytes.data(), std::min(bytes.size(), d.total - part_offset)); - } - pending.erase(it); - ++stats.reassembled_datagrams; - handleUdp(datagram.data(), datagram.size()); - return; - } - } - - if(pending.size() > kMaxPendingDatagrams) - { - auto oldest = std::min_element( - pending.begin(), - pending.end(), - [](const auto& a, const auto& b) - { - return a.second.age < b.second.age; - }); - stats.dropped_fragments += oldest->second.parts.size(); - pending.erase(oldest); - } - } - - void handleFrame(const uint8_t* frame, size_t size) - { - size_t off = 0; - if(!linkPayload(frame, size, off) || size < off + 20) - { - ++stats.other_packets; - return; - } - const uint8_t* ip = frame + off; - const size_t ihl = static_cast(ip[0] & 0x0F) * 4; - const size_t ip_length = std::min(be16(ip + 2), size - off); - if((ip[0] >> 4) != 4 || ihl < 20 || ip_length < ihl || ip[9] != 17 /* UDP */) - { - ++stats.other_packets; - return; - } - if((be16(ip + 6) & 0x3FFF) != 0) // more-fragments flag or a non-zero offset - handleFragment(ip, ihl, ip_length); - else - handleUdp(ip + ihl, ip_length - ihl); - } - decltype(Callbacks::onPoints) onPoints; std::function onImu; }; @@ -760,56 +592,10 @@ OusterPcapReader::OusterPcapReader(const std::filesystem::path& pcap_path, const d.imu_rotation = {m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]}; d.buildLut(); - d.buffer.resize(1 << 20); - d.in.rdbuf()->pubsetbuf(d.buffer.data(), static_cast(d.buffer.size())); - d.in.open(pcap_path, std::ios::binary); - if(!d.in.is_open()) - { - d.fail("cannot open " + pcap_path.string()); - return; - } - - uint8_t header[24]; - if(!d.in.read(reinterpret_cast(header), sizeof(header))) - { - d.fail(pcap_path.string() + " is too short to be a pcap file"); - return; - } - uint32_t magic; - std::memcpy(&magic, header, sizeof(magic)); - switch(magic) - { - case 0xA1B2C3D4: - break; - case 0xA1B23C4D: - d.nanoseconds = true; - break; - case 0xD4C3B2A1: - d.swapped = true; - break; - case 0x4D3CB2A1: - d.swapped = d.nanoseconds = true; - break; - case 0x0A0D0D0A: - d.fail(pcap_path.string() + " is pcapng, which is not supported -- convert it with: editcap -F pcap in.pcapng out.pcap"); - return; - default: - d.fail(pcap_path.string() + " is not a pcap file"); - return; - } - d.linktype = d.u32(header + 20) & 0x0FFFFFFF; // upper bits: FCS length flags - switch(d.linktype) + d.pcap = std::make_unique(pcap_path); + if(!d.pcap->isOpen()) { - case kLinkNull: - case kLinkEthernet: - case kLinkRaw: - case kLinkLoop: - case kLinkLinuxSll: - case kLinkIpv4: - case kLinkLinuxSll2: - break; - default: - d.fail("unsupported pcap link type " + std::to_string(d.linktype)); + d.fail(d.pcap->error()); return; } @@ -845,25 +631,19 @@ bool OusterPcapReader::read(const Callbacks& callbacks) return false; d.onPoints = callbacks.onPoints; d.onImu = callbacks.onImu; + if(d.stop) + return true; - uint8_t record_header[16]; - while(!d.stop) - { - if(!d.in.read(reinterpret_cast(record_header), sizeof(record_header))) - break; // end of file; a torn final header (capture killed mid-write) ends it too - const uint32_t captured = d.u32(record_header + 8); - if(captured > kMaxRecordBytes) - return d.fail("corrupt pcap record #" + std::to_string(d.stats.records + 1) + ": " + std::to_string(captured) + " bytes"); - d.record.resize(captured); - if(!d.in.read(reinterpret_cast(d.record.data()), captured)) - break; // torn final record - ++d.stats.records; - d.stats.bytes_read += sizeof(record_header) + captured; - d.handleFrame(d.record.data(), d.record.size()); - } - for(const auto& [key, datagram] : d.pending) - d.stats.dropped_fragments += datagram.parts.size(); - d.pending.clear(); + const bool ok = d.pcap->read( + [&d](const UdpDatagram& udp) + { + d.handleDatagram(udp); + if(d.stop) + d.pcap->requestStop(); + }); + d.syncPcapStats(); + if(!ok) + return d.fail(d.pcap->error()); return true; } diff --git a/rosbags/PcapUdpReader.cpp b/rosbags/PcapUdpReader.cpp new file mode 100644 index 00000000..b496656d --- /dev/null +++ b/rosbags/PcapUdpReader.cpp @@ -0,0 +1,450 @@ +#include "PcapUdpReader.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace rosbags +{ + +namespace +{ + +// pcap link-layer types handled by ipOffset(). +constexpr uint32_t kLinkNull = 0; +constexpr uint32_t kLinkEthernet = 1; +constexpr uint32_t kLinkRaw = 101; +constexpr uint32_t kLinkLoop = 108; +constexpr uint32_t kLinkLinuxSll = 113; +constexpr uint32_t kLinkIpv4 = 228; +constexpr uint32_t kLinkLinuxSll2 = 276; + +// Larger records are not plausible captures of a sensor (and guard the buffer +// against a corrupt length field). +constexpr uint32_t kMaxRecordBytes = 256 * 1024; + +// Datagrams waiting for their missing fragments. A sensor interleaves at most a +// lidar and an IMU datagram, so anything beyond this is fragments whose +// datagram will never complete (packet loss): the oldest is dropped. +constexpr size_t kMaxPendingDatagrams = 64; + +constexpr uint32_t kZstdMagic = 0xFD2FB528; + +uint16_t be16(const uint8_t* p) +{ + return static_cast((p[0] << 8) | p[1]); +} + +uint32_t be32(const uint8_t* p) +{ + return (static_cast(p[0]) << 24) | (static_cast(p[1]) << 16) | (static_cast(p[2]) << 8) | p[3]; +} + +uint32_t swap32(uint32_t v) +{ + return (v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24); +} + +} // namespace + +struct PcapUdpReader::Impl +{ + PcapUdpStats stats; + std::string error; + bool open = false; + bool stop = false; + + std::ifstream in; + std::vector file_buffer; + + // zstd-compressed capture: compressed input and decompressed output windows. + ZSTD_DStream* zstd = nullptr; + std::vector zin, zout; + ZSTD_inBuffer zin_view{nullptr, 0, 0}; + size_t zout_pos = 0, zout_size = 0; + bool zstd_done = false; + + bool swapped = false; + bool nanoseconds = false; + uint32_t linktype = 0; + + struct PendingDatagram + { + std::map> parts; // byte offset -> payload + uint32_t total = 0; // known once the last fragment arrives + uint64_t age = 0; + }; + std::map, PendingDatagram> pending; + uint64_t pending_clock = 0; + + std::vector record; + std::vector datagram; + std::function on_datagram; + + ~Impl() + { + if(zstd) + ZSTD_freeDStream(zstd); + } + + bool fail(std::string message) + { + if(error.empty()) + error = std::move(message); + // Release the file: a rejected capture must not stay locked (Windows) for the reader's lifetime. + in.close(); + open = false; + return false; + } + + // Reads exactly n bytes of the (decompressed) capture. False at the end of + // the data, or on a decompression error (which also sets `error`). + bool readBytes(void* dst, size_t n) + { + if(!zstd) + { + if(!in.read(static_cast(dst), static_cast(n))) + return false; + stats.compressed_bytes_read += n; + return true; + } + auto* out = static_cast(dst); + while(n > 0) + { + if(zout_pos == zout_size) + { + if(!refillZstd()) + return false; + continue; + } + const size_t take = std::min(n, zout_size - zout_pos); + std::memcpy(out, zout.data() + zout_pos, take); + zout_pos += take; + out += take; + n -= take; + } + return true; + } + + // Decompresses the next window of output. False at the end of the stream or on an error. + bool refillZstd() + { + while(true) + { + if(zin_view.pos == zin_view.size) + { + if(zstd_done) + return false; + in.read(reinterpret_cast(zin.data()), static_cast(zin.size())); + const auto got = static_cast(in.gcount()); + if(got == 0) + { + zstd_done = true; + return false; + } + stats.compressed_bytes_read += got; + zin_view = {zin.data(), got, 0}; + } + ZSTD_outBuffer out{zout.data(), zout.size(), 0}; + const size_t rc = ZSTD_decompressStream(zstd, &out, &zin_view); + if(ZSTD_isError(rc)) + { + error = std::string("zstd: ") + ZSTD_getErrorName(rc); + zstd_done = true; + return false; + } + if(out.pos > 0) + { + zout_pos = 0; + zout_size = out.pos; + return true; + } + } + } + + uint32_t u32(const uint8_t* p) const + { + uint32_t v; + std::memcpy(&v, p, sizeof(v)); + return swapped ? swap32(v) : v; + } + + // Locates the IPv4 header inside a captured frame. Returns false for anything + // that is not IPv4 (ARP, IPv6, ...). + bool ipOffset(const uint8_t* frame, size_t size, size_t& offset) const + { + switch(linktype) + { + case kLinkEthernet: + { + size_t off = 12; + if(size < off + 2) + return false; + uint16_t ethertype = be16(frame + off); + while(ethertype == 0x8100 || ethertype == 0x88A8 || ethertype == 0x9100) // VLAN / QinQ tags + { + off += 4; + if(size < off + 2) + return false; + ethertype = be16(frame + off); + } + offset = off + 2; + return ethertype == 0x0800; + } + case kLinkLinuxSll: + offset = 16; + return size >= 16 && be16(frame + 14) == 0x0800; + case kLinkLinuxSll2: + offset = 20; + return size >= 20 && be16(frame) == 0x0800; + case kLinkNull: + case kLinkLoop: + offset = 4; + return size >= 4 && (u32(frame) == 2 || swap32(u32(frame)) == 2); // AF_INET, host order of the capturing machine + default: // kLinkRaw, kLinkIpv4 + offset = 0; + return size >= 1 && (frame[0] >> 4) == 4; + } + } + + void handleUdp(const uint8_t* ip, const uint8_t* udp, size_t size, int64_t time_ns) + { + if(size < 8) + { + ++stats.non_udp; + return; + } + UdpDatagram d; + d.src_ip = be32(ip + 12); + d.dst_ip = be32(ip + 16); + d.src_port = be16(udp); + d.dst_port = be16(udp + 2); + d.size = std::min(std::max(be16(udp + 4), 8), size) - 8; + d.payload = udp + 8; + d.capture_time_ns = time_ns; + if(on_datagram) + on_datagram(d); + } + + // Feeds one IPv4 fragment in; once every byte of its datagram has arrived, + // hands the reassembled UDP datagram on and forgets it. + void handleFragment(const uint8_t* ip, size_t ihl, size_t ip_length, int64_t time_ns) + { + const auto key = std::make_tuple(be32(ip + 12), be32(ip + 16), be16(ip + 4)); + const uint16_t flags_offset = be16(ip + 6); + const bool more_fragments = (flags_offset & 0x2000) != 0; + const uint32_t offset = static_cast(flags_offset & 0x1FFF) * 8; + const size_t length = ip_length - ihl; + + auto [it, inserted] = pending.try_emplace(key); + PendingDatagram& d = it->second; + if(inserted) + d.age = pending_clock++; + d.parts[offset].assign(ip + ihl, ip + ihl + length); + if(!more_fragments) + d.total = offset + static_cast(length); + + if(d.total != 0) + { + uint32_t covered = 0; + for(const auto& [part_offset, bytes] : d.parts) + { + if(part_offset > covered) + break; // hole + covered = std::max(covered, part_offset + static_cast(bytes.size())); + } + if(covered >= d.total) + { + datagram.assign(d.total, 0); + for(const auto& [part_offset, bytes] : d.parts) + { + if(part_offset >= d.total) + break; + std::memcpy(datagram.data() + part_offset, bytes.data(), std::min(bytes.size(), d.total - part_offset)); + } + pending.erase(it); + ++stats.reassembled_datagrams; + handleUdp(ip, datagram.data(), datagram.size(), time_ns); + return; + } + } + + if(pending.size() > kMaxPendingDatagrams) + { + auto oldest = std::min_element( + pending.begin(), + pending.end(), + [](const auto& a, const auto& b) + { + return a.second.age < b.second.age; + }); + stats.dropped_fragments += oldest->second.parts.size(); + pending.erase(oldest); + } + } + + void handleFrame(const uint8_t* frame, size_t size, int64_t time_ns) + { + size_t off = 0; + if(!ipOffset(frame, size, off) || size < off + 20) + { + ++stats.non_udp; + return; + } + const uint8_t* ip = frame + off; + const size_t ihl = static_cast(ip[0] & 0x0F) * 4; + const size_t ip_length = std::min(be16(ip + 2), size - off); + if((ip[0] >> 4) != 4 || ihl < 20 || ip_length < ihl || ip[9] != 17 /* UDP */) + { + ++stats.non_udp; + return; + } + if((be16(ip + 6) & 0x3FFF) != 0) // more-fragments flag or a non-zero offset + handleFragment(ip, ihl, ip_length, time_ns); + else + handleUdp(ip, ip + ihl, ip_length - ihl, time_ns); + } +}; + +PcapUdpReader::PcapUdpReader(const std::filesystem::path& path) + : impl_(std::make_unique()) +{ + Impl& d = *impl_; + d.file_buffer.resize(1 << 20); + d.in.rdbuf()->pubsetbuf(d.file_buffer.data(), static_cast(d.file_buffer.size())); + d.in.open(path, std::ios::binary); + if(!d.in.is_open()) + { + d.fail("cannot open " + path.string()); + return; + } + + uint8_t magic_bytes[4]; + if(!d.in.read(reinterpret_cast(magic_bytes), sizeof(magic_bytes))) + { + d.fail(path.string() + " is too short to be a pcap file"); + return; + } + uint32_t file_magic; + std::memcpy(&file_magic, magic_bytes, sizeof(file_magic)); + d.in.seekg(0); + if(file_magic == kZstdMagic) + { + d.zstd = ZSTD_createDStream(); + if(!d.zstd || ZSTD_isError(ZSTD_initDStream(d.zstd))) + { + d.fail("cannot create a zstd decompressor for " + path.string()); + return; + } + d.zin.resize(ZSTD_DStreamInSize()); + d.zout.resize(ZSTD_DStreamOutSize()); + } + + uint8_t header[24]; + if(!d.readBytes(header, sizeof(header))) + { + d.fail(d.error.empty() ? path.string() + " is too short to be a pcap file" : path.string() + ": " + d.error); + return; + } + uint32_t magic; + std::memcpy(&magic, header, sizeof(magic)); + switch(magic) + { + case 0xA1B2C3D4: + break; + case 0xA1B23C4D: + d.nanoseconds = true; + break; + case 0xD4C3B2A1: + d.swapped = true; + break; + case 0x4D3CB2A1: + d.swapped = d.nanoseconds = true; + break; + case 0x0A0D0D0A: + d.fail(path.string() + " is pcapng, which is not supported -- convert it with: editcap -F pcap in.pcapng out.pcap"); + return; + default: + d.fail(path.string() + " is not a pcap file"); + return; + } + d.linktype = d.u32(header + 20) & 0x0FFFFFFF; // upper bits: FCS length flags + switch(d.linktype) + { + case kLinkNull: + case kLinkEthernet: + case kLinkRaw: + case kLinkLoop: + case kLinkLinuxSll: + case kLinkIpv4: + case kLinkLinuxSll2: + break; + default: + d.fail("unsupported pcap link type " + std::to_string(d.linktype)); + return; + } + + d.open = true; +} + +PcapUdpReader::~PcapUdpReader() = default; + +bool PcapUdpReader::isOpen() const +{ + return impl_->open; +} + +const std::string& PcapUdpReader::error() const +{ + return impl_->error; +} + +void PcapUdpReader::requestStop() +{ + impl_->stop = true; +} + +const PcapUdpStats& PcapUdpReader::stats() const +{ + return impl_->stats; +} + +bool PcapUdpReader::read(const std::function& on_datagram) +{ + Impl& d = *impl_; + if(!d.open) + return false; + d.on_datagram = on_datagram; + + uint8_t record_header[16]; + while(!d.stop) + { + if(!d.readBytes(record_header, sizeof(record_header))) + break; // end of file; a torn final header (capture killed mid-write) ends it too + const uint32_t captured = d.u32(record_header + 8); + if(captured > kMaxRecordBytes) + return d.fail("corrupt pcap record #" + std::to_string(d.stats.records + 1) + ": " + std::to_string(captured) + " bytes"); + d.record.resize(captured); + if(!d.readBytes(d.record.data(), captured)) + break; // torn final record + ++d.stats.records; + d.stats.bytes_read += sizeof(record_header) + captured; + const int64_t seconds = d.u32(record_header); + const int64_t fraction = d.u32(record_header + 4); + const int64_t time_ns = seconds * 1000000000 + (d.nanoseconds ? fraction : fraction * 1000); + d.handleFrame(d.record.data(), d.record.size(), time_ns); + } + for(const auto& [key, datagram] : d.pending) + d.stats.dropped_fragments += datagram.parts.size(); + d.pending.clear(); + if(!d.error.empty()) // a decompression error + return d.fail(d.error); + return true; +} + +} // namespace rosbags diff --git a/rosbags/PcapUdpReader.h b/rosbags/PcapUdpReader.h new file mode 100644 index 00000000..c55bde3c --- /dev/null +++ b/rosbags/PcapUdpReader.h @@ -0,0 +1,68 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace rosbags +{ + +// One UDP datagram out of a capture, reassembled when it arrived in IPv4 +// fragments. `payload` is valid only during the callback that receives it. +struct UdpDatagram +{ + const uint8_t* payload = nullptr; + size_t size = 0; + uint32_t src_ip = 0; // host byte order + uint32_t dst_ip = 0; + uint16_t src_port = 0; + uint16_t dst_port = 0; + int64_t capture_time_ns = 0; // the pcap record time (Unix epoch) of the last fragment +}; + +struct PcapUdpStats +{ + uint64_t bytes_read = 0; // record headers and payloads consumed so far (uncompressed), for progress + uint64_t compressed_bytes_read = 0; // of the file itself; equals bytes_read + 24 for an uncompressed capture + uint64_t records = 0; + uint64_t non_udp = 0; // not IPv4, not UDP, or too short for a UDP header + uint64_t reassembled_datagrams = 0; + uint64_t dropped_fragments = 0; // IPv4 fragments of a datagram that never completed +}; + +// Streams the UDP datagrams of a classic libpcap capture (tcpdump, Wireshark +// saved as "pcap", ouster-cli, Hesai's PandarView), optionally zstd-compressed +// as a whole (.pcap.zst, e.g. lidar_recorder chunks). Microsecond and +// nanosecond timestamps, either byte order; Ethernet (with VLAN tags), Linux +// cooked (SLL, SLL2), BSD loopback and raw-IP link types; IPv4 only. +// Fragmented datagrams (a 128-beam lidar packet is far above a 1500-byte MTU) +// are reassembled. pcapng is refused with a conversion hint. +class PcapUdpReader +{ +public: + explicit PcapUdpReader(const std::filesystem::path& path); + ~PcapUdpReader(); + + PcapUdpReader(const PcapUdpReader&) = delete; + PcapUdpReader& operator=(const PcapUdpReader&) = delete; + + bool isOpen() const; + const std::string& error() const; + + // Hands every UDP datagram to `on_datagram`, in file order. A torn final + // record (capture killed mid-write) ends the file quietly. Returns false on + // an I/O, decompression or format error (see error()). + bool read(const std::function& on_datagram); + // Makes read() return after the datagram being handled; callable from the callback. + void requestStop(); + + const PcapUdpStats& stats() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace rosbags diff --git a/rosbags/tests/CMakeLists.txt b/rosbags/tests/CMakeLists.txt index 87f91629..74c7578b 100644 --- a/rosbags/tests/CMakeLists.txt +++ b/rosbags/tests/CMakeLists.txt @@ -10,6 +10,8 @@ add_executable(hdmapping_rosbags_tests test_mcap_writer.cpp test_mcap_reader.cpp test_ouster_pcap_reader.cpp + test_pcap_udp_reader.cpp + pcap_test_frames.h test_ros1_bag.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../McapWriter.h ${CMAKE_CURRENT_SOURCE_DIR}/../McapWriter.cpp @@ -19,6 +21,8 @@ add_executable(hdmapping_rosbags_tests ${CMAKE_CURRENT_SOURCE_DIR}/../MandeyeSessionWriter.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../OusterPcapReader.h ${CMAKE_CURRENT_SOURCE_DIR}/../OusterPcapReader.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../PcapUdpReader.h + ${CMAKE_CURRENT_SOURCE_DIR}/../PcapUdpReader.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../Ros1Bag.h ${CMAKE_CURRENT_SOURCE_DIR}/../Ros1Bag.cpp ) @@ -30,7 +34,7 @@ target_include_directories(hdmapping_rosbags_tests PRIVATE ${THIRDPARTY_DIRECTORY}/json/include ) -target_link_libraries(hdmapping_rosbags_tests PRIVATE mcap ros1bag_compression ${PLATFORM_LASZIP_LIB}) +target_link_libraries(hdmapping_rosbags_tests PRIVATE mcap ros1bag_compression hdmapping_zstd ${PLATFORM_LASZIP_LIB}) if (MSVC) target_compile_definitions(hdmapping_rosbags_tests PRIVATE _USE_MATH_DEFINES) diff --git a/rosbags/tests/pcap_test_frames.h b/rosbags/tests/pcap_test_frames.h new file mode 100644 index 00000000..04f2280a --- /dev/null +++ b/rosbags/tests/pcap_test_frames.h @@ -0,0 +1,90 @@ +#pragma once + +// Synthetic pcap captures for the rosbags tests: UDP payloads wrapped in Ethernet/IPv4/UDP frames, optionally split +// into IPv4 fragments, written as a classic pcap file. + +#include +#include +#include +#include +#include +#include + +namespace pcap_test +{ + + namespace fs = std::filesystem; + + inline void putLe(std::vector& out, size_t offset, uint64_t value, int bytes) + { + for (int i = 0; i < bytes; ++i) + out[offset + i] = static_cast(value >> (8 * i)); + } + + inline void putBe16(std::vector& out, size_t offset, uint16_t value) + { + out[offset] = static_cast(value >> 8); + out[offset + 1] = static_cast(value); + } + + // Wraps a UDP payload in Ethernet/IPv4/UDP, split into IPv4 fragments carrying at + // most `fragment_bytes` (a multiple of 8) of IP payload each; 0 = unfragmented. + inline std::vector> udpFrames( + const std::vector& payload, uint16_t dport, uint16_t ip_id, size_t fragment_bytes = 0) + { + std::vector datagram(8 + payload.size()); + putBe16(datagram, 0, 7502); + putBe16(datagram, 2, dport); + putBe16(datagram, 4, static_cast(datagram.size())); + std::copy(payload.begin(), payload.end(), datagram.begin() + 8); + + if (fragment_bytes == 0) + fragment_bytes = datagram.size(); + std::vector> frames; + for (size_t offset = 0; offset < datagram.size(); offset += fragment_bytes) + { + const size_t n = std::min(fragment_bytes, datagram.size() - offset); + const bool more = offset + n < datagram.size(); + std::vector f(14 + 20 + n, 0); + putBe16(f, 12, 0x0800); + f[14] = 0x45; + putBe16(f, 16, static_cast(20 + n)); + putBe16(f, 18, ip_id); + putBe16(f, 20, static_cast((more ? 0x2000 : 0) | (offset / 8))); + f[22] = 64; + f[23] = 17; + const uint8_t src[4] = { 169, 254, 0, 2 }; + const uint8_t dst[4] = { 169, 254, 0, 1 }; + std::memcpy(&f[26], src, 4); + std::memcpy(&f[30], dst, 4); + std::copy(datagram.begin() + offset, datagram.begin() + offset + n, f.begin() + 34); + frames.push_back(std::move(f)); + } + return frames; + } + + // A classic pcap of Ethernet frames; record i is stamped 1000 + i seconds plus `fraction` microseconds, or nanoseconds + // with `nanoseconds` (the 0xA1B23C4D magic). + inline void writePcap( + const fs::path& path, const std::vector>& frames, bool nanoseconds = false, uint32_t fraction = 0) + { + std::vector out(24, 0); + putLe(out, 0, nanoseconds ? 0xA1B23C4D : 0xA1B2C3D4, 4); + putLe(out, 4, 2, 2); + putLe(out, 6, 4, 2); + putLe(out, 16, 65535, 4); + putLe(out, 20, 1, 4); // Ethernet + for (size_t i = 0; i < frames.size(); ++i) + { + std::vector record(16, 0); + putLe(record, 0, 1000 + i, 4); + putLe(record, 4, fraction, 4); + putLe(record, 8, frames[i].size(), 4); + putLe(record, 12, frames[i].size(), 4); + out.insert(out.end(), record.begin(), record.end()); + out.insert(out.end(), frames[i].begin(), frames[i].end()); + } + std::ofstream(path, std::ios::binary).write(reinterpret_cast(out.data()), static_cast(out.size())); + } + +} // namespace pcap_test diff --git a/rosbags/tests/test_ouster_pcap_reader.cpp b/rosbags/tests/test_ouster_pcap_reader.cpp index 8e5e0399..722ce725 100644 --- a/rosbags/tests/test_ouster_pcap_reader.cpp +++ b/rosbags/tests/test_ouster_pcap_reader.cpp @@ -11,6 +11,7 @@ #include #include "OusterPcapReader.h" +#include "pcap_test_frames.h" #include #include @@ -27,6 +28,11 @@ namespace fs = std::filesystem; namespace { +using pcap_test::putBe16; +using pcap_test::putLe; +using pcap_test::udpFrames; +using pcap_test::writePcap; + constexpr uint64_t kInitId = 12345; constexpr uint64_t kSerial = 992612000030; @@ -65,18 +71,6 @@ rosbags::OusterMetadata parseOrFail(const std::string& json) return m; } -void putLe(std::vector& out, size_t offset, uint64_t value, int bytes) -{ - for (int i = 0; i < bytes; ++i) - out[offset + i] = static_cast(value >> (8 * i)); -} - -void putBe16(std::vector& out, size_t offset, uint16_t value) -{ - out[offset] = static_cast(value >> 8); - out[offset + 1] = static_cast(value); -} - struct Column { uint64_t timestamp_ns; @@ -163,61 +157,6 @@ std::vector accel32Gyro32NmeaImuPacket(const ImuMeasurement (&measureme return p; } -// Wraps a UDP payload in Ethernet/IPv4/UDP, split into IPv4 fragments carrying at -// most `fragment_bytes` (a multiple of 8) of IP payload each; 0 = unfragmented. -std::vector> udpFrames(const std::vector& payload, uint16_t dport, uint16_t ip_id, size_t fragment_bytes = 0) -{ - std::vector datagram(8 + payload.size()); - putBe16(datagram, 0, 7502); - putBe16(datagram, 2, dport); - putBe16(datagram, 4, static_cast(datagram.size())); - std::copy(payload.begin(), payload.end(), datagram.begin() + 8); - - if (fragment_bytes == 0) - fragment_bytes = datagram.size(); - std::vector> frames; - for (size_t offset = 0; offset < datagram.size(); offset += fragment_bytes) - { - const size_t n = std::min(fragment_bytes, datagram.size() - offset); - const bool more = offset + n < datagram.size(); - std::vector f(14 + 20 + n, 0); - putBe16(f, 12, 0x0800); - f[14] = 0x45; - putBe16(f, 16, static_cast(20 + n)); - putBe16(f, 18, ip_id); - putBe16(f, 20, static_cast((more ? 0x2000 : 0) | (offset / 8))); - f[22] = 64; - f[23] = 17; - const uint8_t src[4] = {169, 254, 0, 2}; - const uint8_t dst[4] = {169, 254, 0, 1}; - std::memcpy(&f[26], src, 4); - std::memcpy(&f[30], dst, 4); - std::copy(datagram.begin() + offset, datagram.begin() + offset + n, f.begin() + 34); - frames.push_back(std::move(f)); - } - return frames; -} - -void writePcap(const fs::path& path, const std::vector>& frames) -{ - std::vector out(24, 0); - putLe(out, 0, 0xA1B2C3D4, 4); - putLe(out, 4, 2, 2); - putLe(out, 6, 4, 2); - putLe(out, 16, 65535, 4); - putLe(out, 20, 1, 4); // Ethernet - for (size_t i = 0; i < frames.size(); ++i) - { - std::vector record(16, 0); - putLe(record, 0, 1000 + i, 4); - putLe(record, 8, frames[i].size(), 4); - putLe(record, 12, frames[i].size(), 4); - out.insert(out.end(), record.begin(), record.end()); - out.insert(out.end(), frames[i].begin(), frames[i].end()); - } - std::ofstream(path, std::ios::binary).write(reinterpret_cast(out.data()), static_cast(out.size())); -} - struct ReadResult { std::vector points; diff --git a/rosbags/tests/test_pcap_udp_reader.cpp b/rosbags/tests/test_pcap_udp_reader.cpp new file mode 100644 index 00000000..0bee486b --- /dev/null +++ b/rosbags/tests/test_pcap_udp_reader.cpp @@ -0,0 +1,142 @@ +// See rosbags/McapWriter.h for why this needs to come before any standard +// header (including ) gets a chance to lock in the project-wide +// _HAS_STD_BYTE=0 MSVC workaround. +#include "McapWriter.h" + +// doctest's main comes from test_mcap_writer.cpp, linked into the same binary. +#include + +#include "PcapUdpReader.h" +#include "pcap_test_frames.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace +{ + + struct Datagram + { + uint16_t dst_port = 0; + std::vector payload; + int64_t capture_time_ns = 0; + }; + + std::vector readAll(const fs::path& path, rosbags::PcapUdpStats& stats) + { + rosbags::PcapUdpReader reader(path); + INFO(reader.error()); + REQUIRE(reader.isOpen()); + std::vector out; + REQUIRE(reader.read( + [&](const rosbags::UdpDatagram& d) + { + out.push_back({ d.dst_port, std::vector(d.payload, d.payload + d.size), d.capture_time_ns }); + })); + stats = reader.stats(); + return out; + } + + std::vector payload(size_t size, uint8_t seed) + { + std::vector p(size); + for (size_t i = 0; i < size; ++i) + p[i] = static_cast(seed + i * 7); + return p; + } + + // Two datagrams, the second in three IPv4 fragments, and an ARP frame between them. + std::vector> sampleFrames() + { + auto frames = pcap_test::udpFrames(payload(100, 1), 2368, 1); + std::vector arp(42, 0); + pcap_test::putBe16(arp, 12, 0x0806); + frames.push_back(arp); + const auto fragmented = pcap_test::udpFrames(payload(1000, 2), 10110, 2, 400); + frames.insert(frames.end(), fragmented.begin(), fragmented.end()); + return frames; + } + +} // namespace + +TEST_CASE("PcapUdpReader: datagrams, ports and capture times; fragments reassembled, other frames counted") +{ + const fs::path path = fs::temp_directory_path() / "pcap_udp_reader_plain.pcap"; + pcap_test::writePcap(path, sampleFrames(), false, 250); + + rosbags::PcapUdpStats stats; + const auto datagrams = readAll(path, stats); + REQUIRE(datagrams.size() == 2); + CHECK(datagrams[0].dst_port == 2368); + CHECK(datagrams[0].payload == payload(100, 1)); + CHECK(datagrams[0].capture_time_ns == 1000LL * 1000000000 + 250000); // record 0, 250 us + CHECK(datagrams[1].dst_port == 10110); + CHECK(datagrams[1].payload == payload(1000, 2)); + CHECK(datagrams[1].capture_time_ns == 1004LL * 1000000000 + 250000); // the last fragment is record 4 + CHECK(stats.records == 5); + CHECK(stats.non_udp == 1); + CHECK(stats.reassembled_datagrams == 1); + CHECK(stats.dropped_fragments == 0); + fs::remove(path); +} + +TEST_CASE("PcapUdpReader: nanosecond timestamps") +{ + const fs::path path = fs::temp_directory_path() / "pcap_udp_reader_ns.pcap"; + pcap_test::writePcap(path, pcap_test::udpFrames(payload(10, 3), 2368, 1), true, 123); + + rosbags::PcapUdpStats stats; + const auto datagrams = readAll(path, stats); + REQUIRE(datagrams.size() == 1); + CHECK(datagrams[0].capture_time_ns == 1000LL * 1000000000 + 123); + fs::remove(path); +} + +TEST_CASE("PcapUdpReader: a zstd-compressed capture reads the same as the plain one") +{ + const fs::path plain = fs::temp_directory_path() / "pcap_udp_reader_zst.pcap"; + const fs::path compressed = fs::temp_directory_path() / "pcap_udp_reader_zst.pcap.zst"; + pcap_test::writePcap(plain, sampleFrames()); + std::ifstream in(plain, std::ios::binary); + const std::vector bytes((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + std::vector packed(ZSTD_compressBound(bytes.size())); + const size_t packed_size = ZSTD_compress(packed.data(), packed.size(), bytes.data(), bytes.size(), 3); + REQUIRE_FALSE(ZSTD_isError(packed_size)); + std::ofstream(compressed, std::ios::binary).write(packed.data(), static_cast(packed_size)); + + rosbags::PcapUdpStats plain_stats, compressed_stats; + const auto expected = readAll(plain, plain_stats); + const auto actual = readAll(compressed, compressed_stats); + REQUIRE(actual.size() == expected.size()); + for (size_t i = 0; i < actual.size(); ++i) + { + CHECK(actual[i].dst_port == expected[i].dst_port); + CHECK(actual[i].payload == expected[i].payload); + CHECK(actual[i].capture_time_ns == expected[i].capture_time_ns); + } + CHECK(compressed_stats.records == plain_stats.records); + CHECK(compressed_stats.bytes_read == plain_stats.bytes_read); + CHECK(compressed_stats.compressed_bytes_read == packed_size); + fs::remove(plain); + fs::remove(compressed); +} + +TEST_CASE("PcapUdpReader: pcapng is refused with a conversion hint") +{ + const fs::path path = fs::temp_directory_path() / "pcap_udp_reader.pcapng"; + std::vector block(28, 0); + pcap_test::putLe(block, 0, 0x0A0D0D0A, 4); + std::ofstream(path, std::ios::binary).write(reinterpret_cast(block.data()), static_cast(block.size())); + rosbags::PcapUdpReader reader(path); + CHECK_FALSE(reader.isOpen()); + CHECK(reader.error().find("editcap") != std::string::npos); + fs::remove(path); +} From 52357c5b53cb7d4cffc8d7738e61bb9a924528fe Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 16:40:52 +0100 Subject: [PATCH 13/21] Open Hesai pcap captures directly in step 1 and the raw viewer A new recording kind, "Hesai pcap", reads a lidar_recorder session (its lidarNNNN.pcap.zst chunks) or a set of .pcap / .pcap.zst files, with the lidar's angle correction (correction.dat next to them). Each file is one chunk, decoded on its own, so chunks load in parallel and lazily. - recording_sources/hesai_decoder: the Hesai SDK driver's packet loop, run synchronously on the caller's thread with its own UdpParser (no SDK threads). Frames are split at a new rotation, the origin "no return" points are dropped and the last partial frame is kept; IMU samples come from the point packets, in g and rad/s. The packet that selects the parser is decoded too, so a decoder per file loses no packet. - loadImu reads all files with one decoder, so the sample repeated at a file boundary is dropped as within a file. - hesai_pcap_to_laz uses the same decoder instead of the threaded SDK. - The Hesai SDK is built for every configuration (it was CLI tools only); the macOS compatibility header is a source property of the two files that include SDK headers. Step 1 and the raw viewer link RECORDING_SOURCE_LIBRARIES. Tested on a JT128 lidar_recorder session: step 1 loads 24,624,038 points and 13,875 IMU samples straight from the pcaps (skip_first_file off), the same as hesai_pcap_to_laz writes, and runs through. Co-Authored-By: Claude Opus 5.5 --- apps/console_tools/CMakeLists.txt | 7 +- apps/console_tools/hesai_pcap_to_laz.cpp | 198 +++++------------ apps/lidar_odometry_step_1/CMakeLists.txt | 3 +- apps/mandeye_raw_data_viewer/CMakeLists.txt | 3 +- cmake/dependencies.cmake | 41 ++-- recording_sources/hesai_decoder.cpp | 209 ++++++++++++++++++ recording_sources/hesai_decoder.h | 83 +++++++ recording_sources/hesai_pcap_source.cpp | 231 ++++++++++++++++++++ recording_sources/hesai_pcap_source.h | 64 ++++++ recording_sources/recording_sources.cmake | 14 +- 10 files changed, 679 insertions(+), 174 deletions(-) create mode 100644 recording_sources/hesai_decoder.cpp create mode 100644 recording_sources/hesai_decoder.h create mode 100644 recording_sources/hesai_pcap_source.cpp create mode 100644 recording_sources/hesai_pcap_source.h diff --git a/apps/console_tools/CMakeLists.txt b/apps/console_tools/CMakeLists.txt index 7828e2dd..66d1f10f 100644 --- a/apps/console_tools/CMakeLists.txt +++ b/apps/console_tools/CMakeLists.txt @@ -207,17 +207,20 @@ if (MSVC) endif() # hesai_pcap_to_laz: Hesai pcap (or a lidar_recorder session of .pcap.zst chunks) -> mandeye session directory. -# Same writer and chunking as mcap_to_laz; the packets are decoded by the Hesai LiDAR SDK (3rdparty/HesaiLidar_SDK_2.0). +# Same writer and chunking as mcap_to_laz; the packets are decoded by recording_sources/hesai_decoder (the Hesai LiDAR +# SDK's parser, 3rdparty/HesaiLidar_SDK_2.0), as lidar_odometry_step_1 reads a capture directly. add_executable( hesai_pcap_to_laz hesai_pcap_to_laz.cpp ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.h ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.cpp ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionWriter.h ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionWriter.cpp ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionChunker.h ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionChunker.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.h ${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.cpp ) +set_source_files_properties(${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.cpp PROPERTIES COMPILE_OPTIONS "${HESAI_MACOS_FLAGS}") target_include_directories( hesai_pcap_to_laz - PRIVATE ${REPOSITORY_DIRECTORY}/rosbags + PRIVATE ${REPOSITORY_DIRECTORY}/rosbags ${REPOSITORY_DIRECTORY}/recording_sources ${LASZIP_INCLUDE_DIR}/LASzip/include) target_link_libraries( diff --git a/apps/console_tools/hesai_pcap_to_laz.cpp b/apps/console_tools/hesai_pcap_to_laz.cpp index 3f8f295c..605b79ae 100644 --- a/apps/console_tools/hesai_pcap_to_laz.cpp +++ b/apps/console_tools/hesai_pcap_to_laz.cpp @@ -1,62 +1,31 @@ // hesai_pcap_to_laz: Hesai pcap captures (.pcap, or zstd-compressed .pcap.zst as lidar_recorder writes them) -> // mandeye session directory, as mcap_to_laz and ouster_pcap_to_laz write one. // -// UDP payloads are pushed straight into the Hesai LiDAR SDK's decoder with the lidar's angle correction; points and IMU -// samples come out on the lidar clock and are converted as mandeye_controller's Hesai client does (acceleration in g, -// angular velocity deg/s -> rad/s). A lidar_recorder session directory stands for its lidarNNNN.pcap.zst chunks, and -// its gnssNNNN.nmea files (lidar-clock times, already in the mandeye format) are copied next to the result. +// The packets are decoded by HesaiDecoder (the Hesai LiDAR SDK's parser) with the lidar's angle correction, as +// lidar_odometry_step_1 reads a capture directly; points and IMU samples are on the lidar clock. A lidar_recorder session directory stands +// for its lidarNNNN.pcap.zst chunks, and its gnssNNNN.nmea files (lidar-clock times, already in the mandeye format) are copied next to the +// result. // See rosbags/McapWriter.h: the rosbags headers come before any standard header. #include "MandeyeSessionChunker.h" #include "MandeyeSessionWriter.h" -#include "PcapUdpReader.h" - -#include "hesai_lidar_sdk.hpp" +#include "hesai_decoder.h" #include "console_progress.h" #include #include -#include -#include #include #include #include -#include #include -#include #include namespace fs = std::filesystem; -using namespace hesai::lidar; namespace { - // lidarNNNN.pcap.zst (or .pcap when there is no .zst of the same chunk) of a lidar_recorder session, in order. - // Incomplete .part chunks are skipped. - std::vector sessionChunks(const fs::path& dir) - { - std::vector zst, plain; - for (const auto& e : fs::directory_iterator(dir)) - { - const std::string n = e.path().filename().string(); - if (n.rfind("lidar", 0) != 0) - continue; - if (n.ends_with(".pcap.zst")) - zst.push_back(e.path()); - else if (n.ends_with(".pcap")) - plain.push_back(e.path()); - else if (n.ends_with(".part")) - spdlog::warn("Skipping incomplete chunk {}", n); - } - for (const auto& p : plain) - if (std::find(zst.begin(), zst.end(), fs::path(p.string() + ".zst")) == zst.end()) - zst.push_back(p); - std::sort(zst.begin(), zst.end()); - return zst; - } - void print_usage(const char* argv0) { spdlog::error("Usage: {} [ ...] [options]", argv0); @@ -145,7 +114,7 @@ int main(const int argc, const char** argv) { if (fs::is_directory(input)) { - const auto chunks = sessionChunks(input); + const auto chunks = hesai_recorder_chunks(input); if (chunks.empty()) { spdlog::error("No lidarNNNN.pcap.zst or .pcap in {}", input); @@ -180,120 +149,57 @@ int main(const int argc, const char** argv) rosbags::MandeyeSessionChunker chunker(writer, chunk_seconds); spdlog::info("Reading {} input(s) with angle correction {}", inputs.size(), correction.string()); - // Both SDK callbacks run on the SDK's single processing thread, so the chunker needs no locking. - std::atomic write_ok{ true }; + bool write_ok = true; uint64_t frames = 0; - std::vector points; - HesaiLidarSdk sdk; - sdk.RegRecvCallback( - std::function&)>( - [&](const LidarDecodedFrame& frame) - { - points.clear(); - points.reserve(frame.points_num); - for (uint32_t i = 0; i < frame.points_num; ++i) - { - const auto& p = frame.points[i]; - if (p.x == 0.f && p.y == 0.f && p.z == 0.f) - continue; // a "no return" slot, which the SDK still emits at the origin - rosbags::McapPoint out; - out.x = p.x; - out.y = p.y; - out.z = p.z; - out.intensity = static_cast(p.intensity); - out.ring = p.ring; - out.timestamp = p.timestamp; - points.push_back(out); - } - if (!points.empty() && write_ok && !chunker.addPoints(points)) - write_ok = false; - ++frames; - })); - sdk.RegRecvCallback( - std::function( - [&](const LidarImuData& d) - { - // SDK units: acceleration in g, angular velocity in deg/s; mandeye stores g and rad/s. - constexpr double kDegToRad = std::numbers::pi / 180.0; - rosbags::McapImuSample s; - s.timestamp = d.timestamp; - s.acc_x = static_cast(d.imu_accel_x); - s.acc_y = static_cast(d.imu_accel_y); - s.acc_z = static_cast(d.imu_accel_z); - s.gyro_x = static_cast(d.imu_ang_vel_x * kDegToRad); - s.gyro_y = static_cast(d.imu_ang_vel_y * kDegToRad); - s.gyro_z = static_cast(d.imu_ang_vel_z * kDegToRad); - chunker.addImu(s); - })); - - DriverParam param; - param.input_param.source_type = DATA_FROM_ROS_PACKET; // packets are pushed in below - param.input_param.correction_file_path = correction.string(); - param.decoder_param.pcap_play_in_loop = false; - sdk.Init(param); // returns at once; its init thread takes the first packet to detect the model + HesaiDecoder decoder(correction); + decoder.onFrame = [&](std::vector&& points) + { + if (write_ok && !chunker.addPoints(points)) + write_ok = false; + ++frames; + }; + decoder.onImu = [&](const rosbags::McapImuSample& sample) + { + chunker.addImu(sample); + }; - // Reader: pushes the point cloud UDP payloads into the SDK's packet ring, waiting while it is full. - std::atomic read_ok{ true }; - uint64_t pushed = 0; - std::thread reader( - [&] - { - uint64_t input_bytes = 0; - for (const auto& path : inputs) - { - std::error_code ec; - input_bytes += fs::file_size(path, ec); - } - ConsoleProgress progress("Reading pcap (bytes)", input_bytes); - uint64_t bytes_before = 0; - for (const auto& path : inputs) - { - rosbags::PcapUdpReader pcap(path); - if (!pcap.isOpen()) - { - spdlog::error("Cannot read {}: {}", path.string(), pcap.error()); - read_ok = false; - continue; - } - const bool ok = pcap.read( - [&](const rosbags::UdpDatagram& d) - { - progress.update(bytes_before + pcap.stats().compressed_bytes_read); - if (d.dst_port != udp_port) - return; - while (sdk.OriginPacketIsBufferFull()) - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - sdk.PushOriginPacketBuffer(d.payload, static_cast(d.size), static_cast(d.capture_time_ns / 1000)); - ++pushed; - }); - if (!ok) + uint64_t input_bytes = 0; + for (const auto& path : inputs) + { + std::error_code ec; + input_bytes += fs::file_size(path, ec); + } + ConsoleProgress progress("Reading pcap (bytes)", input_bytes); + uint64_t bytes_before = 0; + bool read_ok = true; + for (const auto& path : inputs) + { + // One decoder for all inputs: they are one continuous recording, so a frame spanning two files stays whole. + std::string error; + uint64_t bytes = 0; + if (!decode_hesai_capture( + path, + static_cast(udp_port), + decoder, + error, + [&](uint64_t read) { - spdlog::warn("{}: {} - kept what was read", path.string(), pcap.error()); - read_ok = false; - } - if (pcap.stats().dropped_fragments > 0) - spdlog::warn( - "{}: {} IP fragment(s) dropped: their datagram never completed (packet loss during capture)", - path.string(), - pcap.stats().dropped_fragments); - bytes_before += pcap.stats().compressed_bytes_read; - } - progress.finish(bytes_before); - }); - - sdk.Start(); // blocks until the decoder is initialised - reader.join(); - if (sdk.lidar_ptr_->GetInitFinish(FailInit)) + bytes = read; + progress.update(bytes_before + read); + })) + { + spdlog::warn("{}: {} - kept what was read", path.string(), error); + read_ok = false; + } + bytes_before += bytes; + } + decoder.finish(); + progress.finish(bytes_before); + if (!decoder.error().empty()) { - spdlog::error("The Hesai SDK failed to initialise (no point packets on UDP port {}?)", udp_port); - sdk.Stop(); + spdlog::error("{}", decoder.error()); return EXIT_FAILURE; } - // Let the decoder drain the ring, then give the parser a moment for the last frame. - while (!sdk.lidar_ptr_->origin_packets_buffer_.empty()) - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - std::this_thread::sleep_for(std::chrono::milliseconds(300)); - sdk.Stop(); if (!write_ok) { @@ -302,7 +208,7 @@ int main(const int argc, const char** argv) } if (chunker.chunks() == 0) { - spdlog::error("No points decoded from {} packet(s) on UDP port {} - nothing to write", pushed, udp_port); + spdlog::error("No points decoded on UDP port {} - nothing to write", udp_port); return EXIT_FAILURE; } if (!chunker.finish()) diff --git a/apps/lidar_odometry_step_1/CMakeLists.txt b/apps/lidar_odometry_step_1/CMakeLists.txt index f6eb766b..b60de191 100644 --- a/apps/lidar_odometry_step_1/CMakeLists.txt +++ b/apps/lidar_odometry_step_1/CMakeLists.txt @@ -65,8 +65,7 @@ target_include_directories( target_link_libraries( lidar_odometry_step_1 PRIVATE - mcap - ros1bag_compression + ${RECORDING_SOURCE_LIBRARIES} step1_run_report # core_raylib_utils brings in core_raylib (core, raylib), raylib_widgets and rlImGui. core_raylib_utils diff --git a/apps/mandeye_raw_data_viewer/CMakeLists.txt b/apps/mandeye_raw_data_viewer/CMakeLists.txt index be7c0eb8..738e9b1e 100644 --- a/apps/mandeye_raw_data_viewer/CMakeLists.txt +++ b/apps/mandeye_raw_data_viewer/CMakeLists.txt @@ -48,8 +48,7 @@ target_include_directories( target_link_libraries( mandeye_raw_data_viewer PRIVATE - mcap - ros1bag_compression + ${RECORDING_SOURCE_LIBRARIES} step1_run_report # core_raylib_utils brings in core_raylib (core, raylib), raylib_widgets and rlImGui. core_raylib_utils diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index 060f921f..f4ee837f 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -379,28 +379,27 @@ else() target_link_libraries(ros1bag_compression INTERFACE BZip2::BZip2) endif() -# Hesai LiDAR SDK 2.0 (hesai_pcap_to_laz): decodes Hesai point and IMU packets with the lidar's angle correction. -# Built without PTCS (TLS to a live sensor, which needs OpenSSL): reading captures needs no connection. The SDK -# supports Linux and Windows; on macOS cmake/hesai_macos_compat supplies and the Linux serial ioctls it -# names, force-included into the SDK and, through the hesai_sdk target, into the files that use it. -if(BUILD_WITH_CLI_TOOLS) - set(WITH_PTCS_USE OFF CACHE BOOL "Hesai SDK: TLS connection to a live sensor (needs OpenSSL)" FORCE) - set(DISENABLE_TEST_CC ON CACHE BOOL "Hesai SDK: skip its sample programs" FORCE) - set(HESAI_SDK_DIRECTORY ${THIRDPARTY_DIRECTORY}/HesaiLidar_SDK_2.0) - if(APPLE) - set(HESAI_MACOS_COMPAT ${CMAKE_SOURCE_DIR}/cmake/hesai_macos_compat) - set(HESAI_MACOS_FLAGS -I${HESAI_MACOS_COMPAT} -include ${HESAI_MACOS_COMPAT}/hesai_macos_compat.h) - endif() - get_directory_property(_hesai_saved_compile_options COMPILE_OPTIONS) - add_compile_options(${HESAI_MACOS_FLAGS}) - add_subdirectory(${HESAI_SDK_DIRECTORY} ${CMAKE_BINARY_DIR}/3rdparty/HesaiLidar_SDK_2.0 EXCLUDE_FROM_ALL) - set_directory_properties(PROPERTIES COMPILE_OPTIONS "${_hesai_saved_compile_options}") - - add_library(hesai_sdk INTERFACE) - target_link_libraries(hesai_sdk INTERFACE hesai_sdk_lib) - target_include_directories(hesai_sdk INTERFACE ${HESAI_SDK_DIRECTORY}/driver ${HESAI_SDK_DIRECTORY}/libhesai ${HESAI_SDK_DIRECTORY}) - target_compile_options(hesai_sdk INTERFACE ${HESAI_MACOS_FLAGS}) +# Hesai LiDAR SDK 2.0: decodes Hesai point and IMU packets with the lidar's angle correction (the Hesai pcap recording +# source, hesai_pcap_to_laz). Built without PTCS (TLS to a live sensor, which needs OpenSSL): reading captures needs no +# connection. The SDK supports Linux and Windows; on macOS cmake/hesai_macos_compat supplies and the Linux +# serial ioctls it names. HESAI_MACOS_FLAGS force-includes them; files that include SDK headers get it as a source +# property (it must not reach whole targets). +set(WITH_PTCS_USE OFF CACHE BOOL "Hesai SDK: TLS connection to a live sensor (needs OpenSSL)" FORCE) +set(DISENABLE_TEST_CC ON CACHE BOOL "Hesai SDK: skip its sample programs" FORCE) +set(HESAI_SDK_DIRECTORY ${THIRDPARTY_DIRECTORY}/HesaiLidar_SDK_2.0) +set(HESAI_MACOS_FLAGS "") +if(APPLE) + set(HESAI_MACOS_COMPAT ${CMAKE_SOURCE_DIR}/cmake/hesai_macos_compat) + set(HESAI_MACOS_FLAGS -I${HESAI_MACOS_COMPAT} -include ${HESAI_MACOS_COMPAT}/hesai_macos_compat.h) endif() +get_directory_property(_hesai_saved_compile_options COMPILE_OPTIONS) +add_compile_options(${HESAI_MACOS_FLAGS}) +add_subdirectory(${HESAI_SDK_DIRECTORY} ${CMAKE_BINARY_DIR}/3rdparty/HesaiLidar_SDK_2.0 EXCLUDE_FROM_ALL) +set_directory_properties(PROPERTIES COMPILE_OPTIONS "${_hesai_saved_compile_options}") + +add_library(hesai_sdk INTERFACE) +target_link_libraries(hesai_sdk INTERFACE hesai_sdk_lib) +target_include_directories(hesai_sdk INTERFACE ${HESAI_SDK_DIRECTORY}/driver ${HESAI_SDK_DIRECTORY}/libhesai ${HESAI_SDK_DIRECTORY}) message(STATUS "==== Dependencies Configuration Complete ====") diff --git a/recording_sources/hesai_decoder.cpp b/recording_sources/hesai_decoder.cpp new file mode 100644 index 00000000..f8362c1c --- /dev/null +++ b/recording_sources/hesai_decoder.cpp @@ -0,0 +1,209 @@ +// The rosbags headers come first: they re-enable std::byte on MSVC before any standard header (see rosbags/McapWriter.h). +#include "hesai_decoder.h" + +#include "PcapUdpReader.h" + +#include "driver_param.h" +#include "udp_parser.h" + +#include +#include +#include + +namespace fs = std::filesystem; +using namespace hesai::lidar; + +struct HesaiDecoder::Impl +{ + fs::path correction; + bool decode_points = true; + DriverParam param; + UdpParser parser; + LidarDecodedFrame frame; + bool ready = false; // the model-specific parser exists and the correction is loaded + uint32_t packet_index = 0; + LidarImuData last_imu; + std::vector points; + + void prepare() + { + parser.setFrameRightMemorySpace(frame); + parser.SetPcapPlay(param.input_param.source_type); + parser.SetFrameAzimuth(param.decoder_param.frame_start_azimuth); + parser.LoadCorrectionFile(correction.string()); + ready = true; + } + + // As the SDK driver does once a frame is complete: points of all packets packed together, then FrameProcess. + void emitFrame(HesaiDecoder& owner) + { + if (decode_points && frame.points_num == 0) + { + uint32_t points_num = 0; + for (uint32_t i = 0; i < frame.packet_num; ++i) + { + if (points_num != i * frame.per_points_num) + std::memmove( + frame.points + points_num, frame.points + i * frame.per_points_num, frame.getPointSize() * frame.valid_points[i]); + points_num += frame.valid_points[i]; + } + frame.points_num = points_num; + } + if (decode_points && frame.points_num > 0) + { + parser.FrameProcess(frame); + points.clear(); + points.reserve(frame.points_num); + for (uint32_t i = 0; i < frame.points_num; ++i) + { + const auto& p = frame.points[i]; + if (p.x == 0.f && p.y == 0.f && p.z == 0.f) + continue; // a "no return" slot, which the SDK still emits at the origin + rosbags::McapPoint out; + out.x = p.x; + out.y = p.y; + out.z = p.z; + out.intensity = static_cast(p.intensity); + out.ring = p.ring; + out.timestamp = p.timestamp; + points.push_back(out); + } + if (!points.empty() && owner.onFrame) + owner.onFrame(std::move(points)); + points = {}; + } + frame.Update(); + packet_index = 0; + } + + void emitImu(HesaiDecoder& owner) + { + if (!frame.imu_config.flag || last_imu.isSameImuValue(frame.imu_config)) + return; + last_imu = frame.imu_config; + if (!owner.onImu) + return; + // SDK units: acceleration in g, angular velocity in deg/s; mandeye stores g and rad/s. + constexpr double kDegToRad = std::numbers::pi / 180.0; + const LidarImuData& d = frame.imu_config; + rosbags::McapImuSample s; + s.timestamp = d.timestamp; + s.acc_x = static_cast(d.imu_accel_x); + s.acc_y = static_cast(d.imu_accel_y); + s.acc_z = static_cast(d.imu_accel_z); + s.gyro_x = static_cast(d.imu_ang_vel_x * kDegToRad); + s.gyro_y = static_cast(d.imu_ang_vel_y * kDegToRad); + s.gyro_z = static_cast(d.imu_ang_vel_z * kDegToRad); + owner.onImu(s); + } + + // A packet that is not the one splitting the frame: its points are computed into the frame's next slot. + void addPacket() + { + if (frame.packet_num == packet_index) + return; // the packet carried no points (e.g. an IMU-only packet) + if (decode_points) + parser.ComputeXYZI(frame, packet_index); + ++packet_index; + } +}; + +HesaiDecoder::HesaiDecoder(const fs::path& correction, bool decode_points) + : impl_(std::make_unique()) +{ + impl_->correction = correction; + impl_->decode_points = decode_points; + impl_->param.input_param.source_type = DATA_FROM_ROS_PACKET; + impl_->param.input_param.correction_file_path = correction.string(); + impl_->frame.fParam.Init(impl_->param); +} + +HesaiDecoder::~HesaiDecoder() = default; + +void HesaiDecoder::push(const uint8_t* payload, size_t size) +{ + Impl& d = *impl_; + if (size == 0 || size > kBufSize) + return; // not a Hesai point cloud packet (the SDK's packet buffer holds kBufSize bytes) + const UdpPacket packet(payload, static_cast(size)); + + if (!d.ready) + { + // The first packet only picks the parser for the lidar model; then it is decoded like any other, so a decoder + // per file (one per chunk) loses no packet. + d.parser.DecodePacket(d.frame, packet); + if (d.parser.GetGeneralParser() == nullptr) + return; + d.prepare(); + } + + const int result = d.parser.DecodePacket(d.frame, packet); + d.emitImu(*this); + if (result != 0) + return; + if (d.frame.scan_complete) + { + d.emitFrame(*this); + // The packet that completed the frame is the first packet of the next one. + if (d.parser.DecodePacket(d.frame, packet) == 0) + d.addPacket(); + return; + } + d.addPacket(); +} + +void HesaiDecoder::finish() +{ + if (impl_->ready && impl_->packet_index > 0) + impl_->emitFrame(*this); +} + +std::string HesaiDecoder::error() const +{ + if (impl_->ready && !impl_->parser.isSetCorrectionSucc()) + return "cannot use the angle correction " + impl_->correction.string(); + return {}; +} + +std::vector hesai_recorder_chunks(const fs::path& dir) +{ + std::vector zst, plain; + std::error_code ec; + for (const auto& e : fs::directory_iterator(dir, ec)) + { + const std::string n = e.path().filename().string(); + if (n.rfind("lidar", 0) != 0) + continue; + if (n.ends_with(".pcap.zst")) + zst.push_back(e.path()); + else if (n.ends_with(".pcap")) + plain.push_back(e.path()); + } + for (const auto& p : plain) + if (std::find(zst.begin(), zst.end(), fs::path(p.string() + ".zst")) == zst.end()) + zst.push_back(p); + std::sort(zst.begin(), zst.end()); + return zst; +} + +bool decode_hesai_capture( + const fs::path& file, uint16_t udp_port, HesaiDecoder& decoder, std::string& error, const std::function& on_bytes) +{ + rosbags::PcapUdpReader pcap(file); + if (!pcap.isOpen()) + { + error = pcap.error(); + return false; + } + const bool ok = pcap.read( + [&](const rosbags::UdpDatagram& d) + { + if (on_bytes) + on_bytes(pcap.stats().compressed_bytes_read); + if (d.dst_port == udp_port) + decoder.push(d.payload, d.size); + }); + if (!ok) + error = pcap.error(); + return ok; +} diff --git a/recording_sources/hesai_decoder.h b/recording_sources/hesai_decoder.h new file mode 100644 index 00000000..a7ff4969 --- /dev/null +++ b/recording_sources/hesai_decoder.h @@ -0,0 +1,83 @@ +#pragma once + +// McapPoint, McapImuSample. The rosbags headers come first (see rosbags/McapWriter.h); include this header only from +// .cpp files, never from a header GUI code includes. +#include "McapWriter.h" + +#include +#include +#include +#include +#include +#include + +/** + * @brief Decodes Hesai point cloud UDP payloads with the Hesai LiDAR SDK's parser, synchronously on the caller's + * thread. Every instance has its own parser, so several decode in parallel. + * + * Follows the SDK driver's packet loop: frames are split where the lidar starts a new rotation, the "no return" slots + * the SDK emits at the origin are dropped, and the last (partial) frame comes out on finish(), so every point of the + * input is kept. Points are in metres in the lidar frame with absolute timestamps in seconds on the lidar clock; IMU + * samples carried in the point packets come out with acceleration in g and angular velocity in rad/s, as + * mandeye_controller's Hesai client stores them. + */ +class HesaiDecoder +{ +public: + /** + * @brief Prepares a decoder; the lidar model is detected from the first packet. + * @param correction The lidar's angle correction file (correction.dat). + * @param decode_points False decodes only the IMU samples, skipping the point computation. + */ + explicit HesaiDecoder(const std::filesystem::path& correction, bool decode_points = true); + ~HesaiDecoder(); + + HesaiDecoder(const HesaiDecoder&) = delete; + HesaiDecoder& operator=(const HesaiDecoder&) = delete; + + /** @brief Receives each decoded frame's points. */ + std::function&&)> onFrame; + /** @brief Receives each IMU sample. */ + std::function onImu; + + /** + * @brief Decodes one UDP payload sent to the lidar's point cloud port. + * @param payload The payload. + * @param size Its length in bytes. + */ + void push(const uint8_t* payload, size_t size); + + /** @brief Hands out the frame still being collected. */ + void finish(); + + /** @return Empty, or why points cannot be decoded (no or unreadable angle correction). */ + std::string error() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +/** + * @brief The lidarNNNN.pcap.zst chunks of a lidar_recorder session directory (a .pcap where there is no .zst of the + * same chunk), in order; incomplete .part chunks are skipped. + * @param dir The session directory. + * @return The chunk files; empty when the directory holds none. + */ +std::vector hesai_recorder_chunks(const std::filesystem::path& dir); + +/** + * @brief Decodes every point cloud UDP payload of one capture. + * @param file A classic pcap, optionally zstd-compressed as a whole. + * @param udp_port The point cloud destination port. + * @param decoder Receives the payloads; finish() is not called. + * @param error Set when the file cannot be read; what was read before the error was decoded. + * @param on_bytes Optional: called with the bytes of the file read so far. + * @return False on a read error. + */ +bool decode_hesai_capture( + const std::filesystem::path& file, + uint16_t udp_port, + HesaiDecoder& decoder, + std::string& error, + const std::function& on_bytes = {}); diff --git a/recording_sources/hesai_pcap_source.cpp b/recording_sources/hesai_pcap_source.cpp new file mode 100644 index 00000000..8fd7aada --- /dev/null +++ b/recording_sources/hesai_pcap_source.cpp @@ -0,0 +1,231 @@ +// The rosbags headers come first: they re-enable std::byte on MSVC before any standard header (see rosbags/McapWriter.h). +#include "hesai_decoder.h" + +#include "hesai_pcap_source.h" + +#include +#include +#include + +namespace fs = std::filesystem; + +namespace +{ + bool is_capture(const fs::path& file) + { + const std::string name = file.filename().string(); + return name.ends_with(".pcap") || name.ends_with(".pcap.zst"); + } + + //! The captures of paths in recording order: files as given, a folder's lidarNNNN chunks; empty when a path is neither. + std::vector captures(const std::vector& paths) + { + std::vector files; + for (const auto& path : paths) + { + std::error_code ec; + if (fs::is_regular_file(path, ec) && is_capture(path)) + files.push_back(path); + else if (fs::is_directory(path, ec)) + { + const auto chunks = hesai_recorder_chunks(path); + if (chunks.empty()) + return {}; + files.insert(files.end(), chunks.begin(), chunks.end()); + } + else + return {}; + } + return files; + } + + //! The deepest folder that holds every file. + fs::path common_folder(const std::vector& files) + { + if (files.empty()) + return {}; + fs::path common = files.front().parent_path(); + for (const auto& file : files) + { + const fs::path folder = file.parent_path(); + fs::path shared; + for (auto a = common.begin(), b = folder.begin(); a != common.end() && b != folder.end() && *a == *b; ++a, ++b) + shared /= *a; + common = shared; + } + return common; + } + + ChunkStamp file_stamp(const fs::path& file) + { + std::error_code ec; + ChunkStamp s; + s.size = fs::file_size(file, ec); + if (!ec) + s.time = fs::last_write_time(file, ec); + s.valid = !ec; + return s; + } +} // namespace + +HesaiPcapSource::HesaiPcapSource(std::vector files, fs::path correction, uint16_t udp_port) + : files_(std::move(files)) + , correction_(std::move(correction)) + , udp_port_(udp_port) +{ +} + +fs::path HesaiPcapSource::workingDirectory() const +{ + return common_folder(files_); +} + +size_t HesaiPcapSource::chunkCount() const +{ + return files_.size(); +} + +std::string HesaiPcapSource::chunkName(size_t i) const +{ + return files_[i].string(); +} + +std::vector HesaiPcapSource::loadPoints(size_t i, const PointFilter& filter) const +{ + std::vector points; + size_t total = 0; + HesaiDecoder decoder(correction_); + decoder.onFrame = [&](std::vector&& frame) + { + total += frame.size(); + for (const auto& p : frame) + { + if (filter.omit_timestamp_zero && p.timestamp == 0.0) + continue; + const double r = std::sqrt(static_cast(p.x) * p.x + static_cast(p.y) * p.y); + if (r <= filter.xy_inner || r >= filter.xy_outer) + continue; + Point3Di q{}; + q.point = Eigen::Vector3d(p.x, p.y, p.z); + q.timestamp = p.timestamp; + q.intensity = p.intensity; + q.lidarid = 0; + points.push_back(q); + } + }; + std::string error; + if (!decode_hesai_capture(files_[i], udp_port_, decoder, error)) + std::cerr << "reading '" << chunkName(i) << "' failed: " << error << "\n"; + decoder.finish(); + if (!decoder.error().empty()) + std::cerr << "'" << chunkName(i) << "': " << decoder.error() << "\n"; + + std::sort( + points.begin(), + points.end(), + [](const Point3Di& a, const Point3Di& b) + { + return a.timestamp < b.timestamp; + }); + std::cout << chunkName(i) << ": " << total << " - " << total - points.size() << " = " << points.size() << std::endl; + return points; +} + +ChunkStamp HesaiPcapSource::stamp(size_t i) const +{ + return file_stamp(files_[i]); +} + +void HesaiPcapSource::loadImu(Imu& imu_data, std::vector& imuSpans, const std::function& progress) const +{ + // The IMU samples travel in the point packets, so every packet is decoded once (without computing the points). + uint64_t total_bytes = 0; + for (const auto& file : files_) + { + std::error_code ec; + total_bytes += fs::file_size(file, ec); + } + uint64_t done_bytes = 0; + // One decoder for every file: they are one continuous recording, and the decoder drops a sample repeated in the + // next packet, which at a file boundary is the first packet of the next file. + HesaiDecoder decoder(correction_, /*decode_points=*/false); + size_t first = 0; + decoder.onImu = [&](const rosbags::McapImuSample& s) + { + imu_data.emplace_back( + std::pair(s.timestamp, 0.0), Eigen::Vector3f(s.gyro_x, s.gyro_y, s.gyro_z), Eigen::Vector3f(s.acc_x, s.acc_y, s.acc_z)); + }; + for (const auto& file : files_) + { + std::cout << "loading IMU data from '" << file.string() << "' ..\n"; + first = imu_data.size(); + std::string error; + uint64_t file_bytes = 0; + const bool ok = decode_hesai_capture( + file, + udp_port_, + decoder, + error, + [&](uint64_t read) + { + file_bytes = read; + if (progress && total_bytes > 0) + progress(static_cast(done_bytes + read) / static_cast(total_bytes)); + }); + if (!ok) + std::cerr << "reading IMU from '" << file.string() << "' failed: " << error << "\n"; + done_bytes += file_bytes; + + InputFileSpan span{ file.string() }; + for (size_t k = first; k < imu_data.size(); ++k) + { + const double t = std::get<0>(imu_data[k]).first; + span.first = span.count == 0 ? t : std::min(span.first, t); + span.last = span.count == 0 ? t : std::max(span.last, t); + span.count++; + } + imuSpans.push_back(span); + } +} + +std::string HesaiPcapSource::name() +{ + return "Hesai pcap"; +} + +int HesaiPcapSource::priority() +{ + return 10; +} + +bool HesaiPcapSource::accepts(const std::vector& paths) +{ + return !captures(paths).empty(); +} + +std::shared_ptr HesaiPcapSource::open(const std::vector& paths, std::string& error) +{ + error.clear(); + auto files = captures(paths); + if (files.empty()) + { + error = "no .pcap or .pcap.zst file"; + return nullptr; + } + std::error_code ec; + const fs::path folder = !paths.empty() && fs::is_directory(paths.front(), ec) ? paths.front() : files.front().parent_path(); + const fs::path correction = folder / "correction.dat"; + if (!fs::is_regular_file(correction, ec)) + { + error = "no angle correction (correction.dat) in " + folder.string(); + return nullptr; + } + return std::make_shared(std::move(files), correction); +} + +std::vector HesaiPcapSource::fileFilter() +{ + return { "Hesai capture (*.pcap *.pcap.zst)", "*.pcap *.zst" }; +} + +HDMAPPING_REGISTER_RECORDING_SOURCE(HesaiPcapSource) diff --git a/recording_sources/hesai_pcap_source.h b/recording_sources/hesai_pcap_source.h new file mode 100644 index 00000000..231946ed --- /dev/null +++ b/recording_sources/hesai_pcap_source.h @@ -0,0 +1,64 @@ +#pragma once + +#include "recording_source_factory.h" + +#include +#include +#include +#include +#include + +// No rosbags or Hesai SDK header here: the rosbags headers must come before any standard header on MSVC (see +// rosbags/McapWriter.h), which a header included by GUI code cannot guarantee. + +/** + * @brief Hesai pcap captures as a recording: a lidar_recorder session (its lidarNNNN.pcap.zst chunks) or a set of .pcap + * / .pcap.zst files, each file one chunk, decoded with the lidar's angle correction (correction.dat next to the files). + * + * Every read decodes its file with its own HesaiDecoder, so chunks load from several threads at once. Points keep the + * lidar frame (lidar id 0, no calibration) on the lidar clock; the IMU samples carried in the point packets come out in + * g and rad/s. The working directory is the deepest folder holding every file. + */ +class HesaiPcapSource final : public RecordingSource +{ +public: + /** + * @brief A recording of these files. + * @param files Captures in recording order. + * @param correction The lidar's angle correction. + * @param udp_port The point cloud destination port. + */ + HesaiPcapSource(std::vector files, std::filesystem::path correction, uint16_t udp_port = 2368); + + std::filesystem::path workingDirectory() const override; + size_t chunkCount() const override; + std::string chunkName(size_t i) const override; + std::vector loadPoints(size_t i, const PointFilter& filter) const override; + ChunkStamp stamp(size_t i) const override; + void loadImu(Imu& imu_data, std::vector& imuSpans, const std::function& progress) const override; + + /** @return "Hesai pcap". */ + static std::string name(); + /** @return Above the Mandeye LAZ/CSV kind, which accepts any folder. */ + static int priority(); + /** + * @brief True when every path is a .pcap / .pcap.zst file or a folder holding lidarNNNN.pcap[.zst] chunks. + * @param paths Files and folders as picked or dropped. + * @return Whether this kind reads them. + */ + static bool accepts(const std::vector& paths); + /** + * @brief Opens the captures of paths, with correction.dat from the first folder or the first file's folder. + * @param paths Files and folders as picked or dropped. + * @param error Set when they cannot be opened. + * @return The recording, or null. + */ + static std::shared_ptr open(const std::vector& paths, std::string& error); + /** @return File dialog filter of Hesai captures. */ + static std::vector fileFilter(); + +private: + std::vector files_; + std::filesystem::path correction_; + uint16_t udp_port_; +}; diff --git a/recording_sources/recording_sources.cmake b/recording_sources/recording_sources.cmake index 5a3081d3..6996d118 100644 --- a/recording_sources/recording_sources.cmake +++ b/recording_sources/recording_sources.cmake @@ -12,7 +12,7 @@ set(RECORDING_SOURCE_CORE_FILES ) # Every kind. ROS1 bag / MCAP: the rosbags readers; McapWriter.cpp holds the single MCAP_IMPLEMENTATION that -# McapReader.cpp relies on. +# McapReader.cpp relies on. Hesai pcap: the Hesai SDK's parser through hesai_decoder. set(RECORDING_SOURCE_FILES ${RECORDING_SOURCE_CORE_FILES} ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.h ${REPOSITORY_DIRECTORY}/recording_sources/bag_source.cpp @@ -20,4 +20,16 @@ set(RECORDING_SOURCE_FILES ${REPOSITORY_DIRECTORY}/rosbags/McapReader.cpp ${REPOSITORY_DIRECTORY}/rosbags/McapWriter.cpp ${REPOSITORY_DIRECTORY}/rosbags/Ros1Bag.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/hesai_pcap_source.h ${REPOSITORY_DIRECTORY}/recording_sources/hesai_pcap_source.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.h ${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.cpp + ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.h ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.cpp ) + +# Libraries the kinds above need: link them with RECORDING_SOURCE_FILES. +set(RECORDING_SOURCE_LIBRARIES mcap ros1bag_compression hesai_sdk hdmapping_zstd) + +# The files that include Hesai SDK headers (see cmake/dependencies.cmake). +set_source_files_properties( + ${REPOSITORY_DIRECTORY}/recording_sources/hesai_pcap_source.cpp + ${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.cpp + PROPERTIES COMPILE_OPTIONS "${HESAI_MACOS_FLAGS}") From 731d09e148fdc37a4d6c11e8ff6dc8979eed3538 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 17:01:43 +0100 Subject: [PATCH 14/21] hesai_pcap_to_laz: read through the recording sources The converter no longer decodes Hesai packets or chunks the stream itself: it opens its inputs with RecordingSourceFactory, as lidar_odometry_step_1 does, and writes each chunk's points (unfiltered) and the IMU samples through MandeyeSessionWriter. Step 1 and the converter now read through the same code, and any registered kind converts the same way. - One output chunk per recording chunk (per .pcap.zst file for Hesai); --chunk-seconds, --correction and --udp-port are gone (correction.dat next to the files, as the source requires). - No ring attribute (Point3Di has none) and no gnssNNNN.nmea copy. - MandeyeSessionChunker, used only here, is removed. Tested on a JT128 lidar_recorder session: 24,624,038 points and 13,875 IMU samples written, the same step 1 loads from the pcaps directly and from the converted session. Co-Authored-By: Claude Opus 5.5 --- apps/console_tools/CMakeLists.txt | 36 ++- apps/console_tools/hesai_pcap_to_laz.cpp | 291 ++++++++--------------- rosbags/MandeyeSessionChunker.cpp | 99 -------- rosbags/MandeyeSessionChunker.h | 66 ----- 4 files changed, 127 insertions(+), 365 deletions(-) delete mode 100644 rosbags/MandeyeSessionChunker.cpp delete mode 100644 rosbags/MandeyeSessionChunker.h diff --git a/apps/console_tools/CMakeLists.txt b/apps/console_tools/CMakeLists.txt index 66d1f10f..8b476fc7 100644 --- a/apps/console_tools/CMakeLists.txt +++ b/apps/console_tools/CMakeLists.txt @@ -206,31 +206,43 @@ if (MSVC) target_compile_options(laz_to_mcap PRIVATE /bigobj) endif() -# hesai_pcap_to_laz: Hesai pcap (or a lidar_recorder session of .pcap.zst chunks) -> mandeye session directory. -# Same writer and chunking as mcap_to_laz; the packets are decoded by recording_sources/hesai_decoder (the Hesai LiDAR -# SDK's parser, 3rdparty/HesaiLidar_SDK_2.0), as lidar_odometry_step_1 reads a capture directly. +# hesai_pcap_to_laz: a recording -> mandeye session directory, read through the recording sources +# (recording_sources/) exactly as lidar_odometry_step_1 reads it: Hesai .pcap / .pcap.zst captures or a lidar_recorder +# session, or any other registered kind. The kinds register themselves, so their files are compiled in here. +include(${REPOSITORY_DIRECTORY}/recording_sources/recording_sources.cmake) add_executable( hesai_pcap_to_laz hesai_pcap_to_laz.cpp - ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.h ${REPOSITORY_DIRECTORY}/rosbags/PcapUdpReader.cpp + ${RECORDING_SOURCE_FILES} + ${REPOSITORY_DIRECTORY}/apps/lidar_odometry_step_1/lidar_odometry_utils.h + ${REPOSITORY_DIRECTORY}/apps/lidar_odometry_step_1/lidar_odometry_utils.cpp ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionWriter.h ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionWriter.cpp - ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionChunker.h ${REPOSITORY_DIRECTORY}/rosbags/MandeyeSessionChunker.cpp - ${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.h ${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.cpp ) -set_source_files_properties(${REPOSITORY_DIRECTORY}/recording_sources/hesai_decoder.cpp PROPERTIES COMPILE_OPTIONS "${HESAI_MACOS_FLAGS}") target_include_directories( hesai_pcap_to_laz - PRIVATE ${REPOSITORY_DIRECTORY}/rosbags ${REPOSITORY_DIRECTORY}/recording_sources - ${LASZIP_INCLUDE_DIR}/LASzip/include) + PRIVATE ${REPOSITORY_DIRECTORY}/apps/lidar_odometry_step_1 + ${REPOSITORY_DIRECTORY}/recording_sources + ${REPOSITORY_DIRECTORY}/rosbags + ${REPOSITORY_DIRECTORY}/core/include + ${THIRDPARTY_DIRECTORY} + ${THIRDPARTY_DIRECTORY}/glm + ${EIGEN3_INCLUDE_DIR} + ${THIRDPARTY_DIRECTORY}/tomlplusplus/include + ${THIRDPARTY_DIRECTORY}/json/include + ${LASZIP_INCLUDE_DIR}/LASzip/include + ${THIRDPARTY_DIRECTORY}/observation_equations/codes + ${THIRDPARTY_DIRECTORY}/vqf/vqf/cpp) target_link_libraries( hesai_pcap_to_laz PRIVATE - hesai_sdk - hdmapping_zstd + ${RECORDING_SOURCE_LIBRARIES} + unordered_dense::unordered_dense spdlog::spdlog ${PLATFORM_LASZIP_LIB} - ${PLATFORM_MISCELLANEOUS_LIBS}) + ${PLATFORM_MISCELLANEOUS_LIBS} + ${CORE_LIBRARIES} + imgui_raylib) # the bag kinds' option forms (bag_source_ui.cpp) # bow_loop_closure_detect: headless verification tool for the automatic # image-based (fbow) loop closure detector shared with step 2's GUI -- diff --git a/apps/console_tools/hesai_pcap_to_laz.cpp b/apps/console_tools/hesai_pcap_to_laz.cpp index 605b79ae..9c84f8e6 100644 --- a/apps/console_tools/hesai_pcap_to_laz.cpp +++ b/apps/console_tools/hesai_pcap_to_laz.cpp @@ -1,24 +1,23 @@ -// hesai_pcap_to_laz: Hesai pcap captures (.pcap, or zstd-compressed .pcap.zst as lidar_recorder writes them) -> -// mandeye session directory, as mcap_to_laz and ouster_pcap_to_laz write one. +// hesai_pcap_to_laz: a recording -> mandeye session directory, read through the recording sources exactly as +// lidar_odometry_step_1 reads it. Meant for Hesai captures (.pcap / .pcap.zst files or a lidar_recorder session +// directory), but any registered recording kind converts the same way. // -// The packets are decoded by HesaiDecoder (the Hesai LiDAR SDK's parser) with the lidar's angle correction, as -// lidar_odometry_step_1 reads a capture directly; points and IMU samples are on the lidar clock. A lidar_recorder session directory stands -// for its lidarNNNN.pcap.zst chunks, and its gnssNNNN.nmea files (lidar-clock times, already in the mandeye format) are copied next to the -// result. +// Each chunk of the recording becomes one lidarNNNN.laz (all its points, nothing filtered); every IMU sample goes to the +// imuNNNN.csv of the chunk open at its time. // See rosbags/McapWriter.h: the rosbags headers come before any standard header. -#include "MandeyeSessionChunker.h" #include "MandeyeSessionWriter.h" -#include "hesai_decoder.h" + +#include "recording_source_factory.h" #include "console_progress.h" #include #include -#include #include #include +#include #include #include @@ -28,231 +27,147 @@ namespace { void print_usage(const char* argv0) { - spdlog::error("Usage: {} [ ...] [options]", argv0); - spdlog::error(" input a Hesai capture (classic pcap, optionally zstd-compressed as a whole), or a"); - spdlog::error(" lidar_recorder session directory (its lidarNNNN.pcap.zst chunks, in order);"); - spdlog::error(" several inputs are read in the order given into one session"); - spdlog::error(" output_session_dir written as mandeye lidarNNNN.laz + imuNNNN.csv chunk pairs,"); - spdlog::error(" ready to open in lidar_odometry_step_1"); - spdlog::error("Options:"); - spdlog::error(" --chunk-seconds chunk length in seconds (default: 10, mandeye's own"); - spdlog::error(" cadence; 0 = one single chunk)"); - spdlog::error(" --correction the lidar's angle correction (default: correction.dat next to"); - spdlog::error(" the first input)"); - spdlog::error(" --udp-port point cloud UDP destination port (default: 2368)"); - spdlog::error(""); - spdlog::error("The lidar ring is kept as the LAS extra-bytes attribute 'ring'. No calibration.json or .sn"); - spdlog::error("file is written, so lidar_odometry_step_1 applies no extrinsics to the result."); + spdlog::error("Usage: {} [ ...] ", argv0); + spdlog::error(" input a recording lidar_odometry_step_1 opens: Hesai .pcap / .pcap.zst files or a"); + spdlog::error(" lidar_recorder session directory (correction.dat next to them), ROS1 bags, MCAP files"); + spdlog::error(" output_session_dir written as mandeye lidarNNNN.laz + imuNNNN.csv chunk pairs, one per"); + spdlog::error(" chunk of the recording"); + spdlog::error("No calibration.json or .sn file is written, so lidar_odometry_step_1 applies no extrinsics."); } } // namespace int main(const int argc, const char** argv) { - std::vector positionals; - double chunk_seconds = 10.0; - fs::path correction; - int udp_port = 2368; - + std::vector paths; for (int i = 1; i < argc; ++i) { const std::string arg = argv[i]; - const bool hasValue = i + 1 < argc; - if (arg == "--chunk-seconds" && hasValue) - { - const std::string value = argv[++i]; - try - { - chunk_seconds = std::stod(value); - } catch (const std::exception&) - { - spdlog::error("Invalid --chunk-seconds '{}' (expected a number)", value); - return EXIT_FAILURE; - } - if (!std::isfinite(chunk_seconds) || chunk_seconds < 0.0) - { - spdlog::error("Invalid --chunk-seconds '{}' (expected >= 0; 0 = one single chunk)", value); - return EXIT_FAILURE; - } - } - else if (arg == "--correction" && hasValue) - correction = argv[++i]; - else if (arg == "--udp-port" && hasValue) - { - const std::string value = argv[++i]; - try - { - udp_port = std::stoi(value); - } catch (const std::exception&) - { - spdlog::error("Invalid --udp-port '{}' (expected a number)", value); - return EXIT_FAILURE; - } - } - else if (!arg.starts_with("--")) - positionals.push_back(arg); - else + if (arg.starts_with("--")) { spdlog::error("Unrecognized argument '{}'", arg); print_usage(argv[0]); return EXIT_FAILURE; } + paths.emplace_back(arg); } - - // Every positional is an input except the last, the session dir. - if (positionals.size() < 2) + if (paths.size() < 2) { print_usage(argv[0]); return EXIT_FAILURE; } - const fs::path session_dir = positionals.back(); - positionals.pop_back(); + const fs::path session_dir = paths.back(); + paths.pop_back(); - // A lidar_recorder session directory stands for its chunks; its metadata and GNSS files live next to them. - std::vector inputs; - std::vector recorder_dirs; - for (const auto& input : positionals) + const auto kind = RecordingSourceFactory::find(paths); + if (!kind) { - if (fs::is_directory(input)) - { - const auto chunks = hesai_recorder_chunks(input); - if (chunks.empty()) - { - spdlog::error("No lidarNNNN.pcap.zst or .pcap in {}", input); - return EXIT_FAILURE; - } - inputs.insert(inputs.end(), chunks.begin(), chunks.end()); - recorder_dirs.emplace_back(input); - } - else if (!fs::exists(input)) - { - spdlog::error("Input file {} does not exist", input); - return EXIT_FAILURE; - } - else - inputs.emplace_back(input); + spdlog::error("No recording kind reads '{}'", paths.front().string()); + return EXIT_FAILURE; } - if (correction.empty()) - correction = - (fs::is_directory(positionals.front()) ? fs::path(positionals.front()) : inputs.front().parent_path()) / "correction.dat"; - if (!fs::is_regular_file(correction)) + std::string error; + const auto source = kind->open(paths, error); + if (!source) { - spdlog::error("No angle correction at {} - pass --correction", correction.string()); + spdlog::error("Cannot read '{}' as {}: {}", paths.front().string(), kind->name(), error); return EXIT_FAILURE; } + spdlog::info("Reading '{}' as {}: {} chunk(s)", paths.front().string(), kind->name(), source->chunkCount()); - rosbags::MandeyeSessionWriter writer(session_dir, /*with_rgb=*/false, /*with_ring=*/true); + rosbags::MandeyeSessionWriter writer(session_dir); if (!writer.isOpen()) { spdlog::error("Cannot write session directory: {}", writer.error()); return EXIT_FAILURE; } - rosbags::MandeyeSessionChunker chunker(writer, chunk_seconds); - spdlog::info("Reading {} input(s) with angle correction {}", inputs.size(), correction.string()); - bool write_ok = true; - uint64_t frames = 0; - HesaiDecoder decoder(correction); - decoder.onFrame = [&](std::vector&& points) - { - if (write_ok && !chunker.addPoints(points)) - write_ok = false; - ++frames; - }; - decoder.onImu = [&](const rosbags::McapImuSample& sample) - { - chunker.addImu(sample); - }; - - uint64_t input_bytes = 0; - for (const auto& path : inputs) - { - std::error_code ec; - input_bytes += fs::file_size(path, ec); - } - ConsoleProgress progress("Reading pcap (bytes)", input_bytes); - uint64_t bytes_before = 0; - bool read_ok = true; - for (const auto& path : inputs) + Imu imu; + std::vector imu_spans; + constexpr uint64_t kImuSteps = 1000; + ConsoleProgress imu_progress("Reading IMU", kImuSteps); + source->loadImu( + imu, + imu_spans, + [&](double fraction) + { + imu_progress.update(static_cast(fraction * kImuSteps)); + }); + imu_progress.finish(imu.size()); + std::sort( + imu.begin(), + imu.end(), + [](const auto& a, const auto& b) + { + return std::get<0>(a).first < std::get<0>(b).first; + }); + + // Every point: no filter. + PointFilter filter; + filter.omit_timestamp_zero = false; + filter.xy_inner = -1.0; + filter.xy_outer = std::numeric_limits::infinity(); + + std::vector chunk_start; // first point time of each written chunk + ConsoleProgress chunk_progress("Writing chunks", source->chunkCount()); + for (size_t i = 0; i < source->chunkCount(); ++i) { - // One decoder for all inputs: they are one continuous recording, so a frame spanning two files stays whole. - std::string error; - uint64_t bytes = 0; - if (!decode_hesai_capture( - path, - static_cast(udp_port), - decoder, - error, - [&](uint64_t read) - { - bytes = read; - progress.update(bytes_before + read); - })) + const auto points = source->loadPoints(i, filter); + chunk_progress.update(i + 1); + if (points.empty()) + continue; + std::vector out(points.size()); + for (size_t k = 0; k < points.size(); ++k) { - spdlog::warn("{}: {} - kept what was read", path.string(), error); - read_ok = false; + out[k].x = static_cast(points[k].point.x()); + out[k].y = static_cast(points[k].point.y()); + out[k].z = static_cast(points[k].point.z()); + out[k].intensity = points[k].intensity; + out[k].timestamp = points[k].timestamp; + } + if (!writer.beginChunk(static_cast(chunk_start.size())) || !writer.addPoints(out) || !writer.endChunk()) + { + spdlog::error("Failed writing {}: {}", source->chunkName(i), writer.error()); + return EXIT_FAILURE; } - bytes_before += bytes; + chunk_start.push_back(points.front().timestamp); } - decoder.finish(); - progress.finish(bytes_before); - if (!decoder.error().empty()) + chunk_progress.finish(source->chunkCount()); + if (chunk_start.empty()) { - spdlog::error("{}", decoder.error()); + spdlog::error("No points in '{}' - nothing to write", paths.front().string()); return EXIT_FAILURE; } - if (!write_ok) + // Each IMU sample goes to the chunk open at its time; samples before all lidar data to the first chunk. + std::vector> per_chunk(chunk_start.size()); + for (const auto& [timestamps, gyro, acc] : imu) { - spdlog::error("Failed writing lidar chunks: {}", writer.error()); - return EXIT_FAILURE; - } - if (chunker.chunks() == 0) - { - spdlog::error("No points decoded on UDP port {} - nothing to write", udp_port); - return EXIT_FAILURE; + const double t = timestamps.first; + const auto it = std::upper_bound(chunk_start.begin(), chunk_start.end(), t); + const size_t index = it == chunk_start.begin() ? 0 : static_cast(it - chunk_start.begin() - 1); + rosbags::McapImuSample s; + s.timestamp = t; + s.gyro_x = gyro.x(); + s.gyro_y = gyro.y(); + s.gyro_z = gyro.z(); + s.acc_x = acc.x(); + s.acc_y = acc.y(); + s.acc_z = acc.z(); + per_chunk[index].push_back(s); } - if (!chunker.finish()) + for (size_t k = 0; k < per_chunk.size(); ++k) { - spdlog::error("Failed writing IMU chunks: {}", writer.error()); - return EXIT_FAILURE; + if (!writer.writeImuChunk(static_cast(k), per_chunk[k])) + { + spdlog::error("Failed writing IMU chunk {}: {}", k, writer.error()); + return EXIT_FAILURE; + } } spdlog::info( - "Wrote {} chunk(s) to {}: {} point(s) from {} frame(s), {} IMU sample(s)", - chunker.chunks(), + "Wrote {} chunk(s) to {}: {} point(s), {} IMU sample(s)", + chunk_start.size(), session_dir.string(), writer.pointsWritten(), - frames, writer.imuSamplesWritten()); - if (chunker.outOfOrder()) - spdlog::warn("Frames were not in ascending time order - chunk boundaries may not be monotonic"); - // lidar_odometry_step_1's load_data() needs more than two input files and then discards the first chunk's points - // outright, so a session of one or two chunks contributes little or nothing there. - if (chunker.chunks() < 3) - spdlog::warn( - "Only {} chunk(s): lidar_odometry_step_1 requires more than two files and discards the first chunk's points - " - "use a smaller --chunk-seconds", - chunker.chunks()); - - // lidar_recorder's GNSS files (gnssNNNN.nmea, lidar-clock times) are already in the mandeye format. - int nmea = 0; - for (const auto& dir : recorder_dirs) - { - std::error_code ec; - for (const auto& e : fs::directory_iterator(dir, ec)) - { - const auto name = e.path().filename().string(); - if (e.is_regular_file() && name.rfind("gnss", 0) == 0 && e.path().extension() == ".nmea") - { - fs::copy_file(e.path(), session_dir / name, fs::copy_options::overwrite_existing, ec); - if (ec) - spdlog::warn("Cannot copy {}: {}", e.path().string(), ec.message()); - else - ++nmea; - } - } - } - if (nmea > 0) - spdlog::info("Copied {} gnssNNNN.nmea file(s) to {}", nmea, session_dir.string()); - return read_ok ? EXIT_SUCCESS : EXIT_FAILURE; + return EXIT_SUCCESS; } diff --git a/rosbags/MandeyeSessionChunker.cpp b/rosbags/MandeyeSessionChunker.cpp deleted file mode 100644 index 524a952f..00000000 --- a/rosbags/MandeyeSessionChunker.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include "MandeyeSessionChunker.h" - -#include -#include -#include -#include -#include - -namespace rosbags -{ - -MandeyeSessionChunker::MandeyeSessionChunker(MandeyeSessionWriter& writer, double chunk_seconds) - : writer_(writer) - , chunk_seconds_(chunk_seconds) - , last_stamp_(-std::numeric_limits::infinity()) -{ -} - -int64_t MandeyeSessionChunker::timeBin(double timestamp_s) const -{ - if (chunk_seconds_ <= 0.0) - return 0; // splitting disabled: everything lands in one chunk - return static_cast(std::floor(timestamp_s / chunk_seconds_)); -} - -bool MandeyeSessionChunker::addPoints(const std::vector& points) -{ - if (points.empty()) - return true; - const double stamp_s = points.front().timestamp; - if (stamp_s < last_stamp_) - out_of_order_ = true; - last_stamp_ = stamp_s; - - const int64_t bin = timeBin(stamp_s); - if (chunk_bins_.empty() || bin != chunk_bins_.back()) - { - if (!writer_.beginChunk(static_cast(chunk_bins_.size()))) - return false; - chunk_bins_.push_back(bin); - } - return writer_.addPoints(points); -} - -void MandeyeSessionChunker::addImu(const McapImuSample& sample) -{ - imu_.push_back(sample); -} - -bool MandeyeSessionChunker::finish() -{ - if (!chunk_bins_.empty() && !writer_.endChunk()) - return false; - if (chunk_bins_.empty()) - return true; - - // chunk_bins_ is ascending when clouds arrive in time order, but an out-of-order input (a file-order read, a clock - // step) can break that, and upper_bound on an unsorted range would route samples arbitrarily: search a sorted - // (bin, chunk index) view instead. - std::vector> bin_to_chunk; - bin_to_chunk.reserve(chunk_bins_.size()); - for (size_t i = 0; i < chunk_bins_.size(); ++i) - bin_to_chunk.emplace_back(chunk_bins_[i], i); - std::sort(bin_to_chunk.begin(), bin_to_chunk.end()); - - std::vector> per_chunk(chunk_bins_.size()); - for (const auto& sample : imu_) - { - const int64_t bin = timeBin(sample.timestamp); - const auto it = std::upper_bound( - bin_to_chunk.begin(), - bin_to_chunk.end(), - bin, - [](int64_t value, const std::pair& entry) - { - return value < entry.first; - }); - const size_t index = (it == bin_to_chunk.begin()) ? bin_to_chunk.front().second : std::prev(it)->second; - per_chunk[index].push_back(sample); - } - for (size_t i = 0; i < per_chunk.size(); ++i) - { - if (!writer_.writeImuChunk(static_cast(i), per_chunk[i])) - return false; - } - return true; -} - -size_t MandeyeSessionChunker::chunks() const -{ - return chunk_bins_.size(); -} - -bool MandeyeSessionChunker::outOfOrder() const -{ - return out_of_order_; -} - -} // namespace rosbags diff --git a/rosbags/MandeyeSessionChunker.h b/rosbags/MandeyeSessionChunker.h deleted file mode 100644 index 4d165919..00000000 --- a/rosbags/MandeyeSessionChunker.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include "MandeyeSessionWriter.h" // McapPoint, McapImuSample (via McapWriter.h) -- first, see McapWriter.h - -#include -#include - -namespace rosbags -{ - -/** - * @brief Splits a stream of point clouds and IMU samples into the chunks of a Mandeye session, as the bag and pcap - * converters write them. - * - * Chunks follow an absolute time grid: a timestamp t belongs to bin floor(t / chunk_seconds), so lidar and IMU bin - * identically without agreeing on a time origin. A cloud is never split: it lands in the bin of its first point. IMU - * samples are kept until finish(), then each goes into the chunk that was open at its time (the last chunk whose bin is - * not after the sample's, the first chunk for samples before all lidar data). No sample is dropped. - */ -class MandeyeSessionChunker -{ -public: - /** - * @brief Writes through `writer`, which must outlive the chunker. - * @param writer The session writer. - * @param chunk_seconds Chunk length in seconds; 0 or less writes one chunk. - */ - MandeyeSessionChunker(MandeyeSessionWriter& writer, double chunk_seconds); - - /** - * @brief Writes one cloud, opening a new chunk when its first point starts a new time bin. - * @param points Points with absolute timestamps in seconds. - * @return False on a write error (see the writer's error()). - */ - bool addPoints(const std::vector& points); - - /** - * @brief Keeps one IMU sample for finish(). - * @param sample Sample with an absolute timestamp in seconds. - */ - void addImu(const McapImuSample& sample); - - /** - * @brief Closes the last chunk and writes every chunk's imuNNNN.csv. - * @return False on a write error (see the writer's error()). - */ - bool finish(); - - /** @return Chunks written so far. */ - size_t chunks() const; - - /** @return True when a cloud started earlier than the one before it. */ - bool outOfOrder() const; - -private: - int64_t timeBin(double timestamp_s) const; - - MandeyeSessionWriter& writer_; - double chunk_seconds_; - std::vector chunk_bins_; - std::vector imu_; - double last_stamp_; - bool out_of_order_ = false; -}; - -} // namespace rosbags From 19acd2106b4421a2595e3ca77082436c055b14d9 Mon Sep 17 00:00:00 2001 From: Michal Pelka Date: Fri, 27 Nov 2026 17:53:51 +0100 Subject: [PATCH 15/21] Hesai pcap: take the IMU from the Mandeye IMU files when the lidar has none A Mandeye unit with a Hesai lidar that has no IMU (or one the unit does not use) logs the IMU itself, like a Livox recording: into imu****.csv, or, with an external Murata IMU, into MURATA_IMU. When the first capture carries no IMU samples, HesaiPcapSource now loads those files of the recording folder instead of decoding the rest of the packets. The loading is LazCsvSource's, moved into load_mandeye_imu() so both sources share it; LazCsvSource behaves as before. Tested on a Mandeye recording with a Pandar lidar and a Murata IMU (10 pcaps, 79.7 M points, 58,058 Murata samples): hesai_pcap_to_laz converts it and lidar_odometry_step_1 runs through on the result. Co-Authored-By: Claude Opus 5.5 --- recording_sources/hesai_pcap_source.cpp | 26 +++++++++++++++++++++++++ recording_sources/laz_csv_source.cpp | 22 +++++++++++++-------- recording_sources/laz_csv_source.h | 16 +++++++++++++++ 3 files changed, 56 insertions(+), 8 deletions(-) diff --git a/recording_sources/hesai_pcap_source.cpp b/recording_sources/hesai_pcap_source.cpp index 8fd7aada..d4b2fa13 100644 --- a/recording_sources/hesai_pcap_source.cpp +++ b/recording_sources/hesai_pcap_source.cpp @@ -2,6 +2,7 @@ #include "hesai_decoder.h" #include "hesai_pcap_source.h" +#include "laz_csv_source.h" #include #include @@ -145,6 +146,8 @@ void HesaiPcapSource::loadImu(Imu& imu_data, std::vector& imuSpan std::error_code ec; total_bytes += fs::file_size(file, ec); } + const size_t samples_before = imu_data.size(); + const size_t spans_before = imuSpans.size(); uint64_t done_bytes = 0; // One decoder for every file: they are one continuous recording, and the decoder drops a sample repeated in the // next packet, which at a file boundary is the first packet of the next file. @@ -185,6 +188,29 @@ void HesaiPcapSource::loadImu(Imu& imu_data, std::vector& imuSpan span.count++; } imuSpans.push_back(span); + + // A lidar without an IMU (or one the Mandeye unit does not use): the unit logged the IMU itself, as for a Livox + // recording, into imu****.csv or an external IMU's MURATA_IMU folder next to the captures. + if (imu_data.size() == samples_before) + { + const fs::path folder = workingDirectory(); + std::vector csv_files; + std::error_code ec; + for (const auto& e : fs::directory_iterator(folder, ec)) + { + const std::string n = e.path().filename().string(); + if (e.is_regular_file() && n.rfind("imu", 0) == 0 && e.path().extension() == ".csv") + csv_files.push_back(e.path().string()); + } + std::sort(csv_files.begin(), csv_files.end()); + std::cout << "no IMU data in the lidar packets of '" << file.string() << "', loading the IMU files of '" << folder.string() + << "' ..\n"; + imuSpans.resize(spans_before); + load_mandeye_imu(csv_files, folder, 0, imu_data, imuSpans); + if (progress) + progress(1.0); + return; + } } } diff --git a/recording_sources/laz_csv_source.cpp b/recording_sources/laz_csv_source.cpp index b6e8c170..72ea5292 100644 --- a/recording_sources/laz_csv_source.cpp +++ b/recording_sources/laz_csv_source.cpp @@ -318,10 +318,15 @@ ChunkStamp LazCsvSource::stamp(size_t i) const void LazCsvSource::loadImu(Imu& imu_data, std::vector& imuSpans, const std::function&) const { - // --- Load IMU data (still sequential, could parallelize later) std::cout << "loading IMU data from 'imu****.csv' using ID " << imu_number_to_use_ << " from reference '" << sn_file_ << "' ..\n"; + load_mandeye_imu(csv_files_, working_directory_, imu_number_to_use_, imu_data, imuSpans); +} - const std::size_t minSize = csv_files_.size(); +void load_mandeye_imu( + const std::vector& csv_files, const fs::path& folder, int imu_number, Imu& imu_data, std::vector& imuSpans) +{ + // --- Load IMU data (still sequential, could parallelize later) + const std::size_t minSize = csv_files.size(); // Each thread loads into its own local vector std::vector imuChunks(minSize); @@ -331,21 +336,22 @@ void LazCsvSource::loadImu(Imu& imu_data, std::vector& imuSpans, { for (size_t i = range.begin(); i < range.end(); ++i) { - imuChunks[i] = load_imu(csv_files_[i].c_str(), imu_number_to_use_); + imuChunks[i] = load_imu(csv_files[i].c_str(), imu_number); } }); for (size_t i = 0; i < minSize; ++i) - imuSpans.push_back(imu_file_span(csv_files_[i], imuChunks[i])); + imuSpans.push_back(imu_file_span(csv_files[i], imuChunks[i])); // Merge all chunks sequentially at the end + const size_t first = imu_data.size(); for (auto& chunk : imuChunks) imu_data.insert(imu_data.end(), std::make_move_iterator(chunk.begin()), std::make_move_iterator(chunk.end())); // Units with an external IMU (e.g. Murata) leave 'imu****.csv' header-only and log the IMU // into a subfolder, in files not aligned with the LiDAR chunks - const fs::path murataImuDir = working_directory_ / "MURATA_IMU"; - if (imu_data.empty() && fs::is_directory(murataImuDir)) + const fs::path murataImuDir = folder / "MURATA_IMU"; + if (imu_data.size() == first && fs::is_directory(murataImuDir)) { std::vector murataFiles; for (const auto& entry : fs::directory_iterator(murataImuDir)) @@ -365,9 +371,9 @@ void LazCsvSource::loadImu(Imu& imu_data, std::vector& imuSpans, murataFiles.size(), [&](size_t i) { - murataChunks[i] = load_imu(murataFiles[i], imu_number_to_use_); + murataChunks[i] = load_imu(murataFiles[i], imu_number); }); - imuSpans.clear(); + imuSpans.resize(imuSpans.size() - minSize); for (size_t i = 0; i < murataFiles.size(); ++i) imuSpans.push_back(imu_file_span(murataFiles[i], murataChunks[i])); for (auto& chunk : murataChunks) diff --git a/recording_sources/laz_csv_source.h b/recording_sources/laz_csv_source.h index 69adaad9..8f5899e4 100644 --- a/recording_sources/laz_csv_source.h +++ b/recording_sources/laz_csv_source.h @@ -7,6 +7,22 @@ #include #include +/** + * @brief Loads the IMU of a Mandeye recording: the imu****.csv files, or, when they hold no samples (units with an + * external IMU such as a Murata log into a subfolder instead), the csv files of the folder's MURATA_IMU. + * @param csv_files The recording's imu****.csv files. + * @param folder The recording folder, which holds MURATA_IMU. + * @param imu_number The imuId to read from files that carry one. + * @param imu_data Receives every sample, unsorted. + * @param imuSpans Receives one span per file read. + */ +void load_mandeye_imu( + const std::vector& csv_files, + const std::filesystem::path& folder, + int imu_number, + Imu& imu_data, + std::vector& imuSpans); + //! A Mandeye recording folder: lidarNNNN.laz chunks paired with imuNNNN.csv files by their last four stem characters, //! plus the optional calibration (.mjc or calibration .json), .sn file and MURATA_IMU folder. class LazCsvSource : public RecordingSource From ee8fb8931c8ae5db9e11462820fad6d785ea84eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pe=C5=82ka?= Date: Fri, 27 Nov 2026 19:03:02 +0100 Subject: [PATCH 16/21] raw viewer: warn when a loaded recording shows nothing The viewer places points along the IMU trajectory, so a recording without IMU samples, or whose points lie outside the IMU time span, loaded without error and showed an empty view. A "Nothing to show" window now says why: no points, no IMU samples, or no point within the IMU time span (with both time ranges, as the LiDAR and the IMU may be on different clocks). Co-Authored-By: Claude Opus 5.5 --- .../mandeye_raw_data_viewer.cpp | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp index 7cf84ff0..c360f8ee 100644 --- a/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp +++ b/apps/mandeye_raw_data_viewer/mandeye_raw_data_viewer.cpp @@ -1037,6 +1037,45 @@ void rebuildAllData(bool preserve_position) //! Loads the files of a Mandeye data folder, or the prepared recording when source is set (input_file_names is then //! empty). +std::string load_warning; //!< why the loaded recording shows nothing; shown until dismissed + +//! @return Why the loaded recording shows nothing, or empty when it shows something. +//! @note The viewer places points along the IMU trajectory, so it needs IMU samples spanning the points' time. +std::string empty_view_warning(const Imu& imu_data) +{ + if (!all_data.empty()) + return {}; + size_t points = 0; + double first = std::numeric_limits::max(); + double last = std::numeric_limits::lowest(); + for (const auto& file : g_points_per_file) + { + if (file.empty()) + continue; + points += file.size(); + first = std::min(first, file.front().timestamp); + last = std::max(last, file.back().timestamp); + } + std::ostringstream out; + if (points == 0) + out << "The recording has no points."; + else if (imu_data.empty()) + out << "The recording has no IMU samples, so its " << points << " points cannot be shown:\n" + << "the viewer places them along the IMU trajectory."; + else + { + const double imu_first = std::get<0>(imu_data.front()).first; + const double imu_last = std::get<0>(imu_data.back()).first; + if (last >= imu_first && first <= imu_last) + return {}; + out << std::fixed << std::setprecision(3) << "No point falls within the IMU time span, so nothing can be shown\n" + << "(are the LiDAR and the IMU on different clocks?).\n" + << "IMU: " << imu_first << " .. " << imu_last << " s\n" + << "points: " << first << " .. " << last << " s"; + } + return out.str(); +} + void loadFiles(std::vector input_file_names, const std::shared_ptr& source = nullptr) { LidarOdometryParams params; // dummy for load_data function @@ -1270,6 +1309,10 @@ void loadFiles(std::vector input_file_names, const std::shared_ptr< g_poses_cache = std::move(poses); rebuildAllData(false); + + load_warning = empty_view_warning(imu_data); + if (!load_warning.empty()) + spdlog::warn("{}", load_warning); } } @@ -1371,6 +1414,18 @@ void source_config_window() source_config_ui.reset(); } +//! The load warning, centred until closed. +void load_warning_window() +{ + bool open = true; + ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); + ImGui::Begin("Nothing to show", &open, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", load_warning.c_str()); + ImGui::End(); + if (!open) + load_warning.clear(); +} + void imu_data_gui() { ImGui::Begin("IMU data", &show_imu_data); @@ -2355,6 +2410,9 @@ void display() if (source_config_ui) source_config_window(); + if (!load_warning.empty()) + load_warning_window(); + rlImGuiEnd(); } From d12112db92e8b1e3b86af0f689cfac4f2b8e748c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pe=C5=82ka?= Date: Wed, 2 Dec 2026 19:01:13 +0100 Subject: [PATCH 17/21] Hesai pcap: read lidar_recorder's .pcap.zstd chunks lidar_recorder names its compressed chunks lidarNNNN.pcap.zstd, but the Hesai source looked only for .pcap and .pcap.zst. A session folder was then opened by the Mandeye LAZ/CSV kind, which accepts any folder: it loaded the MURATA_IMU samples, found no LAZ files, and step 1 failed with "Odometry failed". is_hesai_capture() now accepts .pcap, .pcap.zstd and .pcap.zst, and is used both for single files and by hesai_recorder_chunks(), so the two cannot disagree. The reader already detects zstd by its magic number. Tested on a lidar_recorder session with an XT32 and a Murata IMU: three of its .pcap.zstd chunks convert with hesai_pcap_to_laz (25.9 M points, the IMU from MURATA_IMU). Co-Authored-By: Claude Opus 5.5 --- apps/console_tools/CMakeLists.txt | 2 +- apps/console_tools/hesai_pcap_to_laz.cpp | 4 +-- recording_sources/hesai_decoder.cpp | 31 ++++++++++++++++++------ recording_sources/hesai_decoder.h | 9 +++++-- recording_sources/hesai_pcap_source.cpp | 12 +++------ recording_sources/hesai_pcap_source.h | 8 +++--- 6 files changed, 42 insertions(+), 24 deletions(-) diff --git a/apps/console_tools/CMakeLists.txt b/apps/console_tools/CMakeLists.txt index 8b476fc7..f5ebc801 100644 --- a/apps/console_tools/CMakeLists.txt +++ b/apps/console_tools/CMakeLists.txt @@ -207,7 +207,7 @@ if (MSVC) endif() # hesai_pcap_to_laz: a recording -> mandeye session directory, read through the recording sources -# (recording_sources/) exactly as lidar_odometry_step_1 reads it: Hesai .pcap / .pcap.zst captures or a lidar_recorder +# (recording_sources/) exactly as lidar_odometry_step_1 reads it: Hesai .pcap / .pcap.zstd captures or a lidar_recorder # session, or any other registered kind. The kinds register themselves, so their files are compiled in here. include(${REPOSITORY_DIRECTORY}/recording_sources/recording_sources.cmake) add_executable( diff --git a/apps/console_tools/hesai_pcap_to_laz.cpp b/apps/console_tools/hesai_pcap_to_laz.cpp index 9c84f8e6..e060254b 100644 --- a/apps/console_tools/hesai_pcap_to_laz.cpp +++ b/apps/console_tools/hesai_pcap_to_laz.cpp @@ -1,5 +1,5 @@ // hesai_pcap_to_laz: a recording -> mandeye session directory, read through the recording sources exactly as -// lidar_odometry_step_1 reads it. Meant for Hesai captures (.pcap / .pcap.zst files or a lidar_recorder session +// lidar_odometry_step_1 reads it. Meant for Hesai captures (.pcap / .pcap.zstd files or a lidar_recorder session // directory), but any registered recording kind converts the same way. // // Each chunk of the recording becomes one lidarNNNN.laz (all its points, nothing filtered); every IMU sample goes to the @@ -28,7 +28,7 @@ namespace void print_usage(const char* argv0) { spdlog::error("Usage: {} [ ...] ", argv0); - spdlog::error(" input a recording lidar_odometry_step_1 opens: Hesai .pcap / .pcap.zst files or a"); + spdlog::error(" input a recording lidar_odometry_step_1 opens: Hesai .pcap / .pcap.zstd files or a"); spdlog::error(" lidar_recorder session directory (correction.dat next to them), ROS1 bags, MCAP files"); spdlog::error(" output_session_dir written as mandeye lidarNNNN.laz + imuNNNN.csv chunk pairs, one per"); spdlog::error(" chunk of the recording"); diff --git a/recording_sources/hesai_decoder.cpp b/recording_sources/hesai_decoder.cpp index f8362c1c..fce115a9 100644 --- a/recording_sources/hesai_decoder.cpp +++ b/recording_sources/hesai_decoder.cpp @@ -165,25 +165,42 @@ std::string HesaiDecoder::error() const return {}; } +static bool is_compressed_capture(const std::string& name) +{ + return name.ends_with(".pcap.zstd") || name.ends_with(".pcap.zst"); +} + +bool is_hesai_capture(const fs::path& file) +{ + const std::string name = file.filename().string(); + return name.ends_with(".pcap") || is_compressed_capture(name); +} + std::vector hesai_recorder_chunks(const fs::path& dir) { - std::vector zst, plain; + std::vector compressed, plain; std::error_code ec; for (const auto& e : fs::directory_iterator(dir, ec)) { const std::string n = e.path().filename().string(); if (n.rfind("lidar", 0) != 0) continue; - if (n.ends_with(".pcap.zst")) - zst.push_back(e.path()); + if (is_compressed_capture(n)) + compressed.push_back(e.path()); else if (n.ends_with(".pcap")) plain.push_back(e.path()); } for (const auto& p : plain) - if (std::find(zst.begin(), zst.end(), fs::path(p.string() + ".zst")) == zst.end()) - zst.push_back(p); - std::sort(zst.begin(), zst.end()); - return zst; + { + const auto has_copy = [&](const char* suffix) + { + return std::find(compressed.begin(), compressed.end(), fs::path(p.string() + suffix)) != compressed.end(); + }; + if (!has_copy(".zstd") && !has_copy(".zst")) + compressed.push_back(p); + } + std::sort(compressed.begin(), compressed.end()); + return compressed; } bool decode_hesai_capture( diff --git a/recording_sources/hesai_decoder.h b/recording_sources/hesai_decoder.h index a7ff4969..4bbf585d 100644 --- a/recording_sources/hesai_decoder.h +++ b/recording_sources/hesai_decoder.h @@ -59,8 +59,13 @@ class HesaiDecoder }; /** - * @brief The lidarNNNN.pcap.zst chunks of a lidar_recorder session directory (a .pcap where there is no .zst of the - * same chunk), in order; incomplete .part chunks are skipped. + * @brief True for a Hesai capture file name: .pcap, or zstd-compressed .pcap.zstd (as lidar_recorder writes) / .pcap.zst. + */ +bool is_hesai_capture(const std::filesystem::path& file); + +/** + * @brief The lidarNNNN.pcap.zstd / .pcap.zst chunks of a lidar_recorder session directory (a .pcap where there is no + * compressed copy of the same chunk), in order; incomplete .part chunks are skipped. * @param dir The session directory. * @return The chunk files; empty when the directory holds none. */ diff --git a/recording_sources/hesai_pcap_source.cpp b/recording_sources/hesai_pcap_source.cpp index d4b2fa13..f6518108 100644 --- a/recording_sources/hesai_pcap_source.cpp +++ b/recording_sources/hesai_pcap_source.cpp @@ -12,12 +12,6 @@ namespace fs = std::filesystem; namespace { - bool is_capture(const fs::path& file) - { - const std::string name = file.filename().string(); - return name.ends_with(".pcap") || name.ends_with(".pcap.zst"); - } - //! The captures of paths in recording order: files as given, a folder's lidarNNNN chunks; empty when a path is neither. std::vector captures(const std::vector& paths) { @@ -25,7 +19,7 @@ namespace for (const auto& path : paths) { std::error_code ec; - if (fs::is_regular_file(path, ec) && is_capture(path)) + if (fs::is_regular_file(path, ec) && is_hesai_capture(path)) files.push_back(path); else if (fs::is_directory(path, ec)) { @@ -235,7 +229,7 @@ std::shared_ptr HesaiPcapSource::open(const std::vector HesaiPcapSource::open(const std::vector HesaiPcapSource::fileFilter() { - return { "Hesai capture (*.pcap *.pcap.zst)", "*.pcap *.zst" }; + return { "Hesai capture (*.pcap *.pcap.zstd *.pcap.zst)", "*.pcap *.zstd *.zst" }; } HDMAPPING_REGISTER_RECORDING_SOURCE(HesaiPcapSource) diff --git a/recording_sources/hesai_pcap_source.h b/recording_sources/hesai_pcap_source.h index 231946ed..b67ab0a0 100644 --- a/recording_sources/hesai_pcap_source.h +++ b/recording_sources/hesai_pcap_source.h @@ -12,8 +12,9 @@ // rosbags/McapWriter.h), which a header included by GUI code cannot guarantee. /** - * @brief Hesai pcap captures as a recording: a lidar_recorder session (its lidarNNNN.pcap.zst chunks) or a set of .pcap - * / .pcap.zst files, each file one chunk, decoded with the lidar's angle correction (correction.dat next to the files). + * @brief Hesai pcap captures as a recording: a lidar_recorder session (its lidarNNNN.pcap.zstd chunks) or a set of + * .pcap / .pcap.zstd / .pcap.zst files, each file one chunk, decoded with the lidar's angle correction (correction.dat + * next to the files). * * Every read decodes its file with its own HesaiDecoder, so chunks load from several threads at once. Points keep the * lidar frame (lidar id 0, no calibration) on the lidar clock; the IMU samples carried in the point packets come out in @@ -42,7 +43,8 @@ class HesaiPcapSource final : public RecordingSource /** @return Above the Mandeye LAZ/CSV kind, which accepts any folder. */ static int priority(); /** - * @brief True when every path is a .pcap / .pcap.zst file or a folder holding lidarNNNN.pcap[.zst] chunks. + * @brief True when every path is a .pcap / .pcap.zstd / .pcap.zst file or a folder holding lidarNNNN.pcap[.zstd] + * chunks. * @param paths Files and folders as picked or dropped. * @return Whether this kind reads them. */ From 9ab8c2f58df5a40b26b78a7d930777e4938643c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pe=C5=82ka?= Date: Wed, 2 Dec 2026 19:02:51 +0100 Subject: [PATCH 18/21] step 1: clang-format the IMU offset log line The line moved one indentation level up into load_from_source during the rebase onto main, and clang-format 21 wraps it differently there. Co-Authored-By: Claude Opus 5.5 --- apps/lidar_odometry_step_1/lidar_odometry.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/lidar_odometry_step_1/lidar_odometry.cpp b/apps/lidar_odometry_step_1/lidar_odometry.cpp index 69b7881a..50a17b63 100644 --- a/apps/lidar_odometry_step_1/lidar_odometry.cpp +++ b/apps/lidar_odometry_step_1/lidar_odometry.cpp @@ -173,8 +173,8 @@ static bool load_from_source( return false; } rotate_imu(imu_data, imu_offset); - std::cout << "IMU readings rotated by offset quaternion (w x y z): " << params.imu_offset_qw << " " << params.imu_offset_qx - << " " << params.imu_offset_qy << " " << params.imu_offset_qz << "\n"; + std::cout << "IMU readings rotated by offset quaternion (w x y z): " << params.imu_offset_qw << " " << params.imu_offset_qx << " " + << params.imu_offset_qy << " " << params.imu_offset_qz << "\n"; } if (params.imu_target_rate_hz > 0.0) From 06aee143c4487ed4a68c1afd04d385637468a4f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pe=C5=82ka?= Date: Wed, 2 Dec 2026 19:02:51 +0100 Subject: [PATCH 19/21] clang-format: check rosbags and recording_sources too run_clang_format.py and run_check_clang_format.py (CI) now cover rosbags/ and recording_sources/; scripts/README.md lists them. rosbags/ is reformatted with clang-format 21, whitespace and line wrapping only, no include reordered. recording_sources/ was already formatted. Co-Authored-By: Claude Opus 5.5 --- rosbags/ImuTransform.h | 52 +- rosbags/MandeyeSessionWriter.cpp | 492 ++--- rosbags/MandeyeSessionWriter.h | 120 +- rosbags/McapReader.cpp | 509 ++--- rosbags/McapReader.h | 248 +-- rosbags/McapWriter.cpp | 930 ++++---- rosbags/McapWriter.h | 372 ++-- rosbags/OusterPcapReader.cpp | 1280 +++++------ rosbags/OusterPcapReader.h | 269 +-- rosbags/PcapUdpReader.cpp | 868 ++++---- rosbags/PcapUdpReader.h | 96 +- rosbags/Ros1Bag.cpp | 2395 +++++++++++---------- rosbags/Ros1Bag.h | 460 ++-- rosbags/cdr_serializer.hpp | 1581 +++++++------- rosbags/tests/test_mcap_reader.cpp | 531 ++--- rosbags/tests/test_mcap_writer.cpp | 120 +- rosbags/tests/test_ouster_pcap_reader.cpp | 295 +-- rosbags/tests/test_ros1_bag.cpp | 70 +- scripts/README.md | 2 + scripts/run_check_clang_format.py | 2 + scripts/run_clang_format.py | 4 +- 21 files changed, 5402 insertions(+), 5294 deletions(-) diff --git a/rosbags/ImuTransform.h b/rosbags/ImuTransform.h index dddc4b71..739a62c7 100644 --- a/rosbags/ImuTransform.h +++ b/rosbags/ImuTransform.h @@ -12,31 +12,31 @@ namespace rosbags { -// Standard gravity, the g HDMapping's IMU csv is scaled in. -inline constexpr double kStandardGravity = 9.80665; - -struct ImuTransform -{ - Eigen::Quaterniond imu_to_lidar = Eigen::Quaterniond::Identity(); // IMU frame -> lidar frame - double acc_scale = 1.0; // 1 for a bag already in g, 1/9.80665 for m/s^2 -}; - -inline void applyImuTransform(const ImuTransform& t, McapImuSample& s) -{ - const Eigen::Vector3f gyro = (t.imu_to_lidar * Eigen::Vector3d(s.gyro_x, s.gyro_y, s.gyro_z)).cast(); - const Eigen::Vector3f acc = (t.imu_to_lidar * Eigen::Vector3d(s.acc_x, s.acc_y, s.acc_z)).cast(); - s.gyro_x = gyro.x(); - s.gyro_y = gyro.y(); - s.gyro_z = gyro.z(); - s.acc_x = static_cast(acc.x() * t.acc_scale); - s.acc_y = static_cast(acc.y() * t.acc_scale); - s.acc_z = static_cast(acc.z() * t.acc_scale); -} - -inline void applyImuTransform(const ImuTransform& t, std::vector& samples) -{ - for(auto& s : samples) - applyImuTransform(t, s); -} + // Standard gravity, the g HDMapping's IMU csv is scaled in. + inline constexpr double kStandardGravity = 9.80665; + + struct ImuTransform + { + Eigen::Quaterniond imu_to_lidar = Eigen::Quaterniond::Identity(); // IMU frame -> lidar frame + double acc_scale = 1.0; // 1 for a bag already in g, 1/9.80665 for m/s^2 + }; + + inline void applyImuTransform(const ImuTransform& t, McapImuSample& s) + { + const Eigen::Vector3f gyro = (t.imu_to_lidar * Eigen::Vector3d(s.gyro_x, s.gyro_y, s.gyro_z)).cast(); + const Eigen::Vector3f acc = (t.imu_to_lidar * Eigen::Vector3d(s.acc_x, s.acc_y, s.acc_z)).cast(); + s.gyro_x = gyro.x(); + s.gyro_y = gyro.y(); + s.gyro_z = gyro.z(); + s.acc_x = static_cast(acc.x() * t.acc_scale); + s.acc_y = static_cast(acc.y() * t.acc_scale); + s.acc_z = static_cast(acc.z() * t.acc_scale); + } + + inline void applyImuTransform(const ImuTransform& t, std::vector& samples) + { + for (auto& s : samples) + applyImuTransform(t, s); + } } // namespace rosbags diff --git a/rosbags/MandeyeSessionWriter.cpp b/rosbags/MandeyeSessionWriter.cpp index 2770a107..901354aa 100644 --- a/rosbags/MandeyeSessionWriter.cpp +++ b/rosbags/MandeyeSessionWriter.cpp @@ -13,251 +13,251 @@ namespace rosbags { -namespace -{ - -// Same scale mandeye/HDMapping LAZ files use (see LazWriter::open in -// core/include/Core/export_laz.h): 0.1 mm, i.e. an int32 X/Y/Z spans +-214 km, -// far beyond any sensor-local coordinate. -constexpr double kCoordScale = 0.0001; - -std::string chunkFileName(const char* prefix, int index, const char* ext) -{ - std::array buffer{}; - std::snprintf(buffer.data(), buffer.size(), "%s%04d%s", prefix, index, ext); - return std::string(buffer.data()); -} - -} // namespace - -struct MandeyeSessionWriter::Impl -{ - std::filesystem::path dir; - std::string error; - bool open = false; - bool withRgb = false; - bool withRing = false; - - laszip_POINTER writer = nullptr; - laszip_point* point = nullptr; - int currentChunk = -1; - - uint64_t points = 0; - uint64_t imuSamples = 0; - - bool fail(std::string message) - { - if(error.empty()) - error = std::move(message); - return false; - } -}; - -MandeyeSessionWriter::MandeyeSessionWriter(const std::filesystem::path& dir, bool with_rgb, bool with_ring) - : impl_(std::make_unique()) -{ - impl_->dir = dir; - impl_->withRgb = with_rgb; - impl_->withRing = with_ring; - - std::error_code ec; - std::filesystem::create_directories(dir, ec); - if(ec) - { - impl_->fail("failed to create output directory " + dir.string() + ": " + ec.message()); - return; - } - if(!std::filesystem::is_directory(dir)) - { - impl_->fail(dir.string() + " exists but is not a directory"); - return; - } - - impl_->open = true; -} - -MandeyeSessionWriter::~MandeyeSessionWriter() -{ - if(impl_ && impl_->writer) - endChunk(); -} - -bool MandeyeSessionWriter::isOpen() const -{ - return impl_ && impl_->open; -} - -const std::string& MandeyeSessionWriter::error() const -{ - return impl_->error; -} - -bool MandeyeSessionWriter::beginChunk(int index) -{ - if(!isOpen()) - return false; - if(impl_->writer && !endChunk()) - return false; - - const auto path = impl_->dir / chunkFileName("lidar", index, ".laz"); - - if(laszip_create(&impl_->writer)) - { - impl_->writer = nullptr; - return impl_->fail("failed to create laszip writer"); - } - - laszip_header* header = nullptr; - if(laszip_get_header_pointer(impl_->writer, &header)) - return impl_->fail("failed to get laszip header pointer"); - - header->file_source_ID = 4711; - header->global_encoding = (1 << 0); - header->version_major = 1; - header->version_minor = 2; - // 1: XYZ + intensity + user_data + gps_time; 3: the same + 16-bit RGB. - header->point_data_format = impl_->withRgb ? 3 : 1; - header->point_data_record_length = impl_->withRgb ? 34 : 28; - header->number_of_point_records = 0; - header->number_of_points_by_return[0] = 0; - header->number_of_points_by_return[1] = 0; - header->x_scale_factor = kCoordScale; - header->y_scale_factor = kCoordScale; - header->z_scale_factor = kCoordScale; - // Bag points are sensor-local, so no georeferencing offset is applied. - header->x_offset = 0.0; - header->y_offset = 0.0; - header->z_offset = 0.0; - - if(impl_->withRing) - { - // LAS_ATTRIBUTE_U16 = 2 in laszip's 0-based attribute type codes. The - // attribute adds the extra-bytes VLR; the record grows by its 2 bytes. - if(laszip_add_attribute(impl_->writer, 2, kSessionRingAttribute, "laser ring index", 1.0, 0.0)) - return impl_->fail("failed to add the ring attribute for " + path.string()); - header->point_data_record_length += 2; - } - - if(laszip_open_writer(impl_->writer, path.string().c_str(), /*compress=*/1)) - return impl_->fail("failed to open laszip writer for " + path.string()); - - if(laszip_get_point_pointer(impl_->writer, &impl_->point)) - return impl_->fail("failed to get laszip point pointer"); - - impl_->currentChunk = index; - return true; -} - -bool MandeyeSessionWriter::addPoints(const std::vector& points) -{ - return addPoints(points, {}); -} - -bool MandeyeSessionWriter::addPoints(const std::vector& points, const std::vector& rgb) -{ - if(!isOpen()) - return false; - if(!impl_->writer) - return impl_->fail("addPoints() called with no chunk open"); - if(!rgb.empty() && (!impl_->withRgb || rgb.size() != points.size())) - return impl_->fail( - impl_->withRgb ? "addPoints(): " + std::to_string(rgb.size()) + " colours for " + std::to_string(points.size()) + " points" - : "addPoints(): colours given to a writer opened without with_rgb"); - - for(size_t i = 0; i < points.size(); ++i) - { - const auto& p = points[i]; - if(impl_->withRgb) - { - const Rgb colour = rgb.empty() ? Rgb{} : rgb[i]; - impl_->point->rgb[0] = colour[0]; - impl_->point->rgb[1] = colour[1]; - impl_->point->rgb[2] = colour[2]; - } - impl_->point->intensity = static_cast(std::clamp(p.intensity, 0.0f, 65535.0f)); - impl_->point->return_number = 1; - impl_->point->number_of_returns = 1; - // Unscaled: load_point_cloud() assigns p.timestamp = point->gps_time directly. - impl_->point->gps_time = p.timestamp; - // Single-lidar sessions only, so the lidar id load_point_cloud() reads out of - // user_data is always 0 -- and it must be written, because a session with a - // non-zero id but no matching calibration entry has its points dropped. - impl_->point->user_data = 0; - if(impl_->withRing) - { - if(impl_->point->num_extra_bytes < 2) - return impl_->fail("laszip point has no room for the ring attribute"); - std::memcpy(impl_->point->extra_bytes, &p.ring, 2); - } - - laszip_F64 coordinates[3] = {p.x, p.y, p.z}; - if(laszip_set_coordinates(impl_->writer, coordinates)) - return impl_->fail("failed to set laszip coordinates"); - if(laszip_write_point(impl_->writer)) - return impl_->fail("failed to write laszip point"); - if(laszip_update_inventory(impl_->writer)) - return impl_->fail("failed to update laszip inventory"); - - ++impl_->points; - } - return true; -} - -bool MandeyeSessionWriter::endChunk() -{ - if(!impl_->writer) - return true; - - bool ok = true; - if(laszip_close_writer(impl_->writer)) - ok = impl_->fail("failed to close laszip writer for chunk " + std::to_string(impl_->currentChunk)); - if(laszip_destroy(impl_->writer)) - ok = impl_->fail("failed to destroy laszip writer for chunk " + std::to_string(impl_->currentChunk)); - - impl_->writer = nullptr; - impl_->point = nullptr; - impl_->currentChunk = -1; - return ok; -} - -bool MandeyeSessionWriter::writeImuChunk(int index, const std::vector& samples) -{ - if(!isOpen()) - return false; - - const auto path = impl_->dir / chunkFileName("imu", index, ".csv"); - std::ofstream out(path); - if(!out.is_open()) - return impl_->fail("failed to open " + path.string()); - - // Column set and order per concatenate_multi_livox.cpp; load_imu() looks the - // columns up by name, so the order is only a convention. - out << "timestamp timestampUnix accX accY accZ gyroX gyroY gyroZ\n"; - out << std::setprecision(std::numeric_limits::max_digits10); - - for(const auto& s : samples) - { - // timestampUnix is 0: McapImuSample has no slot for load_imu()'s second - // (wall-clock) timestamp, so the exporter never carried it into the bag. - out << static_cast(s.timestamp * 1e9) << " " << 0 << " " << s.acc_x << " " << s.acc_y << " " << s.acc_z << " " << s.gyro_x - << " " << s.gyro_y << " " << s.gyro_z << "\n"; - ++impl_->imuSamples; - } - - out.flush(); - if(!out) - return impl_->fail("failed to write " + path.string()); - return true; -} - -uint64_t MandeyeSessionWriter::pointsWritten() const -{ - return impl_->points; -} - -uint64_t MandeyeSessionWriter::imuSamplesWritten() const -{ - return impl_->imuSamples; -} + namespace + { + + // Same scale mandeye/HDMapping LAZ files use (see LazWriter::open in + // core/include/Core/export_laz.h): 0.1 mm, i.e. an int32 X/Y/Z spans +-214 km, + // far beyond any sensor-local coordinate. + constexpr double kCoordScale = 0.0001; + + std::string chunkFileName(const char* prefix, int index, const char* ext) + { + std::array buffer{}; + std::snprintf(buffer.data(), buffer.size(), "%s%04d%s", prefix, index, ext); + return std::string(buffer.data()); + } + + } // namespace + + struct MandeyeSessionWriter::Impl + { + std::filesystem::path dir; + std::string error; + bool open = false; + bool withRgb = false; + bool withRing = false; + + laszip_POINTER writer = nullptr; + laszip_point* point = nullptr; + int currentChunk = -1; + + uint64_t points = 0; + uint64_t imuSamples = 0; + + bool fail(std::string message) + { + if (error.empty()) + error = std::move(message); + return false; + } + }; + + MandeyeSessionWriter::MandeyeSessionWriter(const std::filesystem::path& dir, bool with_rgb, bool with_ring) + : impl_(std::make_unique()) + { + impl_->dir = dir; + impl_->withRgb = with_rgb; + impl_->withRing = with_ring; + + std::error_code ec; + std::filesystem::create_directories(dir, ec); + if (ec) + { + impl_->fail("failed to create output directory " + dir.string() + ": " + ec.message()); + return; + } + if (!std::filesystem::is_directory(dir)) + { + impl_->fail(dir.string() + " exists but is not a directory"); + return; + } + + impl_->open = true; + } + + MandeyeSessionWriter::~MandeyeSessionWriter() + { + if (impl_ && impl_->writer) + endChunk(); + } + + bool MandeyeSessionWriter::isOpen() const + { + return impl_ && impl_->open; + } + + const std::string& MandeyeSessionWriter::error() const + { + return impl_->error; + } + + bool MandeyeSessionWriter::beginChunk(int index) + { + if (!isOpen()) + return false; + if (impl_->writer && !endChunk()) + return false; + + const auto path = impl_->dir / chunkFileName("lidar", index, ".laz"); + + if (laszip_create(&impl_->writer)) + { + impl_->writer = nullptr; + return impl_->fail("failed to create laszip writer"); + } + + laszip_header* header = nullptr; + if (laszip_get_header_pointer(impl_->writer, &header)) + return impl_->fail("failed to get laszip header pointer"); + + header->file_source_ID = 4711; + header->global_encoding = (1 << 0); + header->version_major = 1; + header->version_minor = 2; + // 1: XYZ + intensity + user_data + gps_time; 3: the same + 16-bit RGB. + header->point_data_format = impl_->withRgb ? 3 : 1; + header->point_data_record_length = impl_->withRgb ? 34 : 28; + header->number_of_point_records = 0; + header->number_of_points_by_return[0] = 0; + header->number_of_points_by_return[1] = 0; + header->x_scale_factor = kCoordScale; + header->y_scale_factor = kCoordScale; + header->z_scale_factor = kCoordScale; + // Bag points are sensor-local, so no georeferencing offset is applied. + header->x_offset = 0.0; + header->y_offset = 0.0; + header->z_offset = 0.0; + + if (impl_->withRing) + { + // LAS_ATTRIBUTE_U16 = 2 in laszip's 0-based attribute type codes. The + // attribute adds the extra-bytes VLR; the record grows by its 2 bytes. + if (laszip_add_attribute(impl_->writer, 2, kSessionRingAttribute, "laser ring index", 1.0, 0.0)) + return impl_->fail("failed to add the ring attribute for " + path.string()); + header->point_data_record_length += 2; + } + + if (laszip_open_writer(impl_->writer, path.string().c_str(), /*compress=*/1)) + return impl_->fail("failed to open laszip writer for " + path.string()); + + if (laszip_get_point_pointer(impl_->writer, &impl_->point)) + return impl_->fail("failed to get laszip point pointer"); + + impl_->currentChunk = index; + return true; + } + + bool MandeyeSessionWriter::addPoints(const std::vector& points) + { + return addPoints(points, {}); + } + + bool MandeyeSessionWriter::addPoints(const std::vector& points, const std::vector& rgb) + { + if (!isOpen()) + return false; + if (!impl_->writer) + return impl_->fail("addPoints() called with no chunk open"); + if (!rgb.empty() && (!impl_->withRgb || rgb.size() != points.size())) + return impl_->fail( + impl_->withRgb ? "addPoints(): " + std::to_string(rgb.size()) + " colours for " + std::to_string(points.size()) + " points" + : "addPoints(): colours given to a writer opened without with_rgb"); + + for (size_t i = 0; i < points.size(); ++i) + { + const auto& p = points[i]; + if (impl_->withRgb) + { + const Rgb colour = rgb.empty() ? Rgb{} : rgb[i]; + impl_->point->rgb[0] = colour[0]; + impl_->point->rgb[1] = colour[1]; + impl_->point->rgb[2] = colour[2]; + } + impl_->point->intensity = static_cast(std::clamp(p.intensity, 0.0f, 65535.0f)); + impl_->point->return_number = 1; + impl_->point->number_of_returns = 1; + // Unscaled: load_point_cloud() assigns p.timestamp = point->gps_time directly. + impl_->point->gps_time = p.timestamp; + // Single-lidar sessions only, so the lidar id load_point_cloud() reads out of + // user_data is always 0 -- and it must be written, because a session with a + // non-zero id but no matching calibration entry has its points dropped. + impl_->point->user_data = 0; + if (impl_->withRing) + { + if (impl_->point->num_extra_bytes < 2) + return impl_->fail("laszip point has no room for the ring attribute"); + std::memcpy(impl_->point->extra_bytes, &p.ring, 2); + } + + laszip_F64 coordinates[3] = { p.x, p.y, p.z }; + if (laszip_set_coordinates(impl_->writer, coordinates)) + return impl_->fail("failed to set laszip coordinates"); + if (laszip_write_point(impl_->writer)) + return impl_->fail("failed to write laszip point"); + if (laszip_update_inventory(impl_->writer)) + return impl_->fail("failed to update laszip inventory"); + + ++impl_->points; + } + return true; + } + + bool MandeyeSessionWriter::endChunk() + { + if (!impl_->writer) + return true; + + bool ok = true; + if (laszip_close_writer(impl_->writer)) + ok = impl_->fail("failed to close laszip writer for chunk " + std::to_string(impl_->currentChunk)); + if (laszip_destroy(impl_->writer)) + ok = impl_->fail("failed to destroy laszip writer for chunk " + std::to_string(impl_->currentChunk)); + + impl_->writer = nullptr; + impl_->point = nullptr; + impl_->currentChunk = -1; + return ok; + } + + bool MandeyeSessionWriter::writeImuChunk(int index, const std::vector& samples) + { + if (!isOpen()) + return false; + + const auto path = impl_->dir / chunkFileName("imu", index, ".csv"); + std::ofstream out(path); + if (!out.is_open()) + return impl_->fail("failed to open " + path.string()); + + // Column set and order per concatenate_multi_livox.cpp; load_imu() looks the + // columns up by name, so the order is only a convention. + out << "timestamp timestampUnix accX accY accZ gyroX gyroY gyroZ\n"; + out << std::setprecision(std::numeric_limits::max_digits10); + + for (const auto& s : samples) + { + // timestampUnix is 0: McapImuSample has no slot for load_imu()'s second + // (wall-clock) timestamp, so the exporter never carried it into the bag. + out << static_cast(s.timestamp * 1e9) << " " << 0 << " " << s.acc_x << " " << s.acc_y << " " << s.acc_z << " " + << s.gyro_x << " " << s.gyro_y << " " << s.gyro_z << "\n"; + ++impl_->imuSamples; + } + + out.flush(); + if (!out) + return impl_->fail("failed to write " + path.string()); + return true; + } + + uint64_t MandeyeSessionWriter::pointsWritten() const + { + return impl_->points; + } + + uint64_t MandeyeSessionWriter::imuSamplesWritten() const + { + return impl_->imuSamples; + } } // namespace rosbags diff --git a/rosbags/MandeyeSessionWriter.h b/rosbags/MandeyeSessionWriter.h index 03dc9cda..bb18f052 100644 --- a/rosbags/MandeyeSessionWriter.h +++ b/rosbags/MandeyeSessionWriter.h @@ -10,73 +10,73 @@ namespace rosbags { -// Name of the LAS extra-bytes attribute that carries each point's laser ring. -inline constexpr const char* kSessionRingAttribute = "ring"; + // Name of the LAS extra-bytes attribute that carries each point's laser ring. + inline constexpr const char* kSessionRingAttribute = "ring"; -// Writes a single-lidar mandeye-style recording directory: lidarNNNN.laz / -// imuNNNN.csv chunk pairs, indexed by the same trailing-4-digit convention -// load_data() in apps/lidar_odometry_step_1 matches them by. -// -// The LAZ side deliberately does NOT go through export_laz.h's LazWriter, which -// stores gps_time as `timestamp * 1e9` -- whereas load_point_cloud() -// (lidar_odometry_utils.cpp) reads timestamps straight out of gps_time. Reusing -// it would produce a session whose timestamps are off by a factor of 1e9. -// -// Point record layout written here, matching what load_point_cloud() reads back: -// gps_time = McapPoint::timestamp (absolute seconds, unscaled) -// user_data = 0 (lidar id; single sensor per session) -// intensity = McapPoint::intensity (clamped to uint16) -// red/green/blue (with_rgb only) LAS 16-bit colour, point format 3 -// instead of 1; load_point_cloud() reads -// neither the colour nor the format -// ring (with_ring only) McapPoint::ring as a uint16 LAS "extra -// bytes" attribute named "ring" (see -// kSessionRingAttribute). user_data stays the -// lidar id and point_source_ID stays free; -// load_point_cloud() returns it only when -// asked for rings -// -// The IMU csv uses the modern named-column format load_imu() prefers, in the -// column order concatenate_multi_livox already writes, with both timestamps in -// integer nanoseconds (load_imu divides by 1e9). -class MandeyeSessionWriter -{ -public: - // One point's LAS colour (red, green, blue, full 16-bit scale). - using Rgb = std::array; + // Writes a single-lidar mandeye-style recording directory: lidarNNNN.laz / + // imuNNNN.csv chunk pairs, indexed by the same trailing-4-digit convention + // load_data() in apps/lidar_odometry_step_1 matches them by. + // + // The LAZ side deliberately does NOT go through export_laz.h's LazWriter, which + // stores gps_time as `timestamp * 1e9` -- whereas load_point_cloud() + // (lidar_odometry_utils.cpp) reads timestamps straight out of gps_time. Reusing + // it would produce a session whose timestamps are off by a factor of 1e9. + // + // Point record layout written here, matching what load_point_cloud() reads back: + // gps_time = McapPoint::timestamp (absolute seconds, unscaled) + // user_data = 0 (lidar id; single sensor per session) + // intensity = McapPoint::intensity (clamped to uint16) + // red/green/blue (with_rgb only) LAS 16-bit colour, point format 3 + // instead of 1; load_point_cloud() reads + // neither the colour nor the format + // ring (with_ring only) McapPoint::ring as a uint16 LAS "extra + // bytes" attribute named "ring" (see + // kSessionRingAttribute). user_data stays the + // lidar id and point_source_ID stays free; + // load_point_cloud() returns it only when + // asked for rings + // + // The IMU csv uses the modern named-column format load_imu() prefers, in the + // column order concatenate_multi_livox already writes, with both timestamps in + // integer nanoseconds (load_imu divides by 1e9). + class MandeyeSessionWriter + { + public: + // One point's LAS colour (red, green, blue, full 16-bit scale). + using Rgb = std::array; - // Creates `dir` if it does not exist. `with_rgb` writes every chunk as LAS - // point format 3 (format 1 + RGB) instead of format 1; `with_ring` adds the - // "ring" extra-bytes attribute. - explicit MandeyeSessionWriter(const std::filesystem::path& dir, bool with_rgb = false, bool with_ring = false); - ~MandeyeSessionWriter(); + // Creates `dir` if it does not exist. `with_rgb` writes every chunk as LAS + // point format 3 (format 1 + RGB) instead of format 1; `with_ring` adds the + // "ring" extra-bytes attribute. + explicit MandeyeSessionWriter(const std::filesystem::path& dir, bool with_rgb = false, bool with_ring = false); + ~MandeyeSessionWriter(); - // Non-copyable - MandeyeSessionWriter(const MandeyeSessionWriter&) = delete; - MandeyeSessionWriter& operator=(const MandeyeSessionWriter&) = delete; + // Non-copyable + MandeyeSessionWriter(const MandeyeSessionWriter&) = delete; + MandeyeSessionWriter& operator=(const MandeyeSessionWriter&) = delete; - bool isOpen() const; - const std::string& error() const; + bool isOpen() const; + const std::string& error() const; - // Opens lidar.laz. Any chunk still open is closed first. - bool beginChunk(int index); - // Without colours, a with_rgb writer stores black. - bool addPoints(const std::vector& points); - // `rgb` is parallel to `points`; only valid on a with_rgb writer. - bool addPoints(const std::vector& points, const std::vector& rgb); - bool endChunk(); + // Opens lidar.laz. Any chunk still open is closed first. + bool beginChunk(int index); + // Without colours, a with_rgb writer stores black. + bool addPoints(const std::vector& points); + // `rgb` is parallel to `points`; only valid on a with_rgb writer. + bool addPoints(const std::vector& points, const std::vector& rgb); + bool endChunk(); - // Writes imu.csv in one shot. Samples are written in the order - // given; an empty vector still produces a header-only file, because - // load_data() reports a missing csv for every laz it cannot pair. - bool writeImuChunk(int index, const std::vector& samples); + // Writes imu.csv in one shot. Samples are written in the order + // given; an empty vector still produces a header-only file, because + // load_data() reports a missing csv for every laz it cannot pair. + bool writeImuChunk(int index, const std::vector& samples); - uint64_t pointsWritten() const; - uint64_t imuSamplesWritten() const; + uint64_t pointsWritten() const; + uint64_t imuSamplesWritten() const; -private: - struct Impl; - std::unique_ptr impl_; -}; + private: + struct Impl; + std::unique_ptr impl_; + }; } // namespace rosbags diff --git a/rosbags/McapReader.cpp b/rosbags/McapReader.cpp index bdb96d2f..2c718f2c 100644 --- a/rosbags/McapReader.cpp +++ b/rosbags/McapReader.cpp @@ -15,276 +15,289 @@ namespace rosbags { -namespace -{ + namespace + { -// ros2 schema names are "sensor_msgs/msg/PointCloud2"; ros1-style bags spell the -// same type "sensor_msgs/PointCloud2". Comparing only the trailing type name -// accepts both. -std::string_view schemaTypeName(std::string_view schema_name) -{ - const auto slash = schema_name.rfind('/'); - return slash == std::string_view::npos ? schema_name : schema_name.substr(slash + 1); -} + // ros2 schema names are "sensor_msgs/msg/PointCloud2"; ros1-style bags spell the + // same type "sensor_msgs/PointCloud2". Comparing only the trailing type name + // accepts both. + std::string_view schemaTypeName(std::string_view schema_name) + { + const auto slash = schema_name.rfind('/'); + return slash == std::string_view::npos ? schema_name : schema_name.substr(slash + 1); + } -} // namespace + } // namespace + + struct McapFileReader::Impl + { + mcap::McapReader reader; + McapReaderOptions options; + ResolvedTopics resolved; + std::vector channels; + std::string error; + std::string lidarLayoutWarning; + bool open = false; + bool timeOrdered = false; + + // Resolves one stream to a topic name. `requested` non-empty means "use this + // topic, and fail if it isn't in the file"; empty means auto-detect the + // single channel carrying `type_name`. `required_unique` streams error out on + // ambiguity, optional ones give up quietly. + bool resolveTopic(const std::string& requested, std::string_view type_name, bool required_unique, std::string& out) + { + if (!requested.empty()) + { + const auto it = std::find_if( + channels.begin(), + channels.end(), + [&](const ChannelInfo& c) + { + return c.topic == requested; + }); + if (it == channels.end()) + { + error = "topic '" + requested + "' is not present in the file"; + return false; + } + if (it->message_encoding != "cdr") + { + error = "topic '" + requested + "' uses message encoding '" + it->message_encoding + "', expected 'cdr'"; + return false; + } + out = requested; + return true; + } -struct McapFileReader::Impl -{ - mcap::McapReader reader; - McapReaderOptions options; - ResolvedTopics resolved; - std::vector channels; - std::string error; - std::string lidarLayoutWarning; - bool open = false; - bool timeOrdered = false; - - // Resolves one stream to a topic name. `requested` non-empty means "use this - // topic, and fail if it isn't in the file"; empty means auto-detect the - // single channel carrying `type_name`. `required_unique` streams error out on - // ambiguity, optional ones give up quietly. - bool resolveTopic(const std::string& requested, std::string_view type_name, bool required_unique, std::string& out) - { - if(!requested.empty()) - { - const auto it = std::find_if(channels.begin(), channels.end(), [&](const ChannelInfo& c) { return c.topic == requested; }); - if(it == channels.end()) - { - error = "topic '" + requested + "' is not present in the file"; - return false; - } - if(it->message_encoding != "cdr") - { - error = "topic '" + requested + "' uses message encoding '" + it->message_encoding + "', expected 'cdr'"; - return false; - } - out = requested; - return true; - } - - std::vector candidates; - for(const auto& c : channels) - { - if(schemaTypeName(c.schema_name) == type_name && c.message_encoding == "cdr") - candidates.push_back(&c); - } - - if(candidates.empty()) - return true; // absent stream, `out` stays empty - if(candidates.size() > 1) - { - if(!required_unique) - return true; - error = "found " + std::to_string(candidates.size()) + " " + std::string(type_name) + " topics ("; - for(size_t i = 0; i < candidates.size(); ++i) - error += (i ? ", " : "") + candidates[i]->topic; - error += ") - pick one explicitly"; - return false; - } - out = candidates.front()->topic; - return true; - } -}; - -McapFileReader::McapFileReader(const std::filesystem::path& path, const McapReaderOptions& options) - : impl_(std::make_unique()) -{ - impl_->options = options; - - auto status = impl_->reader.open(path.string()); - if(!status.ok()) - { - impl_->error = "failed to open " + path.string() + ": " + status.message; - return; - } - - // AllowFallbackScan so files written without a summary section (or truncated - // mid-recording) still enumerate their channels. - status = impl_->reader.readSummary(mcap::ReadSummaryMethod::AllowFallbackScan); - if(!status.ok()) - { - impl_->error = "failed to read summary of " + path.string() + ": " + status.message; - return; - } - - const auto& schemas = impl_->reader.schemas(); - const auto& statistics = impl_->reader.statistics(); - for(const auto& [id, channel] : impl_->reader.channels()) - { - ChannelInfo info; - info.topic = channel->topic; - info.message_encoding = channel->messageEncoding; - if(const auto it = schemas.find(channel->schemaId); it != schemas.end()) - info.schema_name = it->second->name; - if(statistics) - { - if(const auto it = statistics->channelMessageCounts.find(id); it != statistics->channelMessageCounts.end()) - info.message_count = it->second; - } - impl_->channels.push_back(std::move(info)); - } - std::sort(impl_->channels.begin(), impl_->channels.end(), [](const ChannelInfo& a, const ChannelInfo& b) { return a.topic < b.topic; }); - - if(!impl_->resolveTopic(options.lidar_topic, "PointCloud2", /*required_unique=*/true, impl_->resolved.lidar) || - !impl_->resolveTopic(options.lidar_topic, "CustomMsg", /*required_unique=*/true, impl_->resolved.lidar) || - !impl_->resolveTopic(options.imu_topic, "Imu", /*required_unique=*/true, impl_->resolved.imu) || - !impl_->resolveTopic(options.sn_topic, "String", /*required_unique=*/false, impl_->resolved.sn)) - return; - - // resolveTopic() only records *which topic* the lidar stream is on; it + std::vector candidates; + for (const auto& c : channels) + { + if (schemaTypeName(c.schema_name) == type_name && c.message_encoding == "cdr") + candidates.push_back(&c); + } + + if (candidates.empty()) + return true; // absent stream, `out` stays empty + if (candidates.size() > 1) + { + if (!required_unique) + return true; + error = "found " + std::to_string(candidates.size()) + " " + std::string(type_name) + " topics ("; + for (size_t i = 0; i < candidates.size(); ++i) + error += (i ? ", " : "") + candidates[i]->topic; + error += ") - pick one explicitly"; + return false; + } + out = candidates.front()->topic; + return true; + } + }; + + McapFileReader::McapFileReader(const std::filesystem::path& path, const McapReaderOptions& options) + : impl_(std::make_unique()) + { + impl_->options = options; + + auto status = impl_->reader.open(path.string()); + if (!status.ok()) + { + impl_->error = "failed to open " + path.string() + ": " + status.message; + return; + } + + // AllowFallbackScan so files written without a summary section (or truncated + // mid-recording) still enumerate their channels. + status = impl_->reader.readSummary(mcap::ReadSummaryMethod::AllowFallbackScan); + if (!status.ok()) + { + impl_->error = "failed to read summary of " + path.string() + ": " + status.message; + return; + } + + const auto& schemas = impl_->reader.schemas(); + const auto& statistics = impl_->reader.statistics(); + for (const auto& [id, channel] : impl_->reader.channels()) + { + ChannelInfo info; + info.topic = channel->topic; + info.message_encoding = channel->messageEncoding; + if (const auto it = schemas.find(channel->schemaId); it != schemas.end()) + info.schema_name = it->second->name; + if (statistics) + { + if (const auto it = statistics->channelMessageCounts.find(id); it != statistics->channelMessageCounts.end()) + info.message_count = it->second; + } + impl_->channels.push_back(std::move(info)); + } + std::sort( + impl_->channels.begin(), + impl_->channels.end(), + [](const ChannelInfo& a, const ChannelInfo& b) + { + return a.topic < b.topic; + }); + + if (!impl_->resolveTopic(options.lidar_topic, "PointCloud2", /*required_unique=*/true, impl_->resolved.lidar) || + !impl_->resolveTopic(options.lidar_topic, "CustomMsg", /*required_unique=*/true, impl_->resolved.lidar) || + !impl_->resolveTopic(options.imu_topic, "Imu", /*required_unique=*/true, impl_->resolved.imu) || + !impl_->resolveTopic(options.sn_topic, "String", /*required_unique=*/false, impl_->resolved.sn)) + return; + + // resolveTopic() only records *which topic* the lidar stream is on; it // doesn't tell read() *which schema* that topic carries, and the two // calls above happily aim at the same output field. Look the resolved // topic back up in `channels` and record its schema, so read() can pick // the matching decoder instead of guessing. - if (!impl_->resolved.lidar.empty()) + if (!impl_->resolved.lidar.empty()) { const auto it = std::find_if( - impl_->channels.begin(), - impl_->channels.end(), + impl_->channels.begin(), + impl_->channels.end(), [&](const ChannelInfo& c) { return c.topic == impl_->resolved.lidar; }); - if (it != impl_->channels.end()) + if (it != impl_->channels.end()) { const auto type = schemaTypeName(it->schema_name); - if (type == "PointCloud2") - impl_->resolved.lidar_schema = LidarSchema::PointCloud2; + if (type == "PointCloud2") + impl_->resolved.lidar_schema = LidarSchema::PointCloud2; else if (type == "CustomMsg") - impl_->resolved.lidar_schema = LidarSchema::LivoxCustomMsg; + impl_->resolved.lidar_schema = LidarSchema::LivoxCustomMsg; } - } - // Ascending-log-time iteration needs per-chunk message indexes; this mirrors - // the precondition mcap's own IndexedMessageReader checks, so testing it here - // lets us fall back to file order instead of failing mid-iteration. - const auto& chunkIndexes = impl_->reader.chunkIndexes(); - impl_->timeOrdered = !chunkIndexes.empty() && chunkIndexes.front().messageIndexLength != 0; - - impl_->open = true; -} - -McapFileReader::~McapFileReader() -{ - if(impl_) - impl_->reader.close(); -} - -bool McapFileReader::isOpen() const -{ - return impl_ && impl_->open; -} - -const std::string& McapFileReader::error() const -{ - return impl_->error; -} - -const ResolvedTopics& McapFileReader::topics() const -{ - return impl_->resolved; -} + // Ascending-log-time iteration needs per-chunk message indexes; this mirrors + // the precondition mcap's own IndexedMessageReader checks, so testing it here + // lets us fall back to file order instead of failing mid-iteration. + const auto& chunkIndexes = impl_->reader.chunkIndexes(); + impl_->timeOrdered = !chunkIndexes.empty() && chunkIndexes.front().messageIndexLength != 0; + + impl_->open = true; + } + + McapFileReader::~McapFileReader() + { + if (impl_) + impl_->reader.close(); + } + + bool McapFileReader::isOpen() const + { + return impl_ && impl_->open; + } + + const std::string& McapFileReader::error() const + { + return impl_->error; + } + + const ResolvedTopics& McapFileReader::topics() const + { + return impl_->resolved; + } + + const std::vector& McapFileReader::channels() const + { + return impl_->channels; + } + + bool McapFileReader::timeOrdered() const + { + return impl_ && impl_->timeOrdered; + } + + const std::string& McapFileReader::lidarLayoutWarning() const + { + return impl_->lidarLayoutWarning; + } + + std::optional McapFileReader::logTimeSpan() const + { + if (!impl_) + return std::nullopt; + if (const auto& statistics = impl_->reader.statistics(); statistics && statistics->messageCount > 0) + return LogTimeRange{ statistics->messageStartTime, statistics->messageEndTime + 1 }; + const auto& chunkIndexes = impl_->reader.chunkIndexes(); + if (chunkIndexes.empty()) + return std::nullopt; + LogTimeRange span{ std::numeric_limits::max(), 0 }; + for (const auto& chunk : chunkIndexes) + { + span.start_ns = std::min(span.start_ns, chunk.messageStartTime); + span.end_ns = std::max(span.end_ns, chunk.messageEndTime + 1); + } + return span; + } + + bool McapFileReader::read(const Callbacks& callbacks, const LogTimeRange& range) + { + if (!isOpen()) + return false; + + const std::string& lidarTopic = impl_->resolved.lidar; + const std::string& imuTopic = impl_->resolved.imu; + const std::string& snTopic = impl_->resolved.sn; + + const bool wantLidar = callbacks.onPointCloud && !lidarTopic.empty(); + const bool wantImu = callbacks.onImu && !imuTopic.empty(); + const bool wantSn = callbacks.onSn && !snTopic.empty(); + if (!wantLidar && !wantImu && !wantSn) + return true; + + mcap::ReadMessageOptions read_options; + read_options.startTime = range.start_ns; + read_options.endTime = range.end_ns; + read_options.readOrder = + impl_->timeOrdered ? mcap::ReadMessageOptions::ReadOrder::LogTimeOrder : mcap::ReadMessageOptions::ReadOrder::FileOrder; + read_options.topicFilter = [&](std::string_view topic) + { + return (wantLidar && topic == lidarTopic) || (wantImu && topic == imuTopic) || (wantSn && topic == snTopic); + }; -const std::vector& McapFileReader::channels() const -{ - return impl_->channels; -} + bool failed = false; + const auto onProblem = [&](const mcap::Status& status) + { + if (impl_->error.empty()) + impl_->error = status.message; + failed = true; + }; -bool McapFileReader::timeOrdered() const -{ - return impl_ && impl_->timeOrdered; -} + auto messages = impl_->reader.readMessages(onProblem, read_options); + for (const auto& view : messages) + { + if (callbacks.onProgress) + callbacks.onProgress(view.message.logTime); + const auto* data = reinterpret_cast(view.message.data); + const size_t size = view.message.dataSize; + const std::string& topic = view.channel->topic; -const std::string& McapFileReader::lidarLayoutWarning() const -{ - return impl_->lidarLayoutWarning; -} + if (wantLidar && topic == lidarTopic) + { + // Only the first complaint is kept: a layout problem is a property of + // the file, so it would otherwise repeat once per message. + std::vector points; + if (impl_->resolved.lidar_schema == LidarSchema::LivoxCustomMsg) + points = decodeLivoxCustomMsg(data, size, 0.0, &impl_->lidarLayoutWarning); + else + points = decodePc2(data, size, impl_->options.lidar_preset, &impl_->lidarLayoutWarning); + + if (!points.empty()) + callbacks.onPointCloud(view.message.logTime, std::move(points)); + } + else if (wantImu && topic == imuTopic) + { + if (const auto sample = decodeImu(data, size)) + callbacks.onImu(*sample); + } + else if (wantSn && topic == snTopic) + { + callbacks.onSn(view.message.logTime, decodeSn(data, size)); + } + } -std::optional McapFileReader::logTimeSpan() const -{ - if(!impl_) - return std::nullopt; - if(const auto& statistics = impl_->reader.statistics(); statistics && statistics->messageCount > 0) - return LogTimeRange{statistics->messageStartTime, statistics->messageEndTime + 1}; - const auto& chunkIndexes = impl_->reader.chunkIndexes(); - if(chunkIndexes.empty()) - return std::nullopt; - LogTimeRange span{std::numeric_limits::max(), 0}; - for(const auto& chunk : chunkIndexes) - { - span.start_ns = std::min(span.start_ns, chunk.messageStartTime); - span.end_ns = std::max(span.end_ns, chunk.messageEndTime + 1); - } - return span; -} - -bool McapFileReader::read(const Callbacks& callbacks, const LogTimeRange& range) -{ - if(!isOpen()) - return false; - - const std::string& lidarTopic = impl_->resolved.lidar; - const std::string& imuTopic = impl_->resolved.imu; - const std::string& snTopic = impl_->resolved.sn; - - const bool wantLidar = callbacks.onPointCloud && !lidarTopic.empty(); - const bool wantImu = callbacks.onImu && !imuTopic.empty(); - const bool wantSn = callbacks.onSn && !snTopic.empty(); - if(!wantLidar && !wantImu && !wantSn) - return true; - - mcap::ReadMessageOptions read_options; - read_options.startTime = range.start_ns; - read_options.endTime = range.end_ns; - read_options.readOrder = impl_->timeOrdered ? mcap::ReadMessageOptions::ReadOrder::LogTimeOrder - : mcap::ReadMessageOptions::ReadOrder::FileOrder; - read_options.topicFilter = [&](std::string_view topic) { - return (wantLidar && topic == lidarTopic) || (wantImu && topic == imuTopic) || (wantSn && topic == snTopic); - }; - - bool failed = false; - const auto onProblem = [&](const mcap::Status& status) { - if(impl_->error.empty()) - impl_->error = status.message; - failed = true; - }; - - auto messages = impl_->reader.readMessages(onProblem, read_options); - for(const auto& view : messages) - { - if(callbacks.onProgress) - callbacks.onProgress(view.message.logTime); - const auto* data = reinterpret_cast(view.message.data); - const size_t size = view.message.dataSize; - const std::string& topic = view.channel->topic; - - if(wantLidar && topic == lidarTopic) - { - // Only the first complaint is kept: a layout problem is a property of - // the file, so it would otherwise repeat once per message. - std::vector points; - if (impl_->resolved.lidar_schema == LidarSchema::LivoxCustomMsg) - points = decodeLivoxCustomMsg(data, size, 0.0, &impl_->lidarLayoutWarning); - else - points = decodePc2(data, size, impl_->options.lidar_preset, &impl_->lidarLayoutWarning); - - if (!points.empty()) - callbacks.onPointCloud(view.message.logTime, std::move(points)); - } - else if(wantImu && topic == imuTopic) - { - if(const auto sample = decodeImu(data, size)) - callbacks.onImu(*sample); - } - else if(wantSn && topic == snTopic) - { - callbacks.onSn(view.message.logTime, decodeSn(data, size)); - } - } - - return !failed; -} + return !failed; + } } // namespace rosbags diff --git a/rosbags/McapReader.h b/rosbags/McapReader.h index 7b658703..68581eac 100644 --- a/rosbags/McapReader.h +++ b/rosbags/McapReader.h @@ -13,129 +13,129 @@ namespace rosbags { -// Topic selection. An empty name means "auto-detect": the reader looks for -// exactly one channel whose schema is the matching ros2 message type. More than -// one candidate is an error for the lidar/IMU streams (picking one silently -// would quietly export the wrong sensor) but not for the serial-number stream, -// which is cosmetic and simply stays unresolved. -struct McapReaderOptions -{ - std::string lidar_topic; // sensor_msgs/msg/PointCloud2 - std::string imu_topic; // sensor_msgs/msg/Imu - std::string sn_topic; // std_msgs/msg/String - - // How PointCloud2 point records are unpacked. Auto reads the layout from each - // message's own `fields` array and is right for any bag that fills it in - // honestly; a preset forces a known driver layout for bags that do not. - Pc2Preset lidar_preset = Pc2Preset::Auto; -}; - -// Which ros2 message type the resolved lidar topic actually carries. Needed -// because read() must call a different CDR decoder for each: decodePc2() and -// decodeLivoxCustomMsg() are not interchangeable. -enum class LidarSchema -{ - Unknown, - PointCloud2, - LivoxCustomMsg, -}; - -// The topics actually in use after auto-detection; empty means "not present". -struct ResolvedTopics -{ - std::string lidar; - std::string imu; - std::string sn; - LidarSchema lidar_schema = LidarSchema::Unknown; -}; - -// Half-open range [start_ns, end_ns) of message log times: the MCAP log time, or -// the record time of a ROS1 bag. The default covers every message. -struct LogTimeRange -{ - uint64_t start_ns = 0; - uint64_t end_ns = std::numeric_limits::max(); -}; - -// One channel as found in the file, for --list output and diagnostics. -struct ChannelInfo -{ - std::string topic; - std::string schema_name; - std::string message_encoding; - uint64_t message_count = 0; // 0 if the file carries no statistics record -}; - -// Reads ros2msg/CDR-encoded MCAP files back into the McapPoint/McapImuSample -// structs McapFileWriter writes, i.e. the inverse of McapFileWriter. -// -// Decoding is delegated to decodePc2()/decodeImu()/decodeSn() in -// cdr_serializer.hpp, which parse the PointCloud2 `fields` array at runtime and -// therefore handle every PointCloudLayout the writer can emit. -// -// Messages are delivered through callbacks rather than returned in bulk: a real -// recording is far too large to hold in memory, so callers see one message at a -// time. Delivery is in ascending log time when the file has message indexes -// (see timeOrdered()), otherwise in file order. -class McapFileReader -{ -public: - explicit McapFileReader(const std::filesystem::path& path, const McapReaderOptions& options = {}); - ~McapFileReader(); - - // Non-copyable - McapFileReader(const McapFileReader&) = delete; - McapFileReader& operator=(const McapFileReader&) = delete; - - // False if the file could not be opened or a requested/auto-detected topic - // could not be resolved; error() then says why. - bool isOpen() const; - const std::string& error() const; - - const ResolvedTopics& topics() const; - const std::vector& channels() const; - - // True when read() delivers messages in ascending log time. False means the - // file has no message indexes and messages arrive in file order instead. - bool timeOrdered() const; - - // The first point-cloud decoding complaint seen during read(), or empty. - // Most importantly, this is where a forced lidar_preset that disagrees with - // the file's own field descriptions gets reported: decoding still proceeds - // with the preset, so the caller must surface this rather than ignore it. - const std::string& lidarLayoutWarning() const; - - // Any callback may be left empty; its topic is then skipped without being - // decoded. - // - // `log_time_ns` is the message's MCAP log time -- the recorder's clock, not the - // sensor clock the payload timestamps are on. Prefer - // McapPoint/McapImuSample::timestamp for anything that has to agree with the - // data. - // - // onPointCloud is only called with a non-empty vector. - struct Callbacks - { - std::function&&)> onPointCloud; - std::function onImu; - std::function onSn; - // Called with the log time of every message read, before it is decoded; for progress reports. - std::function onProgress; - }; - - // Streams the messages whose log time lies in `range` (by default the whole - // file) through `callbacks`. Uses the chunk index to skip the rest when the file - // has one. Returns false on a read error (see error()); a file with no matching - // messages is not an error. - bool read(const Callbacks& callbacks, const LogTimeRange& range = {}); - - // Log times of the file's first and last message, from the statistics record or - // the chunk index; nullopt when the file has neither. - std::optional logTimeSpan() const; - -private: - struct Impl; - std::unique_ptr impl_; -}; + // Topic selection. An empty name means "auto-detect": the reader looks for + // exactly one channel whose schema is the matching ros2 message type. More than + // one candidate is an error for the lidar/IMU streams (picking one silently + // would quietly export the wrong sensor) but not for the serial-number stream, + // which is cosmetic and simply stays unresolved. + struct McapReaderOptions + { + std::string lidar_topic; // sensor_msgs/msg/PointCloud2 + std::string imu_topic; // sensor_msgs/msg/Imu + std::string sn_topic; // std_msgs/msg/String + + // How PointCloud2 point records are unpacked. Auto reads the layout from each + // message's own `fields` array and is right for any bag that fills it in + // honestly; a preset forces a known driver layout for bags that do not. + Pc2Preset lidar_preset = Pc2Preset::Auto; + }; + + // Which ros2 message type the resolved lidar topic actually carries. Needed + // because read() must call a different CDR decoder for each: decodePc2() and + // decodeLivoxCustomMsg() are not interchangeable. + enum class LidarSchema + { + Unknown, + PointCloud2, + LivoxCustomMsg, + }; + + // The topics actually in use after auto-detection; empty means "not present". + struct ResolvedTopics + { + std::string lidar; + std::string imu; + std::string sn; + LidarSchema lidar_schema = LidarSchema::Unknown; + }; + + // Half-open range [start_ns, end_ns) of message log times: the MCAP log time, or + // the record time of a ROS1 bag. The default covers every message. + struct LogTimeRange + { + uint64_t start_ns = 0; + uint64_t end_ns = std::numeric_limits::max(); + }; + + // One channel as found in the file, for --list output and diagnostics. + struct ChannelInfo + { + std::string topic; + std::string schema_name; + std::string message_encoding; + uint64_t message_count = 0; // 0 if the file carries no statistics record + }; + + // Reads ros2msg/CDR-encoded MCAP files back into the McapPoint/McapImuSample + // structs McapFileWriter writes, i.e. the inverse of McapFileWriter. + // + // Decoding is delegated to decodePc2()/decodeImu()/decodeSn() in + // cdr_serializer.hpp, which parse the PointCloud2 `fields` array at runtime and + // therefore handle every PointCloudLayout the writer can emit. + // + // Messages are delivered through callbacks rather than returned in bulk: a real + // recording is far too large to hold in memory, so callers see one message at a + // time. Delivery is in ascending log time when the file has message indexes + // (see timeOrdered()), otherwise in file order. + class McapFileReader + { + public: + explicit McapFileReader(const std::filesystem::path& path, const McapReaderOptions& options = {}); + ~McapFileReader(); + + // Non-copyable + McapFileReader(const McapFileReader&) = delete; + McapFileReader& operator=(const McapFileReader&) = delete; + + // False if the file could not be opened or a requested/auto-detected topic + // could not be resolved; error() then says why. + bool isOpen() const; + const std::string& error() const; + + const ResolvedTopics& topics() const; + const std::vector& channels() const; + + // True when read() delivers messages in ascending log time. False means the + // file has no message indexes and messages arrive in file order instead. + bool timeOrdered() const; + + // The first point-cloud decoding complaint seen during read(), or empty. + // Most importantly, this is where a forced lidar_preset that disagrees with + // the file's own field descriptions gets reported: decoding still proceeds + // with the preset, so the caller must surface this rather than ignore it. + const std::string& lidarLayoutWarning() const; + + // Any callback may be left empty; its topic is then skipped without being + // decoded. + // + // `log_time_ns` is the message's MCAP log time -- the recorder's clock, not the + // sensor clock the payload timestamps are on. Prefer + // McapPoint/McapImuSample::timestamp for anything that has to agree with the + // data. + // + // onPointCloud is only called with a non-empty vector. + struct Callbacks + { + std::function&&)> onPointCloud; + std::function onImu; + std::function onSn; + // Called with the log time of every message read, before it is decoded; for progress reports. + std::function onProgress; + }; + + // Streams the messages whose log time lies in `range` (by default the whole + // file) through `callbacks`. Uses the chunk index to skip the rest when the file + // has one. Returns false on a read error (see error()); a file with no matching + // messages is not an error. + bool read(const Callbacks& callbacks, const LogTimeRange& range = {}); + + // Log times of the file's first and last message, from the statistics record or + // the chunk index; nullopt when the file has neither. + std::optional logTimeSpan() const; + + private: + struct Impl; + std::unique_ptr impl_; + }; } // namespace rosbags diff --git a/rosbags/McapWriter.cpp b/rosbags/McapWriter.cpp index b668f515..ce342857 100644 --- a/rosbags/McapWriter.cpp +++ b/rosbags/McapWriter.cpp @@ -11,11 +11,11 @@ namespace rosbags { -// --------------------------------------------------------------------------- -// ros2msg schema strings (full definitions including nested types) -// --------------------------------------------------------------------------- + // --------------------------------------------------------------------------- + // ros2msg schema strings (full definitions including nested types) + // --------------------------------------------------------------------------- -static constexpr const char* kPointCloud2Schema = R"(std_msgs/Header header + static constexpr const char* kPointCloud2Schema = R"(std_msgs/Header header uint32 height uint32 width sensor_msgs/PointField[] fields @@ -48,10 +48,10 @@ uint8 FLOAT32=7 uint8 FLOAT64=8 )"; -static constexpr const char* kStringSchema = R"(string data + static constexpr const char* kStringSchema = R"(string data )"; -static constexpr const char* kTfMessageSchema = R"(geometry_msgs/TransformStamped[] transforms + static constexpr const char* kTfMessageSchema = R"(geometry_msgs/TransformStamped[] transforms ================================================================================ MSG: geometry_msgs/TransformStamped std_msgs/Header header @@ -82,7 +82,7 @@ float64 z float64 w )"; -static constexpr const char* kImuSchema = R"(std_msgs/Header header + static constexpr const char* kImuSchema = R"(std_msgs/Header header geometry_msgs/Quaternion orientation float64[9] orientation_covariance geometry_msgs/Vector3 angular_velocity @@ -110,459 +110,467 @@ float64 y float64 z )"; -// --------------------------------------------------------------------------- -// PointCloud2 binary layouts, little-endian (see PointCloudLayout in McapWriter.h -// for the full per-layout offset table). Public so the ROS1 bag writer packs -// exactly the same records. -// --------------------------------------------------------------------------- - -std::vector pointCloudFields(PointCloudLayout layout) -{ - switch(layout) - { - case PointCloudLayout::Velodyne: - return { - {"x", 0, 7}, // FLOAT32 - {"y", 4, 7}, // FLOAT32 - {"z", 8, 7}, // FLOAT32 - {"intensity", 12, 7}, // FLOAT32 - {"ring", 16, 4}, // UINT16 - {"time", 18, 8}, // FLOAT64 - }; - case PointCloudLayout::Ouster: - return { - {"x", 0, 7}, // FLOAT32 - {"y", 4, 7}, // FLOAT32 - {"z", 8, 7}, // FLOAT32 - {"intensity", 12, 7}, // FLOAT32 - {"t", 16, 6}, // UINT32 - {"reflectivity", 20, 4}, // UINT16 - {"ring", 22, 4}, // UINT16 - {"ambient", 24, 4}, // UINT16 - }; - case PointCloudLayout::Hesai: - return { - {"x", 0, 7}, // FLOAT32 - {"y", 4, 7}, // FLOAT32 - {"z", 8, 7}, // FLOAT32 - {"intensity", 12, 7}, // FLOAT32 - {"timestamp", 16, 8}, // FLOAT64 - {"ring", 24, 4}, // UINT16 - }; - case PointCloudLayout::Canonical: - return { - {"x", 0, 7}, // FLOAT32 - {"y", 4, 7}, // FLOAT32 - {"z", 8, 7}, // FLOAT32 - {"intensity", 12, 7}, // FLOAT32 - {"ring", 16, 4}, // UINT16 - {"time", 20, 7}, // FLOAT32 - {"t", 24, 6}, // UINT32 - }; - case PointCloudLayout::Generic: - default: - return { - {"x", 0, 7}, // FLOAT32 - {"y", 4, 7}, // FLOAT32 - {"z", 8, 7}, // FLOAT32 - {"intensity", 12, 7}, // FLOAT32 - {"ring", 16, 4}, // UINT16 - {"laser_id", 18, 2}, // UINT8 - {"time", 20, 8}, // FLOAT64 - }; - } -} - -uint32_t pointCloudPointStep(PointCloudLayout layout) -{ - switch(layout) - { - case PointCloudLayout::Velodyne: - case PointCloudLayout::Ouster: - case PointCloudLayout::Hesai: return 26; - case PointCloudLayout::Canonical: - case PointCloudLayout::Generic: - default: return 28; - } -} - -// Packs one point at `d` per `layout`. Done field-by-field to avoid C++ struct -// padding surprises; padding bytes are left as the caller zeroed them. -static void packPoint(uint8_t* d, const McapPoint& p, double t0, PointCloudLayout layout) -{ - const auto put = [&d](const void* v, size_t n) - { - std::memcpy(d, v, n); - d += n; - }; - put(&p.x, 4); - put(&p.y, 4); - put(&p.z, 4); - put(&p.intensity, 4); - - switch(layout) - { - case PointCloudLayout::Velodyne: - { - put(&p.ring, 2); - const double t = p.timestamp - t0; - put(&t, 8); - return; - } - case PointCloudLayout::Ouster: - { - // t: ns relative to the message stamp, matching ouster-ros' per-point offset. - const uint32_t t = static_cast((p.timestamp - t0) * 1e9); - // LAZ carries no native reflectivity/ambient channel: reflectivity is - // approximated from intensity, ambient is always 0. - const uint16_t reflectivity = static_cast(std::clamp(p.intensity, 0.0f, 65535.0f)); - const uint16_t ambient = 0; - put(&t, 4); - put(&reflectivity, 2); - put(&p.ring, 2); - put(&ambient, 2); - return; - } - case PointCloudLayout::Hesai: - { - // timestamp: ABSOLUTE seconds (not relative to t0), per Hesai driver convention. - put(&p.timestamp, 8); - put(&p.ring, 2); - return; - } - case PointCloudLayout::Canonical: - { - put(&p.ring, 2); - d += 2; // padding - const double dt = p.timestamp - t0; - const float time = static_cast(dt); - const uint32_t t = static_cast(std::llround(dt * 1e9)); - put(&time, 4); - put(&t, 4); - return; - } - case PointCloudLayout::Generic: - default: - { - put(&p.ring, 2); - put(&p.laser_id, 1); - d += 1; // padding - const double t = p.timestamp - t0; - put(&t, 8); - return; - } - } -} - -std::vector packPointCloud(const std::vector& points, PointCloudLayout layout) -{ - const uint32_t step = pointCloudPointStep(layout); - std::vector data(points.size() * step, 0); - const double t0 = points.empty() ? 0.0 : points.front().timestamp; - for(size_t i = 0; i < points.size(); ++i) - packPoint(data.data() + i * step, points[i], t0, layout); - return data; -} - -// --------------------------------------------------------------------------- -// CDR helpers -// --------------------------------------------------------------------------- - -static void writeHeader(CdrWriter& w, uint64_t timestamp_ns, const std::string& frame_id) -{ - w.write_i32(static_cast(timestamp_ns / 1'000'000'000ULL)); - w.write_u32(static_cast(timestamp_ns % 1'000'000'000ULL)); - w.write_string(frame_id); -} - -static std::vector serializePointCloud2( - uint64_t timestamp_ns, const std::vector& pts, const std::string& frame_id, PointCloudLayout layout) -{ - CdrWriter w; - - // Header - writeHeader(w, timestamp_ns, frame_id); - - // height / width (unordered: height=1, width=N) - w.write_u32(1); - w.write_u32(static_cast(pts.size())); - - // PointField[] - const auto fields = pointCloudFields(layout); - const uint32_t pointStep = pointCloudPointStep(layout); - - w.write_u32(static_cast(fields.size())); // sequence length - for(const auto& f : fields) - { - w.write_string(f.name); - w.write_u32(f.offset); - w.write_u8(f.datatype); - w.write_u32(1); // count - } - - w.write_bool(false); // is_bigendian - w.write_u32(pointStep); // point_step - w.write_u32(static_cast(pts.size()) * pointStep); // row_step - - // data[] — uint32 length + raw bytes (no internal CDR padding) - const auto data = packPointCloud(pts, layout); - w.write_u32(static_cast(data.size())); - w.write_raw(data.data(), data.size()); - - w.write_bool(true); // is_dense - return w.data(); -} - -static std::vector serializeImu(uint64_t timestamp_ns, const McapImuSample& imu, const std::string& frame_id) -{ - CdrWriter w; - writeHeader(w, timestamp_ns, frame_id); - - // orientation quaternion — identity (no orientation data from lidar IMU) - w.write_f64(0.0); // x - w.write_f64(0.0); // y - w.write_f64(0.0); // z - w.write_f64(1.0); // w - - // orientation_covariance[9] — -1 in [0] signals "unknown" - w.write_f64(-1.0); - for(int i = 1; i < 9; ++i) - w.write_f64(0.0); - - // angular_velocity (rad/s) - w.write_f64(static_cast(imu.gyro_x)); - w.write_f64(static_cast(imu.gyro_y)); - w.write_f64(static_cast(imu.gyro_z)); - - // angular_velocity_covariance[9] - for(int i = 0; i < 9; ++i) - w.write_f64(0.0); - - // linear_acceleration (m/s²) - w.write_f64(static_cast(imu.acc_x)); - w.write_f64(static_cast(imu.acc_y)); - w.write_f64(static_cast(imu.acc_z)); - - // linear_acceleration_covariance[9] - for(int i = 0; i < 9; ++i) - w.write_f64(0.0); - - return w.data(); -} - -// tf2_msgs/msg/TFMessage carrying a single TransformStamped, matching how a -// real /tf topic publishes one changed transform per message. -static std::vector serializeTf( - uint64_t timestamp_ns, const McapTransform& t, const std::string& parent_frame, const std::string& child_frame) -{ - CdrWriter w; - - w.write_u32(1); // transforms[] sequence length - - writeHeader(w, timestamp_ns, parent_frame); // TransformStamped.header - w.write_string(child_frame); - - // transform.translation - w.write_f64(t.tx); - w.write_f64(t.ty); - w.write_f64(t.tz); - - // transform.rotation - w.write_f64(t.qx); - w.write_f64(t.qy); - w.write_f64(t.qz); - w.write_f64(t.qw); - - return w.data(); -} - -// --------------------------------------------------------------------------- -// Impl -// --------------------------------------------------------------------------- - -struct McapFileWriter::Impl -{ - mcap::McapWriter writer; - mcap::ChannelId lidarChannelId{0}; - mcap::ChannelId imuChannelId{0}; - mcap::ChannelId snChannelId{0}; - mcap::ChannelId tfChannelId{0}; - uint32_t lidarSequence{0}; - uint32_t imuSequence{0}; - uint32_t snSequence{0}; - uint32_t tfSequence{0}; - McapWriterOptions options; - bool open{false}; -}; - -McapFileWriter::McapFileWriter(const std::filesystem::path& path, const McapWriterOptions& options) - : impl_(std::make_unique()) -{ - impl_->options = options; - - mcap::McapWriterOptions opts("ros2"); - opts.compression = mcap::Compression::None; - opts.chunkSize = 128ULL * 1024 * 1024; - - auto status = impl_->writer.open(path.string(), opts); - if(!status.ok()) - { - std::cerr << "McapWriter: failed to open " << path << ": " << status.message << "\n"; - return; - } - - // Register PointCloud2 schema (shared by both PointCloudLayout variants -- - // only the runtime `fields`/point_step differ, not the message schema itself) - mcap::Schema pc2Schema("sensor_msgs/msg/PointCloud2", - "ros2msg", - {reinterpret_cast(kPointCloud2Schema), - reinterpret_cast(kPointCloud2Schema) + std::strlen(kPointCloud2Schema)}); - impl_->writer.addSchema(pc2Schema); - - // Register Imu schema - mcap::Schema imuSchema( - "sensor_msgs/msg/Imu", - "ros2msg", - {reinterpret_cast(kImuSchema), reinterpret_cast(kImuSchema) + std::strlen(kImuSchema)}); - impl_->writer.addSchema(imuSchema); - - // Register channels - mcap::Channel lidarChannel(impl_->options.lidar_topic, "cdr", pc2Schema.id); - impl_->writer.addChannel(lidarChannel); - impl_->lidarChannelId = lidarChannel.id; - - mcap::Channel imuChannel(impl_->options.imu_topic, "cdr", imuSchema.id); - impl_->writer.addChannel(imuChannel); - impl_->imuChannelId = imuChannel.id; - - // Register std_msgs/msg/String schema + /lidar_sn channel - mcap::Schema strSchema("std_msgs/msg/String", "ros2msg", - {reinterpret_cast(kStringSchema), - reinterpret_cast(kStringSchema) + std::strlen(kStringSchema)}); - impl_->writer.addSchema(strSchema); - - mcap::Channel snChannel(impl_->options.sn_topic, "cdr", strSchema.id); - impl_->writer.addChannel(snChannel); - impl_->snChannelId = snChannel.id; - - // Register tf2_msgs/msg/TFMessage schema + /tf channel - mcap::Schema tfSchema("tf2_msgs/msg/TFMessage", "ros2msg", - {reinterpret_cast(kTfMessageSchema), - reinterpret_cast(kTfMessageSchema) + std::strlen(kTfMessageSchema)}); - impl_->writer.addSchema(tfSchema); - - mcap::Channel tfChannel(impl_->options.tf_topic, "cdr", tfSchema.id); - impl_->writer.addChannel(tfChannel); - impl_->tfChannelId = tfChannel.id; - - impl_->open = true; -} - -McapFileWriter::~McapFileWriter() -{ - if(impl_ && impl_->open) - impl_->writer.close(); -} - -bool McapFileWriter::isOpen() const -{ - return impl_ && impl_->open; -} - -void McapFileWriter::writeSn(uint64_t timestamp_ns, const std::string& data) -{ - if(!isOpen()) - return; - - CdrWriter w; - w.write_string(data); - - const auto& payload = w.data(); - mcap::Message msg; - msg.channelId = impl_->snChannelId; - msg.sequence = impl_->snSequence++; - msg.publishTime = timestamp_ns; - msg.logTime = timestamp_ns; - msg.data = reinterpret_cast(payload.data()); - msg.dataSize = payload.size(); - - auto status = impl_->writer.write(msg); - if(!status.ok()) - std::cerr << "McapWriter: writeSn error: " << status.message << "\n"; -} - -void McapFileWriter::writePointCloud(uint64_t timestamp_ns, const std::vector& points) -{ - if(!isOpen() || points.empty()) - return; - const std::string& frame_id = impl_->options.pointcloud_frame_id.empty() ? impl_->options.frame_id : impl_->options.pointcloud_frame_id; - auto payload = serializePointCloud2(timestamp_ns, points, frame_id, impl_->options.lidar_layout); - - mcap::Message msg; - msg.channelId = impl_->lidarChannelId; - msg.sequence = impl_->lidarSequence++; - msg.publishTime = timestamp_ns; - msg.logTime = timestamp_ns; - msg.data = reinterpret_cast(payload.data()); - msg.dataSize = payload.size(); - - auto status = impl_->writer.write(msg); - if(!status.ok()) - std::cerr << "McapWriter: write error: " << status.message << "\n"; -} - -void McapFileWriter::writeImuSample(const McapImuSample& sample) -{ - if(!isOpen()) - return; - - const uint64_t ts = static_cast(sample.timestamp * 1e9); - auto payload = serializeImu(ts, sample, impl_->options.frame_id); - - mcap::Message msg; - msg.channelId = impl_->imuChannelId; - msg.sequence = impl_->imuSequence++; - msg.publishTime = ts; - msg.logTime = ts; - msg.data = reinterpret_cast(payload.data()); - msg.dataSize = payload.size(); - - auto s = impl_->writer.write(msg); - if(!s.ok()) - std::cerr << "McapWriter: IMU write error: " << s.message << "\n"; -} - -void McapFileWriter::writeImu(const std::vector& imu) -{ - for(const auto& sample : imu) - writeImuSample(sample); -} - -void McapFileWriter::writeTfSample(const McapTransform& transform) -{ - if(!isOpen()) - return; - - const uint64_t ts = static_cast(transform.timestamp * 1e9); - auto payload = serializeTf(ts, transform, impl_->options.map_frame, impl_->options.frame_id); - - mcap::Message msg; - msg.channelId = impl_->tfChannelId; - msg.sequence = impl_->tfSequence++; - msg.publishTime = ts; - msg.logTime = ts; - msg.data = reinterpret_cast(payload.data()); - msg.dataSize = payload.size(); - - auto s = impl_->writer.write(msg); - if(!s.ok()) - std::cerr << "McapWriter: tf write error: " << s.message << "\n"; -} - -void McapFileWriter::writeTf(const std::vector& transforms) -{ - for(const auto& t : transforms) - writeTfSample(t); -} + // --------------------------------------------------------------------------- + // PointCloud2 binary layouts, little-endian (see PointCloudLayout in McapWriter.h + // for the full per-layout offset table). Public so the ROS1 bag writer packs + // exactly the same records. + // --------------------------------------------------------------------------- + + std::vector pointCloudFields(PointCloudLayout layout) + { + switch (layout) + { + case PointCloudLayout::Velodyne: + return { + { "x", 0, 7 }, // FLOAT32 + { "y", 4, 7 }, // FLOAT32 + { "z", 8, 7 }, // FLOAT32 + { "intensity", 12, 7 }, // FLOAT32 + { "ring", 16, 4 }, // UINT16 + { "time", 18, 8 }, // FLOAT64 + }; + case PointCloudLayout::Ouster: + return { + { "x", 0, 7 }, // FLOAT32 + { "y", 4, 7 }, // FLOAT32 + { "z", 8, 7 }, // FLOAT32 + { "intensity", 12, 7 }, // FLOAT32 + { "t", 16, 6 }, // UINT32 + { "reflectivity", 20, 4 }, // UINT16 + { "ring", 22, 4 }, // UINT16 + { "ambient", 24, 4 }, // UINT16 + }; + case PointCloudLayout::Hesai: + return { + { "x", 0, 7 }, // FLOAT32 + { "y", 4, 7 }, // FLOAT32 + { "z", 8, 7 }, // FLOAT32 + { "intensity", 12, 7 }, // FLOAT32 + { "timestamp", 16, 8 }, // FLOAT64 + { "ring", 24, 4 }, // UINT16 + }; + case PointCloudLayout::Canonical: + return { + { "x", 0, 7 }, // FLOAT32 + { "y", 4, 7 }, // FLOAT32 + { "z", 8, 7 }, // FLOAT32 + { "intensity", 12, 7 }, // FLOAT32 + { "ring", 16, 4 }, // UINT16 + { "time", 20, 7 }, // FLOAT32 + { "t", 24, 6 }, // UINT32 + }; + case PointCloudLayout::Generic: + default: + return { + { "x", 0, 7 }, // FLOAT32 + { "y", 4, 7 }, // FLOAT32 + { "z", 8, 7 }, // FLOAT32 + { "intensity", 12, 7 }, // FLOAT32 + { "ring", 16, 4 }, // UINT16 + { "laser_id", 18, 2 }, // UINT8 + { "time", 20, 8 }, // FLOAT64 + }; + } + } + + uint32_t pointCloudPointStep(PointCloudLayout layout) + { + switch (layout) + { + case PointCloudLayout::Velodyne: + case PointCloudLayout::Ouster: + case PointCloudLayout::Hesai: + return 26; + case PointCloudLayout::Canonical: + case PointCloudLayout::Generic: + default: + return 28; + } + } + + // Packs one point at `d` per `layout`. Done field-by-field to avoid C++ struct + // padding surprises; padding bytes are left as the caller zeroed them. + static void packPoint(uint8_t* d, const McapPoint& p, double t0, PointCloudLayout layout) + { + const auto put = [&d](const void* v, size_t n) + { + std::memcpy(d, v, n); + d += n; + }; + put(&p.x, 4); + put(&p.y, 4); + put(&p.z, 4); + put(&p.intensity, 4); + + switch (layout) + { + case PointCloudLayout::Velodyne: + { + put(&p.ring, 2); + const double t = p.timestamp - t0; + put(&t, 8); + return; + } + case PointCloudLayout::Ouster: + { + // t: ns relative to the message stamp, matching ouster-ros' per-point offset. + const uint32_t t = static_cast((p.timestamp - t0) * 1e9); + // LAZ carries no native reflectivity/ambient channel: reflectivity is + // approximated from intensity, ambient is always 0. + const uint16_t reflectivity = static_cast(std::clamp(p.intensity, 0.0f, 65535.0f)); + const uint16_t ambient = 0; + put(&t, 4); + put(&reflectivity, 2); + put(&p.ring, 2); + put(&ambient, 2); + return; + } + case PointCloudLayout::Hesai: + { + // timestamp: ABSOLUTE seconds (not relative to t0), per Hesai driver convention. + put(&p.timestamp, 8); + put(&p.ring, 2); + return; + } + case PointCloudLayout::Canonical: + { + put(&p.ring, 2); + d += 2; // padding + const double dt = p.timestamp - t0; + const float time = static_cast(dt); + const uint32_t t = static_cast(std::llround(dt * 1e9)); + put(&time, 4); + put(&t, 4); + return; + } + case PointCloudLayout::Generic: + default: + { + put(&p.ring, 2); + put(&p.laser_id, 1); + d += 1; // padding + const double t = p.timestamp - t0; + put(&t, 8); + return; + } + } + } + + std::vector packPointCloud(const std::vector& points, PointCloudLayout layout) + { + const uint32_t step = pointCloudPointStep(layout); + std::vector data(points.size() * step, 0); + const double t0 = points.empty() ? 0.0 : points.front().timestamp; + for (size_t i = 0; i < points.size(); ++i) + packPoint(data.data() + i * step, points[i], t0, layout); + return data; + } + + // --------------------------------------------------------------------------- + // CDR helpers + // --------------------------------------------------------------------------- + + static void writeHeader(CdrWriter& w, uint64_t timestamp_ns, const std::string& frame_id) + { + w.write_i32(static_cast(timestamp_ns / 1'000'000'000ULL)); + w.write_u32(static_cast(timestamp_ns % 1'000'000'000ULL)); + w.write_string(frame_id); + } + + static std::vector serializePointCloud2( + uint64_t timestamp_ns, const std::vector& pts, const std::string& frame_id, PointCloudLayout layout) + { + CdrWriter w; + + // Header + writeHeader(w, timestamp_ns, frame_id); + + // height / width (unordered: height=1, width=N) + w.write_u32(1); + w.write_u32(static_cast(pts.size())); + + // PointField[] + const auto fields = pointCloudFields(layout); + const uint32_t pointStep = pointCloudPointStep(layout); + + w.write_u32(static_cast(fields.size())); // sequence length + for (const auto& f : fields) + { + w.write_string(f.name); + w.write_u32(f.offset); + w.write_u8(f.datatype); + w.write_u32(1); // count + } + + w.write_bool(false); // is_bigendian + w.write_u32(pointStep); // point_step + w.write_u32(static_cast(pts.size()) * pointStep); // row_step + + // data[] — uint32 length + raw bytes (no internal CDR padding) + const auto data = packPointCloud(pts, layout); + w.write_u32(static_cast(data.size())); + w.write_raw(data.data(), data.size()); + + w.write_bool(true); // is_dense + return w.data(); + } + + static std::vector serializeImu(uint64_t timestamp_ns, const McapImuSample& imu, const std::string& frame_id) + { + CdrWriter w; + writeHeader(w, timestamp_ns, frame_id); + + // orientation quaternion — identity (no orientation data from lidar IMU) + w.write_f64(0.0); // x + w.write_f64(0.0); // y + w.write_f64(0.0); // z + w.write_f64(1.0); // w + + // orientation_covariance[9] — -1 in [0] signals "unknown" + w.write_f64(-1.0); + for (int i = 1; i < 9; ++i) + w.write_f64(0.0); + + // angular_velocity (rad/s) + w.write_f64(static_cast(imu.gyro_x)); + w.write_f64(static_cast(imu.gyro_y)); + w.write_f64(static_cast(imu.gyro_z)); + + // angular_velocity_covariance[9] + for (int i = 0; i < 9; ++i) + w.write_f64(0.0); + + // linear_acceleration (m/s²) + w.write_f64(static_cast(imu.acc_x)); + w.write_f64(static_cast(imu.acc_y)); + w.write_f64(static_cast(imu.acc_z)); + + // linear_acceleration_covariance[9] + for (int i = 0; i < 9; ++i) + w.write_f64(0.0); + + return w.data(); + } + + // tf2_msgs/msg/TFMessage carrying a single TransformStamped, matching how a + // real /tf topic publishes one changed transform per message. + static std::vector serializeTf( + uint64_t timestamp_ns, const McapTransform& t, const std::string& parent_frame, const std::string& child_frame) + { + CdrWriter w; + + w.write_u32(1); // transforms[] sequence length + + writeHeader(w, timestamp_ns, parent_frame); // TransformStamped.header + w.write_string(child_frame); + + // transform.translation + w.write_f64(t.tx); + w.write_f64(t.ty); + w.write_f64(t.tz); + + // transform.rotation + w.write_f64(t.qx); + w.write_f64(t.qy); + w.write_f64(t.qz); + w.write_f64(t.qw); + + return w.data(); + } + + // --------------------------------------------------------------------------- + // Impl + // --------------------------------------------------------------------------- + + struct McapFileWriter::Impl + { + mcap::McapWriter writer; + mcap::ChannelId lidarChannelId{ 0 }; + mcap::ChannelId imuChannelId{ 0 }; + mcap::ChannelId snChannelId{ 0 }; + mcap::ChannelId tfChannelId{ 0 }; + uint32_t lidarSequence{ 0 }; + uint32_t imuSequence{ 0 }; + uint32_t snSequence{ 0 }; + uint32_t tfSequence{ 0 }; + McapWriterOptions options; + bool open{ false }; + }; + + McapFileWriter::McapFileWriter(const std::filesystem::path& path, const McapWriterOptions& options) + : impl_(std::make_unique()) + { + impl_->options = options; + + mcap::McapWriterOptions opts("ros2"); + opts.compression = mcap::Compression::None; + opts.chunkSize = 128ULL * 1024 * 1024; + + auto status = impl_->writer.open(path.string(), opts); + if (!status.ok()) + { + std::cerr << "McapWriter: failed to open " << path << ": " << status.message << "\n"; + return; + } + + // Register PointCloud2 schema (shared by both PointCloudLayout variants -- + // only the runtime `fields`/point_step differ, not the message schema itself) + mcap::Schema pc2Schema( + "sensor_msgs/msg/PointCloud2", + "ros2msg", + { reinterpret_cast(kPointCloud2Schema), + reinterpret_cast(kPointCloud2Schema) + std::strlen(kPointCloud2Schema) }); + impl_->writer.addSchema(pc2Schema); + + // Register Imu schema + mcap::Schema imuSchema( + "sensor_msgs/msg/Imu", + "ros2msg", + { reinterpret_cast(kImuSchema), reinterpret_cast(kImuSchema) + std::strlen(kImuSchema) }); + impl_->writer.addSchema(imuSchema); + + // Register channels + mcap::Channel lidarChannel(impl_->options.lidar_topic, "cdr", pc2Schema.id); + impl_->writer.addChannel(lidarChannel); + impl_->lidarChannelId = lidarChannel.id; + + mcap::Channel imuChannel(impl_->options.imu_topic, "cdr", imuSchema.id); + impl_->writer.addChannel(imuChannel); + impl_->imuChannelId = imuChannel.id; + + // Register std_msgs/msg/String schema + /lidar_sn channel + mcap::Schema strSchema( + "std_msgs/msg/String", + "ros2msg", + { reinterpret_cast(kStringSchema), + reinterpret_cast(kStringSchema) + std::strlen(kStringSchema) }); + impl_->writer.addSchema(strSchema); + + mcap::Channel snChannel(impl_->options.sn_topic, "cdr", strSchema.id); + impl_->writer.addChannel(snChannel); + impl_->snChannelId = snChannel.id; + + // Register tf2_msgs/msg/TFMessage schema + /tf channel + mcap::Schema tfSchema( + "tf2_msgs/msg/TFMessage", + "ros2msg", + { reinterpret_cast(kTfMessageSchema), + reinterpret_cast(kTfMessageSchema) + std::strlen(kTfMessageSchema) }); + impl_->writer.addSchema(tfSchema); + + mcap::Channel tfChannel(impl_->options.tf_topic, "cdr", tfSchema.id); + impl_->writer.addChannel(tfChannel); + impl_->tfChannelId = tfChannel.id; + + impl_->open = true; + } + + McapFileWriter::~McapFileWriter() + { + if (impl_ && impl_->open) + impl_->writer.close(); + } + + bool McapFileWriter::isOpen() const + { + return impl_ && impl_->open; + } + + void McapFileWriter::writeSn(uint64_t timestamp_ns, const std::string& data) + { + if (!isOpen()) + return; + + CdrWriter w; + w.write_string(data); + + const auto& payload = w.data(); + mcap::Message msg; + msg.channelId = impl_->snChannelId; + msg.sequence = impl_->snSequence++; + msg.publishTime = timestamp_ns; + msg.logTime = timestamp_ns; + msg.data = reinterpret_cast(payload.data()); + msg.dataSize = payload.size(); + + auto status = impl_->writer.write(msg); + if (!status.ok()) + std::cerr << "McapWriter: writeSn error: " << status.message << "\n"; + } + + void McapFileWriter::writePointCloud(uint64_t timestamp_ns, const std::vector& points) + { + if (!isOpen() || points.empty()) + return; + const std::string& frame_id = + impl_->options.pointcloud_frame_id.empty() ? impl_->options.frame_id : impl_->options.pointcloud_frame_id; + auto payload = serializePointCloud2(timestamp_ns, points, frame_id, impl_->options.lidar_layout); + + mcap::Message msg; + msg.channelId = impl_->lidarChannelId; + msg.sequence = impl_->lidarSequence++; + msg.publishTime = timestamp_ns; + msg.logTime = timestamp_ns; + msg.data = reinterpret_cast(payload.data()); + msg.dataSize = payload.size(); + + auto status = impl_->writer.write(msg); + if (!status.ok()) + std::cerr << "McapWriter: write error: " << status.message << "\n"; + } + + void McapFileWriter::writeImuSample(const McapImuSample& sample) + { + if (!isOpen()) + return; + + const uint64_t ts = static_cast(sample.timestamp * 1e9); + auto payload = serializeImu(ts, sample, impl_->options.frame_id); + + mcap::Message msg; + msg.channelId = impl_->imuChannelId; + msg.sequence = impl_->imuSequence++; + msg.publishTime = ts; + msg.logTime = ts; + msg.data = reinterpret_cast(payload.data()); + msg.dataSize = payload.size(); + + auto s = impl_->writer.write(msg); + if (!s.ok()) + std::cerr << "McapWriter: IMU write error: " << s.message << "\n"; + } + + void McapFileWriter::writeImu(const std::vector& imu) + { + for (const auto& sample : imu) + writeImuSample(sample); + } + + void McapFileWriter::writeTfSample(const McapTransform& transform) + { + if (!isOpen()) + return; + + const uint64_t ts = static_cast(transform.timestamp * 1e9); + auto payload = serializeTf(ts, transform, impl_->options.map_frame, impl_->options.frame_id); + + mcap::Message msg; + msg.channelId = impl_->tfChannelId; + msg.sequence = impl_->tfSequence++; + msg.publishTime = ts; + msg.logTime = ts; + msg.data = reinterpret_cast(payload.data()); + msg.dataSize = payload.size(); + + auto s = impl_->writer.write(msg); + if (!s.ok()) + std::cerr << "McapWriter: tf write error: " << s.message << "\n"; + } + + void McapFileWriter::writeTf(const std::vector& transforms) + { + for (const auto& t : transforms) + writeTfSample(t); + } } // namespace rosbags \ No newline at end of file diff --git a/rosbags/McapWriter.h b/rosbags/McapWriter.h index c7053b79..6c8f8e12 100644 --- a/rosbags/McapWriter.h +++ b/rosbags/McapWriter.h @@ -7,8 +7,8 @@ // re-enable it here before any standard header can lock the disabled value // in for these translation units. #if defined(_MSC_VER) -# undef _HAS_STD_BYTE -# define _HAS_STD_BYTE 1 +#undef _HAS_STD_BYTE +#define _HAS_STD_BYTE 1 #endif #include @@ -20,194 +20,194 @@ // Forward-declare mcap types so this header stays light. namespace mcap { -class McapWriter; + class McapWriter; } namespace rosbags { -// One lidar point, laid out for direct copy into the ros2msg PointCloud2 -// wire format (see McapFileWriter's class comment below). `timestamp` is -// an absolute timestamp in seconds (e.g. LAS/LAZ gps_time), matching the -// unit HDMapping already stores on Core::Point3Di::timestamp. -struct McapPoint -{ - float x{}; - float y{}; - float z{}; - float intensity{}; - uint16_t ring{}; - uint8_t laser_id{}; - double timestamp{}; -}; - -// One IMU sample. `timestamp` is an absolute timestamp in seconds. -// gyro is rad/s, acc is m/s^2 (sensor_msgs/Imu convention) -- values are -// written through as given, no unit conversion is performed. -struct McapImuSample -{ - double timestamp{}; - float gyro_x{}; - float gyro_y{}; - float gyro_z{}; - float acc_x{}; - float acc_y{}; - float acc_z{}; -}; - -// One rigid transform sample (parent -> child), written as a single-element -// tf2_msgs/msg/TFMessage -- one message per sample, matching how a real /tf -// topic carries one changed transform per publish. `timestamp` is an -// absolute timestamp in seconds. Rotation must be a unit quaternion; the -// default is identity. -struct McapTransform -{ - double timestamp{}; - double tx{}; - double ty{}; - double tz{}; - double qx{}; - double qy{}; - double qz{}; - double qw{1.0}; -}; - -// Selects the sensor_msgs/msg/PointCloud2 field layout the lidar channel is -// written with. The message type is always PointCloud2 -- only the `fields` -// array/point_step (and thus which McapPoint members get written) changes, -// to match what a given downstream consumer expects. -enum class PointCloudLayout -{ - Generic, // x,y,z,intensity,ring,laser_id,time -- point_step = 28 (default) - Velodyne, // x,y,z,intensity,ring,time -- point_step = 26 (no laser_id) - Ouster, // x,y,z,intensity,t,reflectivity,ring,ambient -- point_step = 26 - Hesai, // x,y,z,intensity,timestamp,ring -- point_step = 26 - Canonical, // x,y,z,intensity,ring,time(float32),t -- point_step = 28 (benchmark canonical bag) -}; - -// One PointCloud2 field of a layout; datatype as in sensor_msgs/PointField -// (2 UINT8, 4 UINT16, 6 UINT32, 7 FLOAT32, 8 FLOAT64). -struct PointCloudField -{ - const char* name; - uint32_t offset; - uint8_t datatype; -}; - -// The field table and point_step of `layout` (the tables below), and the -// PointCloud2 `data` bytes for `points` in it. Relative per-point times are -// taken from points.front(), so `points` should be sorted by timestamp. -// McapFileWriter uses these, and so does the ROS1 bag writer, so both formats -// carry identical records. -std::vector pointCloudFields(PointCloudLayout layout); -uint32_t pointCloudPointStep(PointCloudLayout layout); -std::vector packPointCloud(const std::vector& points, PointCloudLayout layout); - -struct McapWriterOptions -{ - std::string frame_id = "lidar"; - // Overrides frame_id for PointCloud2 headers only (Imu headers and the - // /tf child_frame_id keep using frame_id). Left empty, PointCloud2 also - // uses frame_id -- unchanged default behavior. Set this to distinguish a - // point cloud published in a fixed frame (e.g. "map", already - // motion-compensated) from a sensor's own moving frame. - std::string pointcloud_frame_id; - // Parent frame written into /tf's TransformStamped.header.frame_id. - std::string map_frame = "map"; - std::string lidar_topic = "/lidar_points"; - std::string imu_topic = "/imu"; - std::string sn_topic = "/lidar_sn"; - std::string tf_topic = "/tf"; - PointCloudLayout lidar_layout = PointCloudLayout::Generic; -}; - -// Writes lidar points and IMU samples to an MCAP file using ros2msg schema -// encoding + CDR serialization. The resulting file is playable with -// `ros2 bag play` and renderable in Foxglove Studio without any ROS2 runtime. -// -// Default topics: -// /lidar_points — sensor_msgs/msg/PointCloud2 (field layout per options().lidar_layout) -// /imu — sensor_msgs/msg/Imu -// /lidar_sn — std_msgs/msg/String -// /tf — tf2_msgs/msg/TFMessage (one TransformStamped per message) -// -// PointCloud2 field layouts (see PointCloudLayout): -// Generic (point_step = 28): -// x float32 offset 0 -// y float32 offset 4 -// z float32 offset 8 -// intensity float32 offset 12 -// ring uint16 offset 16 -// laser_id uint8 offset 18 -// time float64 offset 20 (seconds, relative to the message stamp) -// Velodyne (point_step = 26, no laser_id): -// x float32 offset 0 -// y float32 offset 4 -// z float32 offset 8 -// intensity float32 offset 12 -// ring uint16 offset 16 -// time float64 offset 18 (seconds, relative to the message stamp) -// Ouster (point_step = 26, matches ouster-ros' field names/types): -// x float32 offset 0 -// y float32 offset 4 -// z float32 offset 8 -// intensity float32 offset 12 -// t uint32 offset 16 (nanoseconds, relative to the message stamp) -// reflectivity uint16 offset 20 (McapPoint::intensity clamped to [0,65535]; LAZ has no native reflectivity) -// ring uint16 offset 22 -// ambient uint16 offset 24 (always 0; LAZ has no native ambient-light channel) -// Hesai (point_step = 26, matches common Hesai driver field names/types): -// x float32 offset 0 -// y float32 offset 4 -// z float32 offset 8 -// intensity float32 offset 12 -// timestamp float64 offset 16 (seconds, ABSOLUTE -- not relative to the message stamp, per Hesai convention) -// ring uint16 offset 24 -// Canonical (point_step = 28, the benchmark's canonical spinning-lidar bag; its float32 -// `time` is what FAST-LIO/LIO-SAM Velodyne point types read -- PCL matches fields by -// name and datatype, so the float64 `time` of the Velodyne layout above reads as 0 there): -// x float32 offset 0 -// y float32 offset 4 -// z float32 offset 8 -// intensity float32 offset 12 -// ring uint16 offset 16 (2 bytes padding follow) -// time float32 offset 20 (seconds, relative to the message stamp) -// t uint32 offset 24 (nanoseconds, relative to the message stamp) -class McapFileWriter -{ -public: - explicit McapFileWriter(const std::filesystem::path& path, const McapWriterOptions& options = {}); - ~McapFileWriter(); - - // Non-copyable, movable - McapFileWriter(const McapFileWriter&) = delete; - McapFileWriter& operator=(const McapFileWriter&) = delete; - - // Write a batch of points as a single PointCloud2 message (layout per options().lidar_layout). - // timestamp_ns is the message publish time (nanoseconds since epoch). - void writePointCloud(uint64_t timestamp_ns, const std::vector& points); - - // Write a single IMU sample as its own /imu message. - void writeImuSample(const McapImuSample& imu); - - // Write a batch of IMU samples, one /imu message per sample. - void writeImu(const std::vector& imu); - - // Write a string to /lidar_sn (std_msgs/msg/String). - void writeSn(uint64_t timestamp_ns, const std::string& data); - - // Write a single transform as its own tf2_msgs/msg/TFMessage (one - // TransformStamped, parent = options().map_frame, child = options().frame_id). - void writeTfSample(const McapTransform& transform); - - // Write a batch of transforms, one /tf message per sample. - void writeTf(const std::vector& transforms); - - bool isOpen() const; - -private: - struct Impl; - std::unique_ptr impl_; -}; + // One lidar point, laid out for direct copy into the ros2msg PointCloud2 + // wire format (see McapFileWriter's class comment below). `timestamp` is + // an absolute timestamp in seconds (e.g. LAS/LAZ gps_time), matching the + // unit HDMapping already stores on Core::Point3Di::timestamp. + struct McapPoint + { + float x{}; + float y{}; + float z{}; + float intensity{}; + uint16_t ring{}; + uint8_t laser_id{}; + double timestamp{}; + }; + + // One IMU sample. `timestamp` is an absolute timestamp in seconds. + // gyro is rad/s, acc is m/s^2 (sensor_msgs/Imu convention) -- values are + // written through as given, no unit conversion is performed. + struct McapImuSample + { + double timestamp{}; + float gyro_x{}; + float gyro_y{}; + float gyro_z{}; + float acc_x{}; + float acc_y{}; + float acc_z{}; + }; + + // One rigid transform sample (parent -> child), written as a single-element + // tf2_msgs/msg/TFMessage -- one message per sample, matching how a real /tf + // topic carries one changed transform per publish. `timestamp` is an + // absolute timestamp in seconds. Rotation must be a unit quaternion; the + // default is identity. + struct McapTransform + { + double timestamp{}; + double tx{}; + double ty{}; + double tz{}; + double qx{}; + double qy{}; + double qz{}; + double qw{ 1.0 }; + }; + + // Selects the sensor_msgs/msg/PointCloud2 field layout the lidar channel is + // written with. The message type is always PointCloud2 -- only the `fields` + // array/point_step (and thus which McapPoint members get written) changes, + // to match what a given downstream consumer expects. + enum class PointCloudLayout + { + Generic, // x,y,z,intensity,ring,laser_id,time -- point_step = 28 (default) + Velodyne, // x,y,z,intensity,ring,time -- point_step = 26 (no laser_id) + Ouster, // x,y,z,intensity,t,reflectivity,ring,ambient -- point_step = 26 + Hesai, // x,y,z,intensity,timestamp,ring -- point_step = 26 + Canonical, // x,y,z,intensity,ring,time(float32),t -- point_step = 28 (benchmark canonical bag) + }; + + // One PointCloud2 field of a layout; datatype as in sensor_msgs/PointField + // (2 UINT8, 4 UINT16, 6 UINT32, 7 FLOAT32, 8 FLOAT64). + struct PointCloudField + { + const char* name; + uint32_t offset; + uint8_t datatype; + }; + + // The field table and point_step of `layout` (the tables below), and the + // PointCloud2 `data` bytes for `points` in it. Relative per-point times are + // taken from points.front(), so `points` should be sorted by timestamp. + // McapFileWriter uses these, and so does the ROS1 bag writer, so both formats + // carry identical records. + std::vector pointCloudFields(PointCloudLayout layout); + uint32_t pointCloudPointStep(PointCloudLayout layout); + std::vector packPointCloud(const std::vector& points, PointCloudLayout layout); + + struct McapWriterOptions + { + std::string frame_id = "lidar"; + // Overrides frame_id for PointCloud2 headers only (Imu headers and the + // /tf child_frame_id keep using frame_id). Left empty, PointCloud2 also + // uses frame_id -- unchanged default behavior. Set this to distinguish a + // point cloud published in a fixed frame (e.g. "map", already + // motion-compensated) from a sensor's own moving frame. + std::string pointcloud_frame_id; + // Parent frame written into /tf's TransformStamped.header.frame_id. + std::string map_frame = "map"; + std::string lidar_topic = "/lidar_points"; + std::string imu_topic = "/imu"; + std::string sn_topic = "/lidar_sn"; + std::string tf_topic = "/tf"; + PointCloudLayout lidar_layout = PointCloudLayout::Generic; + }; + + // Writes lidar points and IMU samples to an MCAP file using ros2msg schema + // encoding + CDR serialization. The resulting file is playable with + // `ros2 bag play` and renderable in Foxglove Studio without any ROS2 runtime. + // + // Default topics: + // /lidar_points — sensor_msgs/msg/PointCloud2 (field layout per options().lidar_layout) + // /imu — sensor_msgs/msg/Imu + // /lidar_sn — std_msgs/msg/String + // /tf — tf2_msgs/msg/TFMessage (one TransformStamped per message) + // + // PointCloud2 field layouts (see PointCloudLayout): + // Generic (point_step = 28): + // x float32 offset 0 + // y float32 offset 4 + // z float32 offset 8 + // intensity float32 offset 12 + // ring uint16 offset 16 + // laser_id uint8 offset 18 + // time float64 offset 20 (seconds, relative to the message stamp) + // Velodyne (point_step = 26, no laser_id): + // x float32 offset 0 + // y float32 offset 4 + // z float32 offset 8 + // intensity float32 offset 12 + // ring uint16 offset 16 + // time float64 offset 18 (seconds, relative to the message stamp) + // Ouster (point_step = 26, matches ouster-ros' field names/types): + // x float32 offset 0 + // y float32 offset 4 + // z float32 offset 8 + // intensity float32 offset 12 + // t uint32 offset 16 (nanoseconds, relative to the message stamp) + // reflectivity uint16 offset 20 (McapPoint::intensity clamped to [0,65535]; LAZ has no native reflectivity) + // ring uint16 offset 22 + // ambient uint16 offset 24 (always 0; LAZ has no native ambient-light channel) + // Hesai (point_step = 26, matches common Hesai driver field names/types): + // x float32 offset 0 + // y float32 offset 4 + // z float32 offset 8 + // intensity float32 offset 12 + // timestamp float64 offset 16 (seconds, ABSOLUTE -- not relative to the message stamp, per Hesai convention) + // ring uint16 offset 24 + // Canonical (point_step = 28, the benchmark's canonical spinning-lidar bag; its float32 + // `time` is what FAST-LIO/LIO-SAM Velodyne point types read -- PCL matches fields by + // name and datatype, so the float64 `time` of the Velodyne layout above reads as 0 there): + // x float32 offset 0 + // y float32 offset 4 + // z float32 offset 8 + // intensity float32 offset 12 + // ring uint16 offset 16 (2 bytes padding follow) + // time float32 offset 20 (seconds, relative to the message stamp) + // t uint32 offset 24 (nanoseconds, relative to the message stamp) + class McapFileWriter + { + public: + explicit McapFileWriter(const std::filesystem::path& path, const McapWriterOptions& options = {}); + ~McapFileWriter(); + + // Non-copyable, movable + McapFileWriter(const McapFileWriter&) = delete; + McapFileWriter& operator=(const McapFileWriter&) = delete; + + // Write a batch of points as a single PointCloud2 message (layout per options().lidar_layout). + // timestamp_ns is the message publish time (nanoseconds since epoch). + void writePointCloud(uint64_t timestamp_ns, const std::vector& points); + + // Write a single IMU sample as its own /imu message. + void writeImuSample(const McapImuSample& imu); + + // Write a batch of IMU samples, one /imu message per sample. + void writeImu(const std::vector& imu); + + // Write a string to /lidar_sn (std_msgs/msg/String). + void writeSn(uint64_t timestamp_ns, const std::string& data); + + // Write a single transform as its own tf2_msgs/msg/TFMessage (one + // TransformStamped, parent = options().map_frame, child = options().frame_id). + void writeTfSample(const McapTransform& transform); + + // Write a batch of transforms, one /tf message per sample. + void writeTf(const std::vector& transforms); + + bool isOpen() const; + + private: + struct Impl; + std::unique_ptr impl_; + }; } // namespace rosbags \ No newline at end of file diff --git a/rosbags/OusterPcapReader.cpp b/rosbags/OusterPcapReader.cpp index a168145a..53be03e7 100644 --- a/rosbags/OusterPcapReader.cpp +++ b/rosbags/OusterPcapReader.cpp @@ -12,639 +12,651 @@ namespace rosbags { -namespace -{ - -using nlohmann::json; - -// Non-legacy lidar packet framing ("header_type": "STANDARD"). -constexpr size_t kPacketHeaderBytes = 32; -constexpr size_t kPacketFooterBytes = 32; -constexpr size_t kColumnHeaderBytes = 12; // u64 timestamp ns, u16 measurement_id, u16 status -constexpr size_t kLegacyImuPacketBytes = 48; -// ACCEL32_GYRO32_NMEA IMU packet: the lidar packet header, a 100-byte NMEA -// block (ignored), N measurements, the packet footer. -constexpr size_t kNmeaBlockBytes = 100; -constexpr size_t kImuMeasurementBytes = 36; // u64 timestamp ns, u16 measurement_id, u16 status, 6 x f32 -constexpr double kStandardGravity = 9.80665; - -// Profiles whose channel data block is known without a pixel_data_format. All of -// them carry the first return in word 0 -- range [18:0] in mm, reflectivity -// [31:24] -- then signal and NIR in word 1, and differ only in what follows: -// the RGB ones put red, green, blue in bits [79:64], [95:80], [111:96]. -struct KnownProfile -{ - const char* name; - int pixel_bytes; - bool rgb; -}; -constexpr KnownProfile kKnownProfiles[] = { - {"RNG19_RFL8_SIG16_NIR16", 12, false}, - {"RNG19_RFL8_SIG16_NIR16_RGB16", 16, true}, - // FW 4.0.0 pre-release name of the RGB profile: two RGB sets, 20 bytes. - {"RNG19_RFL8_SIG16_NIR16_R16_G16_B16", 20, true}, -}; - -uint16_t le16(const uint8_t* p) -{ - return static_cast(p[0] | (p[1] << 8)); -} - -uint64_t le64(const uint8_t* p) -{ - uint64_t v = 0; - for(int i = 7; i >= 0; --i) - v = (v << 8) | p[i]; - return v; -} - -float leFloat(const uint8_t* p) -{ - const uint32_t bits = static_cast(p[0]) | (static_cast(p[1]) << 8) | (static_cast(p[2]) << 16) | - (static_cast(p[3]) << 24); - float v; - std::memcpy(&v, &bits, sizeof(v)); - return v; -} - -// Little-endian bit field of a channel data block, as pixel_data_format -// describes it (bit 0 = LSB of byte 0). -uint32_t bitField(const uint8_t* pixel, int start_bit, int width) -{ - const uint8_t* p = pixel + start_bit / 8; - const int shift = start_bit % 8; - const int bytes = (shift + width + 7) / 8; - uint64_t v = 0; - for(int i = bytes - 1; i >= 0; --i) - v = (v << 8) | p[i]; - return static_cast((v >> shift) & ((uint64_t{1} << width) - 1)); -} - -bool readMatrix(const json& parent, const char* key, std::array& out, std::string& error) -{ - if(!parent.contains(key) || !parent[key].is_array() || parent[key].size() != 16) - { - error = std::string("metadata: '") + key + "' must be an array of 16 numbers"; - return false; - } - for(size_t i = 0; i < 16; ++i) - out[i] = parent[key][i].get(); - return true; -} - -bool readAngles(const json& parent, const char* key, size_t expected, std::vector& out, std::string& error) -{ - if(!parent.contains(key) || !parent[key].is_array() || parent[key].size() != expected) - { - error = std::string("metadata: beam_intrinsics.") + key + " must hold one angle per beam (" + std::to_string(expected) + ")"; - return false; - } - out = parent[key].get>(); - return true; -} - -} // namespace - -size_t OusterMetadata::lidarPacketSize() const -{ - return kPacketHeaderBytes + static_cast(columns_per_packet) * (kColumnHeaderBytes + static_cast(pixels_per_column) * pixel_bytes) + - kPacketFooterBytes; -} - -size_t OusterMetadata::imuPacketSize() const -{ - if(udp_profile_imu == "LEGACY") - return kLegacyImuPacketBytes; - if(udp_profile_imu == "ACCEL32_GYRO32_NMEA") - return kPacketHeaderBytes + kNmeaBlockBytes + static_cast(imu_measurements_per_packet) * kImuMeasurementBytes + kPacketFooterBytes; - return 0; -} - -bool parseOusterMetadata(const std::string& json_text, OusterMetadata& out, std::string& error) -{ - OusterMetadata m; - try - { - const json j = json::parse(json_text); - if(!j.contains("lidar_data_format") || !j.contains("beam_intrinsics") || !j.contains("config_params")) - { - error = "metadata: missing lidar_data_format / beam_intrinsics / config_params -- only the non-legacy " - "(FW 2.4+) metadata layout is supported"; - return false; - } - - if(j.contains("sensor_info")) - { - const json& info = j["sensor_info"]; - m.prod_sn = info.value("prod_sn", ""); - m.prod_line = info.value("prod_line", ""); - m.firmware = info.value("image_rev", ""); - if(info.contains("initialization_id") && info["initialization_id"].is_number_unsigned()) - { - m.initialization_id = info["initialization_id"].get(); - m.has_initialization_id = true; - } - } - - const json& config = j["config_params"]; - m.udp_port_lidar = config.value("udp_port_lidar", uint16_t{7502}); - m.udp_port_imu = config.value("udp_port_imu", uint16_t{7503}); - m.udp_profile_imu = config.value("udp_profile_imu", std::string("LEGACY")); - if(j.contains("imu_data_format")) - m.imu_measurements_per_packet = j["imu_data_format"].value("imu_measurements_per_packet", m.imu_measurements_per_packet); - if(m.imu_measurements_per_packet <= 0) - { - error = "metadata: imu_data_format.imu_measurements_per_packet must be positive"; - return false; - } - - const json& format = j["lidar_data_format"]; - m.pixels_per_column = format.at("pixels_per_column").get(); - m.columns_per_packet = format.at("columns_per_packet").get(); - m.columns_per_frame = format.at("columns_per_frame").get(); - m.udp_profile_lidar = format.value("udp_profile_lidar", config.value("udp_profile_lidar", std::string("LEGACY"))); - m.header_type = format.value("header_type", std::string("STANDARD")); - if(m.pixels_per_column <= 0 || m.columns_per_packet <= 0 || m.columns_per_frame <= 0) - { - error = "metadata: lidar_data_format has a non-positive pixels_per_column / columns_per_packet / columns_per_frame"; - return false; - } - if(m.header_type != "STANDARD") - { - error = "metadata: header_type '" + m.header_type + "' is not supported (STANDARD only)"; - return false; - } - if(m.udp_profile_lidar == "LEGACY") - { - error = "metadata: the LEGACY lidar profile is not supported -- reconfigure the sensor to RNG19_RFL8_SIG16_NIR16"; - return false; - } - - // The sensor's own description of the channel data block wins over the - // name table: it is what lets a pre-release profile be read at all. - if(j.contains("pixel_data_format")) - { - const json& pdf = j["pixel_data_format"]; - m.pixel_bytes = pdf.at("pixel_bytes").get(); - bool has_range = false; - std::array rgb_width{}; - for(const auto& field : pdf.at("fields")) - { - const std::string name = field.at("field_name").get(); - const int start = field.at("start_bit").get(); - const int width = field.at("width").get(); - // First match only: in a dual-return profile return 1 is listed first. - // Range fields are in mm (e.g. range_capped_mm_0). - if(!has_range && name.starts_with("range")) - { - m.range_start_bit = start; - m.range_width = width; - has_range = true; - } - else if(m.reflectivity_width == 0 && name.starts_with("reflectivity")) - { - m.reflectivity_start_bit = start; - m.reflectivity_width = width; - } - else - { - // Exact names: the pre-release RGB profile also lists a second - // set, rgb_r1/rgb_g1/rgb_b1, which carries no image. - static constexpr const char* kRgbNames[3] = {"rgb_r", "rgb_g", "rgb_b"}; - for(int c = 0; c < 3; ++c) - { - if(name == kRgbNames[c]) - { - m.rgb_start_bit[c] = start; - rgb_width[c] = width; - } - } - } - } - if(!has_range) - { - error = "metadata: pixel_data_format has no range field"; - return false; - } - // Colour only when all three channels are there and fit a LAS 16-bit channel. - if(rgb_width[0] > 0 && rgb_width[0] <= 16 && rgb_width[1] == rgb_width[0] && rgb_width[2] == rgb_width[0]) - m.rgb_width = rgb_width[0]; - } - else - { - const auto it = std::find_if( - std::begin(kKnownProfiles), - std::end(kKnownProfiles), - [&](const KnownProfile& p) - { - return m.udp_profile_lidar == p.name; - }); - if(it == std::end(kKnownProfiles)) - { - std::string known; - for(const auto& p : kKnownProfiles) - known += std::string(known.empty() ? "" : ", ") + p.name; - error = "metadata: lidar profile '" + m.udp_profile_lidar + "' is not supported and the metadata has no pixel_data_format " - "to describe it (known: " + known + ")"; - return false; - } - m.pixel_bytes = it->pixel_bytes; - m.range_start_bit = 0; - m.range_width = 19; - m.reflectivity_start_bit = 24; - m.reflectivity_width = 8; - if(it->rgb) - { - m.rgb_start_bit = {64, 80, 96}; - m.rgb_width = 16; - } - } - for(const auto& [start, width] : - {std::pair{m.range_start_bit, m.range_width}, - std::pair{m.reflectivity_start_bit, m.reflectivity_width}, - std::pair{m.rgb_start_bit[0], m.rgb_width}, - std::pair{m.rgb_start_bit[1], m.rgb_width}, - std::pair{m.rgb_start_bit[2], m.rgb_width}}) - { - if(width > 32 || start < 0 || start + width > m.pixel_bytes * 8) - { - error = "metadata: a pixel field lies outside the " + std::to_string(m.pixel_bytes) + "-byte channel data block or is wider than 32 bits"; - return false; - } - } - - m.rgb_float16 = m.rgb_width == 16; - - const json& beams = j["beam_intrinsics"]; - const size_t beam_count = static_cast(m.pixels_per_column); - if(!readAngles(beams, "beam_altitude_angles", beam_count, m.beam_altitude_angles_deg, error) || - !readAngles(beams, "beam_azimuth_angles", beam_count, m.beam_azimuth_angles_deg, error)) - return false; - m.lidar_origin_to_beam_origin_mm = beams.value("lidar_origin_to_beam_origin_mm", 0.0); - if(beams.contains("beam_to_lidar_transform")) - { - if(!readMatrix(beams, "beam_to_lidar_transform", m.beam_to_lidar_transform, error)) - return false; - } - else - { - // Pre-FW 2.5 metadata: only the scalar offset, along the beam's x axis. - m.beam_to_lidar_transform = {1, 0, 0, m.lidar_origin_to_beam_origin_mm, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; - } - - if(!j.contains("lidar_intrinsics") || !readMatrix(j["lidar_intrinsics"], "lidar_to_sensor_transform", m.lidar_to_sensor_transform, error)) - { - error = "metadata: lidar_intrinsics.lidar_to_sensor_transform is missing or malformed"; - return false; - } - if(!j.contains("imu_intrinsics") || !readMatrix(j["imu_intrinsics"], "imu_to_sensor_transform", m.imu_to_sensor_transform, error)) - { - error = "metadata: imu_intrinsics.imu_to_sensor_transform is missing or malformed"; - return false; - } - } catch(const std::exception& e) - { - error = std::string("metadata: ") + e.what(); - return false; - } - - out = std::move(m); - return true; -} - -struct OusterPcapReader::Impl -{ - OusterMetadata meta; - OusterPcapReaderOptions options; - OusterPcapStats stats; - std::string error; - bool open = false; - bool stop = false; - bool have_lidar_timestamp = false; - - std::unique_ptr pcap; - uint64_t unrelated_datagrams = 0; // UDP on a port that is neither lidar nor IMU, or too short - - uint64_t prod_sn = 0; - bool check_sn = false; - - // Per pixel (row-major, beam u, measurement id v): point = direction * range_mm - // + offset, already in the sensor frame and in metres -- the Ouster SDK's - // make_xyz_lut() with range_unit = 1 mm. - std::vector lut_direction; - std::vector lut_offset; - std::array imu_rotation{}; - - std::vector points; - std::vector> rgb; - - bool fail(std::string message) - { - if(error.empty()) - error = std::move(message); - // Release the file: a rejected capture must not stay locked (Windows) for the reader's lifetime. - pcap.reset(); - open = false; - return false; - } - - void buildLut() - { - const int w = meta.columns_per_frame; - const int h = meta.pixels_per_column; - const auto& b2l = meta.beam_to_lidar_transform; - const auto& l2s = meta.lidar_to_sensor_transform; - const double beam_offset_x = b2l[3]; - const double beam_offset_z = b2l[11]; - const double n = std::hypot(beam_offset_x, beam_offset_z); - constexpr double kDeg = std::numbers::pi / 180.0; - constexpr double kMmToM = 0.001; - - lut_direction.resize(static_cast(w) * h * 3); - lut_offset.resize(static_cast(w) * h * 3); - for(int u = 0; u < h; ++u) - { - const double azimuth = -meta.beam_azimuth_angles_deg[u] * kDeg; - const double altitude = meta.beam_altitude_angles_deg[u] * kDeg; - for(int v = 0; v < w; ++v) - { - const double encoder = 2.0 * std::numbers::pi - v * (2.0 * std::numbers::pi / w); - const double dir[3] = { - std::cos(encoder + azimuth) * std::cos(altitude), std::sin(encoder + azimuth) * std::cos(altitude), std::sin(altitude)}; - const double off[3] = { - std::cos(encoder) * beam_offset_x - dir[0] * n, std::sin(encoder) * beam_offset_x - dir[1] * n, -dir[2] * n + beam_offset_z}; - - const size_t i = (static_cast(u) * w + v) * 3; - for(int r = 0; r < 3; ++r) - { - const double* row = &l2s[r * 4]; - lut_direction[i + r] = (row[0] * dir[0] + row[1] * dir[1] + row[2] * dir[2]) * kMmToM; - lut_offset[i + r] = (row[0] * off[0] + row[1] * off[1] + row[2] * off[2] + row[3]) * kMmToM; - } - } - } - } - - void handleDatagram(const UdpDatagram& udp) - { - if(udp.dst_port == options.lidar_port) - handleLidar(udp.payload, udp.size); - else if(udp.dst_port == options.imu_port && meta.udp_profile_imu == "LEGACY") - handleLegacyImu(udp.payload, udp.size); - else if(udp.dst_port == options.imu_port && meta.udp_profile_imu == "ACCEL32_GYRO32_NMEA") - handleAccel32Gyro32NmeaImu(udp.payload, udp.size); - else - ++unrelated_datagrams; - syncPcapStats(); - } - - // The capture-level counters come from the pcap reader. - void syncPcapStats() - { - const PcapUdpStats& p = pcap->stats(); - stats.bytes_read = p.bytes_read; - stats.records = p.records; - stats.other_packets = p.non_udp + unrelated_datagrams; - stats.reassembled_datagrams = p.reassembled_datagrams; - stats.dropped_fragments = p.dropped_fragments; - } - - // Packet header init_id / serial number differ from the metadata's. - bool isForeign(const uint8_t* p) const - { - const uint64_t init_id = p[4] | (p[5] << 8) | (static_cast(p[6]) << 16); - uint64_t sn = 0; - for(int i = 11; i >= 7; --i) - sn = (sn << 8) | p[i]; - return (meta.has_initialization_id && init_id != meta.initialization_id) || (check_sn && sn != prod_sn); - } - - void handleLidar(const uint8_t* p, size_t size) - { - if(size != meta.lidarPacketSize()) - { - ++stats.bad_size_packets; - return; - } - if(isForeign(p)) - { - ++stats.foreign_packets; - return; - } - - const int w = meta.columns_per_frame; - const int h = meta.pixels_per_column; - const size_t column_bytes = kColumnHeaderBytes + static_cast(h) * meta.pixel_bytes; - points.clear(); - points.reserve(static_cast(meta.columns_per_packet) * h); - rgb.clear(); - if(meta.rgb_width) - rgb.reserve(points.capacity()); - bool any_valid = false; - for(int c = 0; c < meta.columns_per_packet; ++c) - { - const uint8_t* col = p + kPacketHeaderBytes + c * column_bytes; - const uint64_t timestamp_ns = le64(col); - const uint16_t measurement_id = le16(col + 8); - const uint16_t status = le16(col + 10); - if(!(status & 1) || measurement_id >= w) - { - ++stats.invalid_columns; - continue; - } - const double t = static_cast(timestamp_ns) * 1e-9; - if(!have_lidar_timestamp) - { - stats.first_lidar_timestamp = t; - have_lidar_timestamp = true; - } - stats.last_lidar_timestamp = std::max(stats.last_lidar_timestamp, t); - any_valid = true; - if(measurement_id % options.column_step != 0) - continue; - - const uint8_t* pixel = col + kColumnHeaderBytes; - for(int u = 0; u < h; ++u, pixel += meta.pixel_bytes) - { - const uint32_t range_mm = bitField(pixel, meta.range_start_bit, meta.range_width); - if(range_mm == 0) - continue; // no return - const size_t i = (static_cast(u) * w + measurement_id) * 3; - McapPoint pt; - pt.x = static_cast(lut_direction[i] * range_mm + lut_offset[i]); - pt.y = static_cast(lut_direction[i + 1] * range_mm + lut_offset[i + 1]); - pt.z = static_cast(lut_direction[i + 2] * range_mm + lut_offset[i + 2]); - pt.intensity = - meta.reflectivity_width ? static_cast(bitField(pixel, meta.reflectivity_start_bit, meta.reflectivity_width)) : 0.0f; - pt.ring = static_cast(u); - pt.timestamp = t; - points.push_back(pt); - if(meta.rgb_width) - { - rgb.push_back( - {static_cast(bitField(pixel, meta.rgb_start_bit[0], meta.rgb_width)), - static_cast(bitField(pixel, meta.rgb_start_bit[1], meta.rgb_width)), - static_cast(bitField(pixel, meta.rgb_start_bit[2], meta.rgb_width))}); - } - } - } - if(any_valid) - ++stats.lidar_packets; - if(!points.empty() && onPoints) - onPoints(std::move(points), std::move(rgb)); - points = {}; - rgb = {}; - } - - // Rotates one sample (acceleration in g, gyro in rad/s, IMU frame) into the - // sensor frame and hands it on. - void emitImu(double timestamp, const double (&acc)[3], const double (&gyro)[3]) - { - const auto& r = imu_rotation; - McapImuSample s; - s.timestamp = timestamp; - s.acc_x = static_cast(r[0] * acc[0] + r[1] * acc[1] + r[2] * acc[2]); - s.acc_y = static_cast(r[3] * acc[0] + r[4] * acc[1] + r[5] * acc[2]); - s.acc_z = static_cast(r[6] * acc[0] + r[7] * acc[1] + r[8] * acc[2]); - s.gyro_x = static_cast(r[0] * gyro[0] + r[1] * gyro[1] + r[2] * gyro[2]); - s.gyro_y = static_cast(r[3] * gyro[0] + r[4] * gyro[1] + r[5] * gyro[2]); - s.gyro_z = static_cast(r[6] * gyro[0] + r[7] * gyro[1] + r[8] * gyro[2]); - if(onImu) - onImu(s); - } - - void handleLegacyImu(const uint8_t* p, size_t size) - { - // LEGACY IMU packet: u64 system / accel / gyro read times (ns), then - // accel x y z (g) and gyro x y z (deg/s) as float32. - if(size != kLegacyImuPacketBytes) - { - ++stats.bad_size_packets; - return; - } - constexpr double kDegToRad = std::numbers::pi / 180.0; - const double acc[3] = {leFloat(p + 24), leFloat(p + 28), leFloat(p + 32)}; - const double gyro[3] = {leFloat(p + 36) * kDegToRad, leFloat(p + 40) * kDegToRad, leFloat(p + 44) * kDegToRad}; - ++stats.imu_packets; - // The gyro read time follows the configured timestamp_mode, like the lidar - // column timestamps; the system timestamp is a diagnostic counter. - emitImu(static_cast(le64(p + 16)) * 1e-9, acc, gyro); - } - - void handleAccel32Gyro32NmeaImu(const uint8_t* p, size_t size) - { - // ACCEL32_GYRO32_NMEA (FW 3.1+): standard packet header, NMEA block, then - // per measurement u64 timestamp (ns, same clock as the lidar columns), - // u16 measurement_id, u16 status (bit 0 = valid), accel x y z (m/s^2) - // and gyro x y z (rad/s) as float32. - if(size != meta.imuPacketSize()) - { - ++stats.bad_size_packets; - return; - } - if(isForeign(p)) - { - ++stats.foreign_packets; - return; - } - ++stats.imu_packets; - const uint8_t* m = p + kPacketHeaderBytes + kNmeaBlockBytes; - for(int i = 0; i < meta.imu_measurements_per_packet; ++i, m += kImuMeasurementBytes) - { - if(!(le16(m + 10) & 1)) - continue; - const double acc[3] = { - leFloat(m + 12) / kStandardGravity, leFloat(m + 16) / kStandardGravity, leFloat(m + 20) / kStandardGravity}; - const double gyro[3] = {leFloat(m + 24), leFloat(m + 28), leFloat(m + 32)}; - emitImu(static_cast(le64(m)) * 1e-9, acc, gyro); - } - } - - decltype(Callbacks::onPoints) onPoints; - std::function onImu; -}; - -OusterPcapReader::OusterPcapReader(const std::filesystem::path& pcap_path, const OusterMetadata& metadata, const OusterPcapReaderOptions& options) - : impl_(std::make_unique()) -{ - Impl& d = *impl_; - d.meta = metadata; - d.options = options; - if(d.options.lidar_port == 0) - d.options.lidar_port = metadata.udp_port_lidar; - if(d.options.imu_port == 0) - d.options.imu_port = metadata.udp_port_imu; - d.options.column_step = std::max(1, d.options.column_step); - - if(!metadata.prod_sn.empty()) - { - try - { - d.prod_sn = std::stoull(metadata.prod_sn); - d.check_sn = true; - } catch(const std::exception&) - { - // Non-numeric serial: nothing to compare the 40-bit header field with. - } - } - - const auto& m = metadata.imu_to_sensor_transform; - d.imu_rotation = {m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]}; - d.buildLut(); - - d.pcap = std::make_unique(pcap_path); - if(!d.pcap->isOpen()) - { - d.fail(d.pcap->error()); - return; - } - - d.open = true; -} - -OusterPcapReader::~OusterPcapReader() = default; - -bool OusterPcapReader::isOpen() const -{ - return impl_->open; -} - -const std::string& OusterPcapReader::error() const -{ - return impl_->error; -} - -void OusterPcapReader::requestStop() -{ - impl_->stop = true; -} - -const OusterPcapStats& OusterPcapReader::stats() const -{ - return impl_->stats; -} - -bool OusterPcapReader::read(const Callbacks& callbacks) -{ - Impl& d = *impl_; - if(!d.open) - return false; - d.onPoints = callbacks.onPoints; - d.onImu = callbacks.onImu; - if(d.stop) - return true; - - const bool ok = d.pcap->read( - [&d](const UdpDatagram& udp) - { - d.handleDatagram(udp); - if(d.stop) - d.pcap->requestStop(); - }); - d.syncPcapStats(); - if(!ok) - return d.fail(d.pcap->error()); - return true; -} + namespace + { + + using nlohmann::json; + + // Non-legacy lidar packet framing ("header_type": "STANDARD"). + constexpr size_t kPacketHeaderBytes = 32; + constexpr size_t kPacketFooterBytes = 32; + constexpr size_t kColumnHeaderBytes = 12; // u64 timestamp ns, u16 measurement_id, u16 status + constexpr size_t kLegacyImuPacketBytes = 48; + // ACCEL32_GYRO32_NMEA IMU packet: the lidar packet header, a 100-byte NMEA + // block (ignored), N measurements, the packet footer. + constexpr size_t kNmeaBlockBytes = 100; + constexpr size_t kImuMeasurementBytes = 36; // u64 timestamp ns, u16 measurement_id, u16 status, 6 x f32 + constexpr double kStandardGravity = 9.80665; + + // Profiles whose channel data block is known without a pixel_data_format. All of + // them carry the first return in word 0 -- range [18:0] in mm, reflectivity + // [31:24] -- then signal and NIR in word 1, and differ only in what follows: + // the RGB ones put red, green, blue in bits [79:64], [95:80], [111:96]. + struct KnownProfile + { + const char* name; + int pixel_bytes; + bool rgb; + }; + constexpr KnownProfile kKnownProfiles[] = { + { "RNG19_RFL8_SIG16_NIR16", 12, false }, + { "RNG19_RFL8_SIG16_NIR16_RGB16", 16, true }, + // FW 4.0.0 pre-release name of the RGB profile: two RGB sets, 20 bytes. + { "RNG19_RFL8_SIG16_NIR16_R16_G16_B16", 20, true }, + }; + + uint16_t le16(const uint8_t* p) + { + return static_cast(p[0] | (p[1] << 8)); + } + + uint64_t le64(const uint8_t* p) + { + uint64_t v = 0; + for (int i = 7; i >= 0; --i) + v = (v << 8) | p[i]; + return v; + } + + float leFloat(const uint8_t* p) + { + const uint32_t bits = static_cast(p[0]) | (static_cast(p[1]) << 8) | (static_cast(p[2]) << 16) | + (static_cast(p[3]) << 24); + float v; + std::memcpy(&v, &bits, sizeof(v)); + return v; + } + + // Little-endian bit field of a channel data block, as pixel_data_format + // describes it (bit 0 = LSB of byte 0). + uint32_t bitField(const uint8_t* pixel, int start_bit, int width) + { + const uint8_t* p = pixel + start_bit / 8; + const int shift = start_bit % 8; + const int bytes = (shift + width + 7) / 8; + uint64_t v = 0; + for (int i = bytes - 1; i >= 0; --i) + v = (v << 8) | p[i]; + return static_cast((v >> shift) & ((uint64_t{ 1 } << width) - 1)); + } + + bool readMatrix(const json& parent, const char* key, std::array& out, std::string& error) + { + if (!parent.contains(key) || !parent[key].is_array() || parent[key].size() != 16) + { + error = std::string("metadata: '") + key + "' must be an array of 16 numbers"; + return false; + } + for (size_t i = 0; i < 16; ++i) + out[i] = parent[key][i].get(); + return true; + } + + bool readAngles(const json& parent, const char* key, size_t expected, std::vector& out, std::string& error) + { + if (!parent.contains(key) || !parent[key].is_array() || parent[key].size() != expected) + { + error = + std::string("metadata: beam_intrinsics.") + key + " must hold one angle per beam (" + std::to_string(expected) + ")"; + return false; + } + out = parent[key].get>(); + return true; + } + + } // namespace + + size_t OusterMetadata::lidarPacketSize() const + { + return kPacketHeaderBytes + + static_cast(columns_per_packet) * (kColumnHeaderBytes + static_cast(pixels_per_column) * pixel_bytes) + + kPacketFooterBytes; + } + + size_t OusterMetadata::imuPacketSize() const + { + if (udp_profile_imu == "LEGACY") + return kLegacyImuPacketBytes; + if (udp_profile_imu == "ACCEL32_GYRO32_NMEA") + return kPacketHeaderBytes + kNmeaBlockBytes + static_cast(imu_measurements_per_packet) * kImuMeasurementBytes + + kPacketFooterBytes; + return 0; + } + + bool parseOusterMetadata(const std::string& json_text, OusterMetadata& out, std::string& error) + { + OusterMetadata m; + try + { + const json j = json::parse(json_text); + if (!j.contains("lidar_data_format") || !j.contains("beam_intrinsics") || !j.contains("config_params")) + { + error = "metadata: missing lidar_data_format / beam_intrinsics / config_params -- only the non-legacy " + "(FW 2.4+) metadata layout is supported"; + return false; + } + + if (j.contains("sensor_info")) + { + const json& info = j["sensor_info"]; + m.prod_sn = info.value("prod_sn", ""); + m.prod_line = info.value("prod_line", ""); + m.firmware = info.value("image_rev", ""); + if (info.contains("initialization_id") && info["initialization_id"].is_number_unsigned()) + { + m.initialization_id = info["initialization_id"].get(); + m.has_initialization_id = true; + } + } + + const json& config = j["config_params"]; + m.udp_port_lidar = config.value("udp_port_lidar", uint16_t{ 7502 }); + m.udp_port_imu = config.value("udp_port_imu", uint16_t{ 7503 }); + m.udp_profile_imu = config.value("udp_profile_imu", std::string("LEGACY")); + if (j.contains("imu_data_format")) + m.imu_measurements_per_packet = j["imu_data_format"].value("imu_measurements_per_packet", m.imu_measurements_per_packet); + if (m.imu_measurements_per_packet <= 0) + { + error = "metadata: imu_data_format.imu_measurements_per_packet must be positive"; + return false; + } + + const json& format = j["lidar_data_format"]; + m.pixels_per_column = format.at("pixels_per_column").get(); + m.columns_per_packet = format.at("columns_per_packet").get(); + m.columns_per_frame = format.at("columns_per_frame").get(); + m.udp_profile_lidar = format.value("udp_profile_lidar", config.value("udp_profile_lidar", std::string("LEGACY"))); + m.header_type = format.value("header_type", std::string("STANDARD")); + if (m.pixels_per_column <= 0 || m.columns_per_packet <= 0 || m.columns_per_frame <= 0) + { + error = "metadata: lidar_data_format has a non-positive pixels_per_column / columns_per_packet / columns_per_frame"; + return false; + } + if (m.header_type != "STANDARD") + { + error = "metadata: header_type '" + m.header_type + "' is not supported (STANDARD only)"; + return false; + } + if (m.udp_profile_lidar == "LEGACY") + { + error = "metadata: the LEGACY lidar profile is not supported -- reconfigure the sensor to RNG19_RFL8_SIG16_NIR16"; + return false; + } + + // The sensor's own description of the channel data block wins over the + // name table: it is what lets a pre-release profile be read at all. + if (j.contains("pixel_data_format")) + { + const json& pdf = j["pixel_data_format"]; + m.pixel_bytes = pdf.at("pixel_bytes").get(); + bool has_range = false; + std::array rgb_width{}; + for (const auto& field : pdf.at("fields")) + { + const std::string name = field.at("field_name").get(); + const int start = field.at("start_bit").get(); + const int width = field.at("width").get(); + // First match only: in a dual-return profile return 1 is listed first. + // Range fields are in mm (e.g. range_capped_mm_0). + if (!has_range && name.starts_with("range")) + { + m.range_start_bit = start; + m.range_width = width; + has_range = true; + } + else if (m.reflectivity_width == 0 && name.starts_with("reflectivity")) + { + m.reflectivity_start_bit = start; + m.reflectivity_width = width; + } + else + { + // Exact names: the pre-release RGB profile also lists a second + // set, rgb_r1/rgb_g1/rgb_b1, which carries no image. + static constexpr const char* kRgbNames[3] = { "rgb_r", "rgb_g", "rgb_b" }; + for (int c = 0; c < 3; ++c) + { + if (name == kRgbNames[c]) + { + m.rgb_start_bit[c] = start; + rgb_width[c] = width; + } + } + } + } + if (!has_range) + { + error = "metadata: pixel_data_format has no range field"; + return false; + } + // Colour only when all three channels are there and fit a LAS 16-bit channel. + if (rgb_width[0] > 0 && rgb_width[0] <= 16 && rgb_width[1] == rgb_width[0] && rgb_width[2] == rgb_width[0]) + m.rgb_width = rgb_width[0]; + } + else + { + const auto it = std::find_if( + std::begin(kKnownProfiles), + std::end(kKnownProfiles), + [&](const KnownProfile& p) + { + return m.udp_profile_lidar == p.name; + }); + if (it == std::end(kKnownProfiles)) + { + std::string known; + for (const auto& p : kKnownProfiles) + known += std::string(known.empty() ? "" : ", ") + p.name; + error = "metadata: lidar profile '" + m.udp_profile_lidar + + "' is not supported and the metadata has no pixel_data_format " + "to describe it (known: " + + known + ")"; + return false; + } + m.pixel_bytes = it->pixel_bytes; + m.range_start_bit = 0; + m.range_width = 19; + m.reflectivity_start_bit = 24; + m.reflectivity_width = 8; + if (it->rgb) + { + m.rgb_start_bit = { 64, 80, 96 }; + m.rgb_width = 16; + } + } + for (const auto& [start, width] : { std::pair{ m.range_start_bit, m.range_width }, + std::pair{ m.reflectivity_start_bit, m.reflectivity_width }, + std::pair{ m.rgb_start_bit[0], m.rgb_width }, + std::pair{ m.rgb_start_bit[1], m.rgb_width }, + std::pair{ m.rgb_start_bit[2], m.rgb_width } }) + { + if (width > 32 || start < 0 || start + width > m.pixel_bytes * 8) + { + error = "metadata: a pixel field lies outside the " + std::to_string(m.pixel_bytes) + + "-byte channel data block or is wider than 32 bits"; + return false; + } + } + + m.rgb_float16 = m.rgb_width == 16; + + const json& beams = j["beam_intrinsics"]; + const size_t beam_count = static_cast(m.pixels_per_column); + if (!readAngles(beams, "beam_altitude_angles", beam_count, m.beam_altitude_angles_deg, error) || + !readAngles(beams, "beam_azimuth_angles", beam_count, m.beam_azimuth_angles_deg, error)) + return false; + m.lidar_origin_to_beam_origin_mm = beams.value("lidar_origin_to_beam_origin_mm", 0.0); + if (beams.contains("beam_to_lidar_transform")) + { + if (!readMatrix(beams, "beam_to_lidar_transform", m.beam_to_lidar_transform, error)) + return false; + } + else + { + // Pre-FW 2.5 metadata: only the scalar offset, along the beam's x axis. + m.beam_to_lidar_transform = { 1, 0, 0, m.lidar_origin_to_beam_origin_mm, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; + } + + if (!j.contains("lidar_intrinsics") || + !readMatrix(j["lidar_intrinsics"], "lidar_to_sensor_transform", m.lidar_to_sensor_transform, error)) + { + error = "metadata: lidar_intrinsics.lidar_to_sensor_transform is missing or malformed"; + return false; + } + if (!j.contains("imu_intrinsics") || + !readMatrix(j["imu_intrinsics"], "imu_to_sensor_transform", m.imu_to_sensor_transform, error)) + { + error = "metadata: imu_intrinsics.imu_to_sensor_transform is missing or malformed"; + return false; + } + } catch (const std::exception& e) + { + error = std::string("metadata: ") + e.what(); + return false; + } + + out = std::move(m); + return true; + } + + struct OusterPcapReader::Impl + { + OusterMetadata meta; + OusterPcapReaderOptions options; + OusterPcapStats stats; + std::string error; + bool open = false; + bool stop = false; + bool have_lidar_timestamp = false; + + std::unique_ptr pcap; + uint64_t unrelated_datagrams = 0; // UDP on a port that is neither lidar nor IMU, or too short + + uint64_t prod_sn = 0; + bool check_sn = false; + + // Per pixel (row-major, beam u, measurement id v): point = direction * range_mm + // + offset, already in the sensor frame and in metres -- the Ouster SDK's + // make_xyz_lut() with range_unit = 1 mm. + std::vector lut_direction; + std::vector lut_offset; + std::array imu_rotation{}; + + std::vector points; + std::vector> rgb; + + bool fail(std::string message) + { + if (error.empty()) + error = std::move(message); + // Release the file: a rejected capture must not stay locked (Windows) for the reader's lifetime. + pcap.reset(); + open = false; + return false; + } + + void buildLut() + { + const int w = meta.columns_per_frame; + const int h = meta.pixels_per_column; + const auto& b2l = meta.beam_to_lidar_transform; + const auto& l2s = meta.lidar_to_sensor_transform; + const double beam_offset_x = b2l[3]; + const double beam_offset_z = b2l[11]; + const double n = std::hypot(beam_offset_x, beam_offset_z); + constexpr double kDeg = std::numbers::pi / 180.0; + constexpr double kMmToM = 0.001; + + lut_direction.resize(static_cast(w) * h * 3); + lut_offset.resize(static_cast(w) * h * 3); + for (int u = 0; u < h; ++u) + { + const double azimuth = -meta.beam_azimuth_angles_deg[u] * kDeg; + const double altitude = meta.beam_altitude_angles_deg[u] * kDeg; + for (int v = 0; v < w; ++v) + { + const double encoder = 2.0 * std::numbers::pi - v * (2.0 * std::numbers::pi / w); + const double dir[3] = { std::cos(encoder + azimuth) * std::cos(altitude), + std::sin(encoder + azimuth) * std::cos(altitude), + std::sin(altitude) }; + const double off[3] = { std::cos(encoder) * beam_offset_x - dir[0] * n, + std::sin(encoder) * beam_offset_x - dir[1] * n, + -dir[2] * n + beam_offset_z }; + + const size_t i = (static_cast(u) * w + v) * 3; + for (int r = 0; r < 3; ++r) + { + const double* row = &l2s[r * 4]; + lut_direction[i + r] = (row[0] * dir[0] + row[1] * dir[1] + row[2] * dir[2]) * kMmToM; + lut_offset[i + r] = (row[0] * off[0] + row[1] * off[1] + row[2] * off[2] + row[3]) * kMmToM; + } + } + } + } + + void handleDatagram(const UdpDatagram& udp) + { + if (udp.dst_port == options.lidar_port) + handleLidar(udp.payload, udp.size); + else if (udp.dst_port == options.imu_port && meta.udp_profile_imu == "LEGACY") + handleLegacyImu(udp.payload, udp.size); + else if (udp.dst_port == options.imu_port && meta.udp_profile_imu == "ACCEL32_GYRO32_NMEA") + handleAccel32Gyro32NmeaImu(udp.payload, udp.size); + else + ++unrelated_datagrams; + syncPcapStats(); + } + + // The capture-level counters come from the pcap reader. + void syncPcapStats() + { + const PcapUdpStats& p = pcap->stats(); + stats.bytes_read = p.bytes_read; + stats.records = p.records; + stats.other_packets = p.non_udp + unrelated_datagrams; + stats.reassembled_datagrams = p.reassembled_datagrams; + stats.dropped_fragments = p.dropped_fragments; + } + + // Packet header init_id / serial number differ from the metadata's. + bool isForeign(const uint8_t* p) const + { + const uint64_t init_id = p[4] | (p[5] << 8) | (static_cast(p[6]) << 16); + uint64_t sn = 0; + for (int i = 11; i >= 7; --i) + sn = (sn << 8) | p[i]; + return (meta.has_initialization_id && init_id != meta.initialization_id) || (check_sn && sn != prod_sn); + } + + void handleLidar(const uint8_t* p, size_t size) + { + if (size != meta.lidarPacketSize()) + { + ++stats.bad_size_packets; + return; + } + if (isForeign(p)) + { + ++stats.foreign_packets; + return; + } + + const int w = meta.columns_per_frame; + const int h = meta.pixels_per_column; + const size_t column_bytes = kColumnHeaderBytes + static_cast(h) * meta.pixel_bytes; + points.clear(); + points.reserve(static_cast(meta.columns_per_packet) * h); + rgb.clear(); + if (meta.rgb_width) + rgb.reserve(points.capacity()); + bool any_valid = false; + for (int c = 0; c < meta.columns_per_packet; ++c) + { + const uint8_t* col = p + kPacketHeaderBytes + c * column_bytes; + const uint64_t timestamp_ns = le64(col); + const uint16_t measurement_id = le16(col + 8); + const uint16_t status = le16(col + 10); + if (!(status & 1) || measurement_id >= w) + { + ++stats.invalid_columns; + continue; + } + const double t = static_cast(timestamp_ns) * 1e-9; + if (!have_lidar_timestamp) + { + stats.first_lidar_timestamp = t; + have_lidar_timestamp = true; + } + stats.last_lidar_timestamp = std::max(stats.last_lidar_timestamp, t); + any_valid = true; + if (measurement_id % options.column_step != 0) + continue; + + const uint8_t* pixel = col + kColumnHeaderBytes; + for (int u = 0; u < h; ++u, pixel += meta.pixel_bytes) + { + const uint32_t range_mm = bitField(pixel, meta.range_start_bit, meta.range_width); + if (range_mm == 0) + continue; // no return + const size_t i = (static_cast(u) * w + measurement_id) * 3; + McapPoint pt; + pt.x = static_cast(lut_direction[i] * range_mm + lut_offset[i]); + pt.y = static_cast(lut_direction[i + 1] * range_mm + lut_offset[i + 1]); + pt.z = static_cast(lut_direction[i + 2] * range_mm + lut_offset[i + 2]); + pt.intensity = meta.reflectivity_width + ? static_cast(bitField(pixel, meta.reflectivity_start_bit, meta.reflectivity_width)) + : 0.0f; + pt.ring = static_cast(u); + pt.timestamp = t; + points.push_back(pt); + if (meta.rgb_width) + { + rgb.push_back( + { static_cast(bitField(pixel, meta.rgb_start_bit[0], meta.rgb_width)), + static_cast(bitField(pixel, meta.rgb_start_bit[1], meta.rgb_width)), + static_cast(bitField(pixel, meta.rgb_start_bit[2], meta.rgb_width)) }); + } + } + } + if (any_valid) + ++stats.lidar_packets; + if (!points.empty() && onPoints) + onPoints(std::move(points), std::move(rgb)); + points = {}; + rgb = {}; + } + + // Rotates one sample (acceleration in g, gyro in rad/s, IMU frame) into the + // sensor frame and hands it on. + void emitImu(double timestamp, const double (&acc)[3], const double (&gyro)[3]) + { + const auto& r = imu_rotation; + McapImuSample s; + s.timestamp = timestamp; + s.acc_x = static_cast(r[0] * acc[0] + r[1] * acc[1] + r[2] * acc[2]); + s.acc_y = static_cast(r[3] * acc[0] + r[4] * acc[1] + r[5] * acc[2]); + s.acc_z = static_cast(r[6] * acc[0] + r[7] * acc[1] + r[8] * acc[2]); + s.gyro_x = static_cast(r[0] * gyro[0] + r[1] * gyro[1] + r[2] * gyro[2]); + s.gyro_y = static_cast(r[3] * gyro[0] + r[4] * gyro[1] + r[5] * gyro[2]); + s.gyro_z = static_cast(r[6] * gyro[0] + r[7] * gyro[1] + r[8] * gyro[2]); + if (onImu) + onImu(s); + } + + void handleLegacyImu(const uint8_t* p, size_t size) + { + // LEGACY IMU packet: u64 system / accel / gyro read times (ns), then + // accel x y z (g) and gyro x y z (deg/s) as float32. + if (size != kLegacyImuPacketBytes) + { + ++stats.bad_size_packets; + return; + } + constexpr double kDegToRad = std::numbers::pi / 180.0; + const double acc[3] = { leFloat(p + 24), leFloat(p + 28), leFloat(p + 32) }; + const double gyro[3] = { leFloat(p + 36) * kDegToRad, leFloat(p + 40) * kDegToRad, leFloat(p + 44) * kDegToRad }; + ++stats.imu_packets; + // The gyro read time follows the configured timestamp_mode, like the lidar + // column timestamps; the system timestamp is a diagnostic counter. + emitImu(static_cast(le64(p + 16)) * 1e-9, acc, gyro); + } + + void handleAccel32Gyro32NmeaImu(const uint8_t* p, size_t size) + { + // ACCEL32_GYRO32_NMEA (FW 3.1+): standard packet header, NMEA block, then + // per measurement u64 timestamp (ns, same clock as the lidar columns), + // u16 measurement_id, u16 status (bit 0 = valid), accel x y z (m/s^2) + // and gyro x y z (rad/s) as float32. + if (size != meta.imuPacketSize()) + { + ++stats.bad_size_packets; + return; + } + if (isForeign(p)) + { + ++stats.foreign_packets; + return; + } + ++stats.imu_packets; + const uint8_t* m = p + kPacketHeaderBytes + kNmeaBlockBytes; + for (int i = 0; i < meta.imu_measurements_per_packet; ++i, m += kImuMeasurementBytes) + { + if (!(le16(m + 10) & 1)) + continue; + const double acc[3] = { leFloat(m + 12) / kStandardGravity, + leFloat(m + 16) / kStandardGravity, + leFloat(m + 20) / kStandardGravity }; + const double gyro[3] = { leFloat(m + 24), leFloat(m + 28), leFloat(m + 32) }; + emitImu(static_cast(le64(m)) * 1e-9, acc, gyro); + } + } + + decltype(Callbacks::onPoints) onPoints; + std::function onImu; + }; + + OusterPcapReader::OusterPcapReader( + const std::filesystem::path& pcap_path, const OusterMetadata& metadata, const OusterPcapReaderOptions& options) + : impl_(std::make_unique()) + { + Impl& d = *impl_; + d.meta = metadata; + d.options = options; + if (d.options.lidar_port == 0) + d.options.lidar_port = metadata.udp_port_lidar; + if (d.options.imu_port == 0) + d.options.imu_port = metadata.udp_port_imu; + d.options.column_step = std::max(1, d.options.column_step); + + if (!metadata.prod_sn.empty()) + { + try + { + d.prod_sn = std::stoull(metadata.prod_sn); + d.check_sn = true; + } catch (const std::exception&) + { + // Non-numeric serial: nothing to compare the 40-bit header field with. + } + } + + const auto& m = metadata.imu_to_sensor_transform; + d.imu_rotation = { m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10] }; + d.buildLut(); + + d.pcap = std::make_unique(pcap_path); + if (!d.pcap->isOpen()) + { + d.fail(d.pcap->error()); + return; + } + + d.open = true; + } + + OusterPcapReader::~OusterPcapReader() = default; + + bool OusterPcapReader::isOpen() const + { + return impl_->open; + } + + const std::string& OusterPcapReader::error() const + { + return impl_->error; + } + + void OusterPcapReader::requestStop() + { + impl_->stop = true; + } + + const OusterPcapStats& OusterPcapReader::stats() const + { + return impl_->stats; + } + + bool OusterPcapReader::read(const Callbacks& callbacks) + { + Impl& d = *impl_; + if (!d.open) + return false; + d.onPoints = callbacks.onPoints; + d.onImu = callbacks.onImu; + if (d.stop) + return true; + + const bool ok = d.pcap->read( + [&d](const UdpDatagram& udp) + { + d.handleDatagram(udp); + if (d.stop) + d.pcap->requestStop(); + }); + d.syncPcapStats(); + if (!ok) + return d.fail(d.pcap->error()); + return true; + } } // namespace rosbags diff --git a/rosbags/OusterPcapReader.h b/rosbags/OusterPcapReader.h index 48ffd2d2..5b49bee8 100644 --- a/rosbags/OusterPcapReader.h +++ b/rosbags/OusterPcapReader.h @@ -11,139 +11,140 @@ namespace rosbags { -// Ouster sensor description, parsed from the metadata JSON the Ouster SDK / -// Ouster Studio / the sensor's HTTP API (`/api/v1/sensor/metadata`) write next -// to a recording. Only the non-legacy layout (FW 2.4+: config_params, -// lidar_data_format, beam_intrinsics, ...) is understood. -struct OusterMetadata -{ - std::string prod_sn; - std::string prod_line; - std::string firmware; - uint64_t initialization_id = 0; - bool has_initialization_id = false; - - uint16_t udp_port_lidar = 7502; - uint16_t udp_port_imu = 7503; - std::string udp_profile_lidar; - std::string udp_profile_imu; - std::string header_type; - - int pixels_per_column = 0; - int columns_per_packet = 0; - int columns_per_frame = 0; - - // Channel data block layout: bytes per pixel and where the first-return range - // (mm) and reflectivity live inside it. From `pixel_data_format` when the - // metadata carries one (FW 4.0 does, including pre-release profiles no SDK - // knows), otherwise from a table of known profile names. - int pixel_bytes = 0; - int range_start_bit = 0; - int range_width = 0; - int reflectivity_start_bit = 0; - int reflectivity_width = 0; // 0 = profile has no reflectivity - std::array rgb_start_bit{}; // red, green, blue - int rgb_width = 0; // 0 = profile has no colour - // The 16-bit colour words are IEEE half floats (linear, HDR) -- how the Ouster - // SDK decodes FW 4.0 RGB16 -- not unsigned integers. - bool rgb_float16 = false; - - std::vector beam_altitude_angles_deg; - std::vector beam_azimuth_angles_deg; - std::array beam_to_lidar_transform{}; // row-major 4x4, mm - double lidar_origin_to_beam_origin_mm = 0.0; - std::array lidar_to_sensor_transform{}; // row-major 4x4, mm - std::array imu_to_sensor_transform{}; // row-major 4x4, mm - - // ACCEL32_GYRO32_NMEA only: samples per IMU packet (imu_data_format). - int imu_measurements_per_packet = 8; - - // Bytes in one lidar UDP payload: packet header + columns + packet footer. - size_t lidarPacketSize() const; - // Bytes in one IMU UDP payload for udp_profile_imu; 0 = unsupported profile. - size_t imuPacketSize() const; -}; - -// Parses `json_text`. On failure returns false and fills `error`. -bool parseOusterMetadata(const std::string& json_text, OusterMetadata& out, std::string& error); - -struct OusterPcapReaderOptions -{ - // 0 = take the port from the metadata. - uint16_t lidar_port = 0; - uint16_t imu_port = 0; - - // Keep every Nth measurement column (1 = all). Thins the cloud horizontally - // without touching the vertical beam pattern. - int column_step = 1; -}; - -struct OusterPcapStats -{ - uint64_t bytes_read = 0; // record headers and payloads consumed so far, for progress against the file size - uint64_t records = 0; - uint64_t lidar_packets = 0; - uint64_t imu_packets = 0; - uint64_t other_packets = 0; // non-UDP, non-IPv4, or a port that is neither lidar nor IMU - uint64_t bad_size_packets = 0; // on the lidar/IMU port but the wrong length for the metadata's profile - uint64_t foreign_packets = 0; // header init_id / serial number does not match the metadata - uint64_t invalid_columns = 0; // column status bit 0 clear (no data, e.g. outside the azimuth window) - uint64_t reassembled_datagrams = 0; - uint64_t dropped_fragments = 0; // IPv4 fragments of a datagram that never completed - double first_lidar_timestamp = 0.0; - double last_lidar_timestamp = 0.0; -}; - -// Streams lidar points and IMU samples out of a classic libpcap capture of an -// Ouster sensor (tcpdump, Wireshark saved as "pcap", ouster-cli / Ouster SDK -// recordings). Ethernet / Linux cooked (SLL, SLL2) / raw-IP link types; IPv4 -// only; fragmented UDP datagrams (a 128-beam lidar packet is ~20-25 kB, far -// above a 1500-byte MTU) are reassembled. -// -// Points come out in the SENSOR frame (lidar_to_sensor_transform applied) in -// metres, each stamped with its column's timestamp in seconds on the sensor -// clock. Zero-range (no return) pixels are dropped. Intensity carries the 8-bit -// calibrated reflectivity, the scale mandeye's own LAZ files use. On an RGB -// profile each point's colour comes alongside, as the sensor's raw 16-bit words. -// -// IMU samples (LEGACY or ACCEL32_GYRO32_NMEA profile) are rotated into the sensor frame, -// gyro in rad/s, acceleration in g -- the units mandeye's imuNNNN.csv uses, -// NOT the m/s^2 McapImuSample documents for bags; MandeyeSessionWriter writes -// the values through unchanged. -class OusterPcapReader -{ -public: - struct Callbacks - { - // One lidar packet's worth of points, in column (= time) order. `rgb` is - // parallel to `points` (raw red, green, blue words) on an RGB profile and - // empty otherwise. - std::function&& points, std::vector>&& rgb)> onPoints; - std::function onImu; - }; - - OusterPcapReader(const std::filesystem::path& pcap_path, const OusterMetadata& metadata, const OusterPcapReaderOptions& options = {}); - ~OusterPcapReader(); - - OusterPcapReader(const OusterPcapReader&) = delete; - OusterPcapReader& operator=(const OusterPcapReader&) = delete; - - bool isOpen() const; - const std::string& error() const; - - // Reads the whole capture front to back. Returns false on an I/O or format - // error; packets it cannot use are counted in stats(), not treated as errors. - bool read(const Callbacks& callbacks); - - // Makes read() return after the packet being processed -- callable from a - // callback to end the read early. - void requestStop(); - - const OusterPcapStats& stats() const; - -private: - struct Impl; - std::unique_ptr impl_; -}; + // Ouster sensor description, parsed from the metadata JSON the Ouster SDK / + // Ouster Studio / the sensor's HTTP API (`/api/v1/sensor/metadata`) write next + // to a recording. Only the non-legacy layout (FW 2.4+: config_params, + // lidar_data_format, beam_intrinsics, ...) is understood. + struct OusterMetadata + { + std::string prod_sn; + std::string prod_line; + std::string firmware; + uint64_t initialization_id = 0; + bool has_initialization_id = false; + + uint16_t udp_port_lidar = 7502; + uint16_t udp_port_imu = 7503; + std::string udp_profile_lidar; + std::string udp_profile_imu; + std::string header_type; + + int pixels_per_column = 0; + int columns_per_packet = 0; + int columns_per_frame = 0; + + // Channel data block layout: bytes per pixel and where the first-return range + // (mm) and reflectivity live inside it. From `pixel_data_format` when the + // metadata carries one (FW 4.0 does, including pre-release profiles no SDK + // knows), otherwise from a table of known profile names. + int pixel_bytes = 0; + int range_start_bit = 0; + int range_width = 0; + int reflectivity_start_bit = 0; + int reflectivity_width = 0; // 0 = profile has no reflectivity + std::array rgb_start_bit{}; // red, green, blue + int rgb_width = 0; // 0 = profile has no colour + // The 16-bit colour words are IEEE half floats (linear, HDR) -- how the Ouster + // SDK decodes FW 4.0 RGB16 -- not unsigned integers. + bool rgb_float16 = false; + + std::vector beam_altitude_angles_deg; + std::vector beam_azimuth_angles_deg; + std::array beam_to_lidar_transform{}; // row-major 4x4, mm + double lidar_origin_to_beam_origin_mm = 0.0; + std::array lidar_to_sensor_transform{}; // row-major 4x4, mm + std::array imu_to_sensor_transform{}; // row-major 4x4, mm + + // ACCEL32_GYRO32_NMEA only: samples per IMU packet (imu_data_format). + int imu_measurements_per_packet = 8; + + // Bytes in one lidar UDP payload: packet header + columns + packet footer. + size_t lidarPacketSize() const; + // Bytes in one IMU UDP payload for udp_profile_imu; 0 = unsupported profile. + size_t imuPacketSize() const; + }; + + // Parses `json_text`. On failure returns false and fills `error`. + bool parseOusterMetadata(const std::string& json_text, OusterMetadata& out, std::string& error); + + struct OusterPcapReaderOptions + { + // 0 = take the port from the metadata. + uint16_t lidar_port = 0; + uint16_t imu_port = 0; + + // Keep every Nth measurement column (1 = all). Thins the cloud horizontally + // without touching the vertical beam pattern. + int column_step = 1; + }; + + struct OusterPcapStats + { + uint64_t bytes_read = 0; // record headers and payloads consumed so far, for progress against the file size + uint64_t records = 0; + uint64_t lidar_packets = 0; + uint64_t imu_packets = 0; + uint64_t other_packets = 0; // non-UDP, non-IPv4, or a port that is neither lidar nor IMU + uint64_t bad_size_packets = 0; // on the lidar/IMU port but the wrong length for the metadata's profile + uint64_t foreign_packets = 0; // header init_id / serial number does not match the metadata + uint64_t invalid_columns = 0; // column status bit 0 clear (no data, e.g. outside the azimuth window) + uint64_t reassembled_datagrams = 0; + uint64_t dropped_fragments = 0; // IPv4 fragments of a datagram that never completed + double first_lidar_timestamp = 0.0; + double last_lidar_timestamp = 0.0; + }; + + // Streams lidar points and IMU samples out of a classic libpcap capture of an + // Ouster sensor (tcpdump, Wireshark saved as "pcap", ouster-cli / Ouster SDK + // recordings). Ethernet / Linux cooked (SLL, SLL2) / raw-IP link types; IPv4 + // only; fragmented UDP datagrams (a 128-beam lidar packet is ~20-25 kB, far + // above a 1500-byte MTU) are reassembled. + // + // Points come out in the SENSOR frame (lidar_to_sensor_transform applied) in + // metres, each stamped with its column's timestamp in seconds on the sensor + // clock. Zero-range (no return) pixels are dropped. Intensity carries the 8-bit + // calibrated reflectivity, the scale mandeye's own LAZ files use. On an RGB + // profile each point's colour comes alongside, as the sensor's raw 16-bit words. + // + // IMU samples (LEGACY or ACCEL32_GYRO32_NMEA profile) are rotated into the sensor frame, + // gyro in rad/s, acceleration in g -- the units mandeye's imuNNNN.csv uses, + // NOT the m/s^2 McapImuSample documents for bags; MandeyeSessionWriter writes + // the values through unchanged. + class OusterPcapReader + { + public: + struct Callbacks + { + // One lidar packet's worth of points, in column (= time) order. `rgb` is + // parallel to `points` (raw red, green, blue words) on an RGB profile and + // empty otherwise. + std::function&& points, std::vector>&& rgb)> onPoints; + std::function onImu; + }; + + OusterPcapReader( + const std::filesystem::path& pcap_path, const OusterMetadata& metadata, const OusterPcapReaderOptions& options = {}); + ~OusterPcapReader(); + + OusterPcapReader(const OusterPcapReader&) = delete; + OusterPcapReader& operator=(const OusterPcapReader&) = delete; + + bool isOpen() const; + const std::string& error() const; + + // Reads the whole capture front to back. Returns false on an I/O or format + // error; packets it cannot use are counted in stats(), not treated as errors. + bool read(const Callbacks& callbacks); + + // Makes read() return after the packet being processed -- callable from a + // callback to end the read early. + void requestStop(); + + const OusterPcapStats& stats() const; + + private: + struct Impl; + std::unique_ptr impl_; + }; } // namespace rosbags diff --git a/rosbags/PcapUdpReader.cpp b/rosbags/PcapUdpReader.cpp index b496656d..d72b8ced 100644 --- a/rosbags/PcapUdpReader.cpp +++ b/rosbags/PcapUdpReader.cpp @@ -12,439 +12,439 @@ namespace rosbags { -namespace -{ - -// pcap link-layer types handled by ipOffset(). -constexpr uint32_t kLinkNull = 0; -constexpr uint32_t kLinkEthernet = 1; -constexpr uint32_t kLinkRaw = 101; -constexpr uint32_t kLinkLoop = 108; -constexpr uint32_t kLinkLinuxSll = 113; -constexpr uint32_t kLinkIpv4 = 228; -constexpr uint32_t kLinkLinuxSll2 = 276; - -// Larger records are not plausible captures of a sensor (and guard the buffer -// against a corrupt length field). -constexpr uint32_t kMaxRecordBytes = 256 * 1024; - -// Datagrams waiting for their missing fragments. A sensor interleaves at most a -// lidar and an IMU datagram, so anything beyond this is fragments whose -// datagram will never complete (packet loss): the oldest is dropped. -constexpr size_t kMaxPendingDatagrams = 64; - -constexpr uint32_t kZstdMagic = 0xFD2FB528; - -uint16_t be16(const uint8_t* p) -{ - return static_cast((p[0] << 8) | p[1]); -} - -uint32_t be32(const uint8_t* p) -{ - return (static_cast(p[0]) << 24) | (static_cast(p[1]) << 16) | (static_cast(p[2]) << 8) | p[3]; -} - -uint32_t swap32(uint32_t v) -{ - return (v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24); -} - -} // namespace - -struct PcapUdpReader::Impl -{ - PcapUdpStats stats; - std::string error; - bool open = false; - bool stop = false; - - std::ifstream in; - std::vector file_buffer; - - // zstd-compressed capture: compressed input and decompressed output windows. - ZSTD_DStream* zstd = nullptr; - std::vector zin, zout; - ZSTD_inBuffer zin_view{nullptr, 0, 0}; - size_t zout_pos = 0, zout_size = 0; - bool zstd_done = false; - - bool swapped = false; - bool nanoseconds = false; - uint32_t linktype = 0; - - struct PendingDatagram - { - std::map> parts; // byte offset -> payload - uint32_t total = 0; // known once the last fragment arrives - uint64_t age = 0; - }; - std::map, PendingDatagram> pending; - uint64_t pending_clock = 0; - - std::vector record; - std::vector datagram; - std::function on_datagram; - - ~Impl() - { - if(zstd) - ZSTD_freeDStream(zstd); - } - - bool fail(std::string message) - { - if(error.empty()) - error = std::move(message); - // Release the file: a rejected capture must not stay locked (Windows) for the reader's lifetime. - in.close(); - open = false; - return false; - } - - // Reads exactly n bytes of the (decompressed) capture. False at the end of - // the data, or on a decompression error (which also sets `error`). - bool readBytes(void* dst, size_t n) - { - if(!zstd) - { - if(!in.read(static_cast(dst), static_cast(n))) - return false; - stats.compressed_bytes_read += n; - return true; - } - auto* out = static_cast(dst); - while(n > 0) - { - if(zout_pos == zout_size) - { - if(!refillZstd()) - return false; - continue; - } - const size_t take = std::min(n, zout_size - zout_pos); - std::memcpy(out, zout.data() + zout_pos, take); - zout_pos += take; - out += take; - n -= take; - } - return true; - } - - // Decompresses the next window of output. False at the end of the stream or on an error. - bool refillZstd() - { - while(true) - { - if(zin_view.pos == zin_view.size) - { - if(zstd_done) - return false; - in.read(reinterpret_cast(zin.data()), static_cast(zin.size())); - const auto got = static_cast(in.gcount()); - if(got == 0) - { - zstd_done = true; - return false; - } - stats.compressed_bytes_read += got; - zin_view = {zin.data(), got, 0}; - } - ZSTD_outBuffer out{zout.data(), zout.size(), 0}; - const size_t rc = ZSTD_decompressStream(zstd, &out, &zin_view); - if(ZSTD_isError(rc)) - { - error = std::string("zstd: ") + ZSTD_getErrorName(rc); - zstd_done = true; - return false; - } - if(out.pos > 0) - { - zout_pos = 0; - zout_size = out.pos; - return true; - } - } - } - - uint32_t u32(const uint8_t* p) const - { - uint32_t v; - std::memcpy(&v, p, sizeof(v)); - return swapped ? swap32(v) : v; - } - - // Locates the IPv4 header inside a captured frame. Returns false for anything - // that is not IPv4 (ARP, IPv6, ...). - bool ipOffset(const uint8_t* frame, size_t size, size_t& offset) const - { - switch(linktype) - { - case kLinkEthernet: - { - size_t off = 12; - if(size < off + 2) - return false; - uint16_t ethertype = be16(frame + off); - while(ethertype == 0x8100 || ethertype == 0x88A8 || ethertype == 0x9100) // VLAN / QinQ tags - { - off += 4; - if(size < off + 2) - return false; - ethertype = be16(frame + off); - } - offset = off + 2; - return ethertype == 0x0800; - } - case kLinkLinuxSll: - offset = 16; - return size >= 16 && be16(frame + 14) == 0x0800; - case kLinkLinuxSll2: - offset = 20; - return size >= 20 && be16(frame) == 0x0800; - case kLinkNull: - case kLinkLoop: - offset = 4; - return size >= 4 && (u32(frame) == 2 || swap32(u32(frame)) == 2); // AF_INET, host order of the capturing machine - default: // kLinkRaw, kLinkIpv4 - offset = 0; - return size >= 1 && (frame[0] >> 4) == 4; - } - } - - void handleUdp(const uint8_t* ip, const uint8_t* udp, size_t size, int64_t time_ns) - { - if(size < 8) - { - ++stats.non_udp; - return; - } - UdpDatagram d; - d.src_ip = be32(ip + 12); - d.dst_ip = be32(ip + 16); - d.src_port = be16(udp); - d.dst_port = be16(udp + 2); - d.size = std::min(std::max(be16(udp + 4), 8), size) - 8; - d.payload = udp + 8; - d.capture_time_ns = time_ns; - if(on_datagram) - on_datagram(d); - } - - // Feeds one IPv4 fragment in; once every byte of its datagram has arrived, - // hands the reassembled UDP datagram on and forgets it. - void handleFragment(const uint8_t* ip, size_t ihl, size_t ip_length, int64_t time_ns) - { - const auto key = std::make_tuple(be32(ip + 12), be32(ip + 16), be16(ip + 4)); - const uint16_t flags_offset = be16(ip + 6); - const bool more_fragments = (flags_offset & 0x2000) != 0; - const uint32_t offset = static_cast(flags_offset & 0x1FFF) * 8; - const size_t length = ip_length - ihl; - - auto [it, inserted] = pending.try_emplace(key); - PendingDatagram& d = it->second; - if(inserted) - d.age = pending_clock++; - d.parts[offset].assign(ip + ihl, ip + ihl + length); - if(!more_fragments) - d.total = offset + static_cast(length); - - if(d.total != 0) - { - uint32_t covered = 0; - for(const auto& [part_offset, bytes] : d.parts) - { - if(part_offset > covered) - break; // hole - covered = std::max(covered, part_offset + static_cast(bytes.size())); - } - if(covered >= d.total) - { - datagram.assign(d.total, 0); - for(const auto& [part_offset, bytes] : d.parts) - { - if(part_offset >= d.total) - break; - std::memcpy(datagram.data() + part_offset, bytes.data(), std::min(bytes.size(), d.total - part_offset)); - } - pending.erase(it); - ++stats.reassembled_datagrams; - handleUdp(ip, datagram.data(), datagram.size(), time_ns); - return; - } - } - - if(pending.size() > kMaxPendingDatagrams) - { - auto oldest = std::min_element( - pending.begin(), - pending.end(), - [](const auto& a, const auto& b) - { - return a.second.age < b.second.age; - }); - stats.dropped_fragments += oldest->second.parts.size(); - pending.erase(oldest); - } - } - - void handleFrame(const uint8_t* frame, size_t size, int64_t time_ns) - { - size_t off = 0; - if(!ipOffset(frame, size, off) || size < off + 20) - { - ++stats.non_udp; - return; - } - const uint8_t* ip = frame + off; - const size_t ihl = static_cast(ip[0] & 0x0F) * 4; - const size_t ip_length = std::min(be16(ip + 2), size - off); - if((ip[0] >> 4) != 4 || ihl < 20 || ip_length < ihl || ip[9] != 17 /* UDP */) - { - ++stats.non_udp; - return; - } - if((be16(ip + 6) & 0x3FFF) != 0) // more-fragments flag or a non-zero offset - handleFragment(ip, ihl, ip_length, time_ns); - else - handleUdp(ip, ip + ihl, ip_length - ihl, time_ns); - } -}; - -PcapUdpReader::PcapUdpReader(const std::filesystem::path& path) - : impl_(std::make_unique()) -{ - Impl& d = *impl_; - d.file_buffer.resize(1 << 20); - d.in.rdbuf()->pubsetbuf(d.file_buffer.data(), static_cast(d.file_buffer.size())); - d.in.open(path, std::ios::binary); - if(!d.in.is_open()) - { - d.fail("cannot open " + path.string()); - return; - } - - uint8_t magic_bytes[4]; - if(!d.in.read(reinterpret_cast(magic_bytes), sizeof(magic_bytes))) - { - d.fail(path.string() + " is too short to be a pcap file"); - return; - } - uint32_t file_magic; - std::memcpy(&file_magic, magic_bytes, sizeof(file_magic)); - d.in.seekg(0); - if(file_magic == kZstdMagic) - { - d.zstd = ZSTD_createDStream(); - if(!d.zstd || ZSTD_isError(ZSTD_initDStream(d.zstd))) - { - d.fail("cannot create a zstd decompressor for " + path.string()); - return; - } - d.zin.resize(ZSTD_DStreamInSize()); - d.zout.resize(ZSTD_DStreamOutSize()); - } - - uint8_t header[24]; - if(!d.readBytes(header, sizeof(header))) - { - d.fail(d.error.empty() ? path.string() + " is too short to be a pcap file" : path.string() + ": " + d.error); - return; - } - uint32_t magic; - std::memcpy(&magic, header, sizeof(magic)); - switch(magic) - { - case 0xA1B2C3D4: - break; - case 0xA1B23C4D: - d.nanoseconds = true; - break; - case 0xD4C3B2A1: - d.swapped = true; - break; - case 0x4D3CB2A1: - d.swapped = d.nanoseconds = true; - break; - case 0x0A0D0D0A: - d.fail(path.string() + " is pcapng, which is not supported -- convert it with: editcap -F pcap in.pcapng out.pcap"); - return; - default: - d.fail(path.string() + " is not a pcap file"); - return; - } - d.linktype = d.u32(header + 20) & 0x0FFFFFFF; // upper bits: FCS length flags - switch(d.linktype) - { - case kLinkNull: - case kLinkEthernet: - case kLinkRaw: - case kLinkLoop: - case kLinkLinuxSll: - case kLinkIpv4: - case kLinkLinuxSll2: - break; - default: - d.fail("unsupported pcap link type " + std::to_string(d.linktype)); - return; - } - - d.open = true; -} - -PcapUdpReader::~PcapUdpReader() = default; - -bool PcapUdpReader::isOpen() const -{ - return impl_->open; -} - -const std::string& PcapUdpReader::error() const -{ - return impl_->error; -} - -void PcapUdpReader::requestStop() -{ - impl_->stop = true; -} - -const PcapUdpStats& PcapUdpReader::stats() const -{ - return impl_->stats; -} - -bool PcapUdpReader::read(const std::function& on_datagram) -{ - Impl& d = *impl_; - if(!d.open) - return false; - d.on_datagram = on_datagram; - - uint8_t record_header[16]; - while(!d.stop) - { - if(!d.readBytes(record_header, sizeof(record_header))) - break; // end of file; a torn final header (capture killed mid-write) ends it too - const uint32_t captured = d.u32(record_header + 8); - if(captured > kMaxRecordBytes) - return d.fail("corrupt pcap record #" + std::to_string(d.stats.records + 1) + ": " + std::to_string(captured) + " bytes"); - d.record.resize(captured); - if(!d.readBytes(d.record.data(), captured)) - break; // torn final record - ++d.stats.records; - d.stats.bytes_read += sizeof(record_header) + captured; - const int64_t seconds = d.u32(record_header); - const int64_t fraction = d.u32(record_header + 4); - const int64_t time_ns = seconds * 1000000000 + (d.nanoseconds ? fraction : fraction * 1000); - d.handleFrame(d.record.data(), d.record.size(), time_ns); - } - for(const auto& [key, datagram] : d.pending) - d.stats.dropped_fragments += datagram.parts.size(); - d.pending.clear(); - if(!d.error.empty()) // a decompression error - return d.fail(d.error); - return true; -} + namespace + { + + // pcap link-layer types handled by ipOffset(). + constexpr uint32_t kLinkNull = 0; + constexpr uint32_t kLinkEthernet = 1; + constexpr uint32_t kLinkRaw = 101; + constexpr uint32_t kLinkLoop = 108; + constexpr uint32_t kLinkLinuxSll = 113; + constexpr uint32_t kLinkIpv4 = 228; + constexpr uint32_t kLinkLinuxSll2 = 276; + + // Larger records are not plausible captures of a sensor (and guard the buffer + // against a corrupt length field). + constexpr uint32_t kMaxRecordBytes = 256 * 1024; + + // Datagrams waiting for their missing fragments. A sensor interleaves at most a + // lidar and an IMU datagram, so anything beyond this is fragments whose + // datagram will never complete (packet loss): the oldest is dropped. + constexpr size_t kMaxPendingDatagrams = 64; + + constexpr uint32_t kZstdMagic = 0xFD2FB528; + + uint16_t be16(const uint8_t* p) + { + return static_cast((p[0] << 8) | p[1]); + } + + uint32_t be32(const uint8_t* p) + { + return (static_cast(p[0]) << 24) | (static_cast(p[1]) << 16) | (static_cast(p[2]) << 8) | p[3]; + } + + uint32_t swap32(uint32_t v) + { + return (v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | (v << 24); + } + + } // namespace + + struct PcapUdpReader::Impl + { + PcapUdpStats stats; + std::string error; + bool open = false; + bool stop = false; + + std::ifstream in; + std::vector file_buffer; + + // zstd-compressed capture: compressed input and decompressed output windows. + ZSTD_DStream* zstd = nullptr; + std::vector zin, zout; + ZSTD_inBuffer zin_view{ nullptr, 0, 0 }; + size_t zout_pos = 0, zout_size = 0; + bool zstd_done = false; + + bool swapped = false; + bool nanoseconds = false; + uint32_t linktype = 0; + + struct PendingDatagram + { + std::map> parts; // byte offset -> payload + uint32_t total = 0; // known once the last fragment arrives + uint64_t age = 0; + }; + std::map, PendingDatagram> pending; + uint64_t pending_clock = 0; + + std::vector record; + std::vector datagram; + std::function on_datagram; + + ~Impl() + { + if (zstd) + ZSTD_freeDStream(zstd); + } + + bool fail(std::string message) + { + if (error.empty()) + error = std::move(message); + // Release the file: a rejected capture must not stay locked (Windows) for the reader's lifetime. + in.close(); + open = false; + return false; + } + + // Reads exactly n bytes of the (decompressed) capture. False at the end of + // the data, or on a decompression error (which also sets `error`). + bool readBytes(void* dst, size_t n) + { + if (!zstd) + { + if (!in.read(static_cast(dst), static_cast(n))) + return false; + stats.compressed_bytes_read += n; + return true; + } + auto* out = static_cast(dst); + while (n > 0) + { + if (zout_pos == zout_size) + { + if (!refillZstd()) + return false; + continue; + } + const size_t take = std::min(n, zout_size - zout_pos); + std::memcpy(out, zout.data() + zout_pos, take); + zout_pos += take; + out += take; + n -= take; + } + return true; + } + + // Decompresses the next window of output. False at the end of the stream or on an error. + bool refillZstd() + { + while (true) + { + if (zin_view.pos == zin_view.size) + { + if (zstd_done) + return false; + in.read(reinterpret_cast(zin.data()), static_cast(zin.size())); + const auto got = static_cast(in.gcount()); + if (got == 0) + { + zstd_done = true; + return false; + } + stats.compressed_bytes_read += got; + zin_view = { zin.data(), got, 0 }; + } + ZSTD_outBuffer out{ zout.data(), zout.size(), 0 }; + const size_t rc = ZSTD_decompressStream(zstd, &out, &zin_view); + if (ZSTD_isError(rc)) + { + error = std::string("zstd: ") + ZSTD_getErrorName(rc); + zstd_done = true; + return false; + } + if (out.pos > 0) + { + zout_pos = 0; + zout_size = out.pos; + return true; + } + } + } + + uint32_t u32(const uint8_t* p) const + { + uint32_t v; + std::memcpy(&v, p, sizeof(v)); + return swapped ? swap32(v) : v; + } + + // Locates the IPv4 header inside a captured frame. Returns false for anything + // that is not IPv4 (ARP, IPv6, ...). + bool ipOffset(const uint8_t* frame, size_t size, size_t& offset) const + { + switch (linktype) + { + case kLinkEthernet: + { + size_t off = 12; + if (size < off + 2) + return false; + uint16_t ethertype = be16(frame + off); + while (ethertype == 0x8100 || ethertype == 0x88A8 || ethertype == 0x9100) // VLAN / QinQ tags + { + off += 4; + if (size < off + 2) + return false; + ethertype = be16(frame + off); + } + offset = off + 2; + return ethertype == 0x0800; + } + case kLinkLinuxSll: + offset = 16; + return size >= 16 && be16(frame + 14) == 0x0800; + case kLinkLinuxSll2: + offset = 20; + return size >= 20 && be16(frame) == 0x0800; + case kLinkNull: + case kLinkLoop: + offset = 4; + return size >= 4 && (u32(frame) == 2 || swap32(u32(frame)) == 2); // AF_INET, host order of the capturing machine + default: // kLinkRaw, kLinkIpv4 + offset = 0; + return size >= 1 && (frame[0] >> 4) == 4; + } + } + + void handleUdp(const uint8_t* ip, const uint8_t* udp, size_t size, int64_t time_ns) + { + if (size < 8) + { + ++stats.non_udp; + return; + } + UdpDatagram d; + d.src_ip = be32(ip + 12); + d.dst_ip = be32(ip + 16); + d.src_port = be16(udp); + d.dst_port = be16(udp + 2); + d.size = std::min(std::max(be16(udp + 4), 8), size) - 8; + d.payload = udp + 8; + d.capture_time_ns = time_ns; + if (on_datagram) + on_datagram(d); + } + + // Feeds one IPv4 fragment in; once every byte of its datagram has arrived, + // hands the reassembled UDP datagram on and forgets it. + void handleFragment(const uint8_t* ip, size_t ihl, size_t ip_length, int64_t time_ns) + { + const auto key = std::make_tuple(be32(ip + 12), be32(ip + 16), be16(ip + 4)); + const uint16_t flags_offset = be16(ip + 6); + const bool more_fragments = (flags_offset & 0x2000) != 0; + const uint32_t offset = static_cast(flags_offset & 0x1FFF) * 8; + const size_t length = ip_length - ihl; + + auto [it, inserted] = pending.try_emplace(key); + PendingDatagram& d = it->second; + if (inserted) + d.age = pending_clock++; + d.parts[offset].assign(ip + ihl, ip + ihl + length); + if (!more_fragments) + d.total = offset + static_cast(length); + + if (d.total != 0) + { + uint32_t covered = 0; + for (const auto& [part_offset, bytes] : d.parts) + { + if (part_offset > covered) + break; // hole + covered = std::max(covered, part_offset + static_cast(bytes.size())); + } + if (covered >= d.total) + { + datagram.assign(d.total, 0); + for (const auto& [part_offset, bytes] : d.parts) + { + if (part_offset >= d.total) + break; + std::memcpy(datagram.data() + part_offset, bytes.data(), std::min(bytes.size(), d.total - part_offset)); + } + pending.erase(it); + ++stats.reassembled_datagrams; + handleUdp(ip, datagram.data(), datagram.size(), time_ns); + return; + } + } + + if (pending.size() > kMaxPendingDatagrams) + { + auto oldest = std::min_element( + pending.begin(), + pending.end(), + [](const auto& a, const auto& b) + { + return a.second.age < b.second.age; + }); + stats.dropped_fragments += oldest->second.parts.size(); + pending.erase(oldest); + } + } + + void handleFrame(const uint8_t* frame, size_t size, int64_t time_ns) + { + size_t off = 0; + if (!ipOffset(frame, size, off) || size < off + 20) + { + ++stats.non_udp; + return; + } + const uint8_t* ip = frame + off; + const size_t ihl = static_cast(ip[0] & 0x0F) * 4; + const size_t ip_length = std::min(be16(ip + 2), size - off); + if ((ip[0] >> 4) != 4 || ihl < 20 || ip_length < ihl || ip[9] != 17 /* UDP */) + { + ++stats.non_udp; + return; + } + if ((be16(ip + 6) & 0x3FFF) != 0) // more-fragments flag or a non-zero offset + handleFragment(ip, ihl, ip_length, time_ns); + else + handleUdp(ip, ip + ihl, ip_length - ihl, time_ns); + } + }; + + PcapUdpReader::PcapUdpReader(const std::filesystem::path& path) + : impl_(std::make_unique()) + { + Impl& d = *impl_; + d.file_buffer.resize(1 << 20); + d.in.rdbuf()->pubsetbuf(d.file_buffer.data(), static_cast(d.file_buffer.size())); + d.in.open(path, std::ios::binary); + if (!d.in.is_open()) + { + d.fail("cannot open " + path.string()); + return; + } + + uint8_t magic_bytes[4]; + if (!d.in.read(reinterpret_cast(magic_bytes), sizeof(magic_bytes))) + { + d.fail(path.string() + " is too short to be a pcap file"); + return; + } + uint32_t file_magic; + std::memcpy(&file_magic, magic_bytes, sizeof(file_magic)); + d.in.seekg(0); + if (file_magic == kZstdMagic) + { + d.zstd = ZSTD_createDStream(); + if (!d.zstd || ZSTD_isError(ZSTD_initDStream(d.zstd))) + { + d.fail("cannot create a zstd decompressor for " + path.string()); + return; + } + d.zin.resize(ZSTD_DStreamInSize()); + d.zout.resize(ZSTD_DStreamOutSize()); + } + + uint8_t header[24]; + if (!d.readBytes(header, sizeof(header))) + { + d.fail(d.error.empty() ? path.string() + " is too short to be a pcap file" : path.string() + ": " + d.error); + return; + } + uint32_t magic; + std::memcpy(&magic, header, sizeof(magic)); + switch (magic) + { + case 0xA1B2C3D4: + break; + case 0xA1B23C4D: + d.nanoseconds = true; + break; + case 0xD4C3B2A1: + d.swapped = true; + break; + case 0x4D3CB2A1: + d.swapped = d.nanoseconds = true; + break; + case 0x0A0D0D0A: + d.fail(path.string() + " is pcapng, which is not supported -- convert it with: editcap -F pcap in.pcapng out.pcap"); + return; + default: + d.fail(path.string() + " is not a pcap file"); + return; + } + d.linktype = d.u32(header + 20) & 0x0FFFFFFF; // upper bits: FCS length flags + switch (d.linktype) + { + case kLinkNull: + case kLinkEthernet: + case kLinkRaw: + case kLinkLoop: + case kLinkLinuxSll: + case kLinkIpv4: + case kLinkLinuxSll2: + break; + default: + d.fail("unsupported pcap link type " + std::to_string(d.linktype)); + return; + } + + d.open = true; + } + + PcapUdpReader::~PcapUdpReader() = default; + + bool PcapUdpReader::isOpen() const + { + return impl_->open; + } + + const std::string& PcapUdpReader::error() const + { + return impl_->error; + } + + void PcapUdpReader::requestStop() + { + impl_->stop = true; + } + + const PcapUdpStats& PcapUdpReader::stats() const + { + return impl_->stats; + } + + bool PcapUdpReader::read(const std::function& on_datagram) + { + Impl& d = *impl_; + if (!d.open) + return false; + d.on_datagram = on_datagram; + + uint8_t record_header[16]; + while (!d.stop) + { + if (!d.readBytes(record_header, sizeof(record_header))) + break; // end of file; a torn final header (capture killed mid-write) ends it too + const uint32_t captured = d.u32(record_header + 8); + if (captured > kMaxRecordBytes) + return d.fail("corrupt pcap record #" + std::to_string(d.stats.records + 1) + ": " + std::to_string(captured) + " bytes"); + d.record.resize(captured); + if (!d.readBytes(d.record.data(), captured)) + break; // torn final record + ++d.stats.records; + d.stats.bytes_read += sizeof(record_header) + captured; + const int64_t seconds = d.u32(record_header); + const int64_t fraction = d.u32(record_header + 4); + const int64_t time_ns = seconds * 1000000000 + (d.nanoseconds ? fraction : fraction * 1000); + d.handleFrame(d.record.data(), d.record.size(), time_ns); + } + for (const auto& [key, datagram] : d.pending) + d.stats.dropped_fragments += datagram.parts.size(); + d.pending.clear(); + if (!d.error.empty()) // a decompression error + return d.fail(d.error); + return true; + } } // namespace rosbags diff --git a/rosbags/PcapUdpReader.h b/rosbags/PcapUdpReader.h index c55bde3c..128596db 100644 --- a/rosbags/PcapUdpReader.h +++ b/rosbags/PcapUdpReader.h @@ -9,60 +9,60 @@ namespace rosbags { -// One UDP datagram out of a capture, reassembled when it arrived in IPv4 -// fragments. `payload` is valid only during the callback that receives it. -struct UdpDatagram -{ - const uint8_t* payload = nullptr; - size_t size = 0; - uint32_t src_ip = 0; // host byte order - uint32_t dst_ip = 0; - uint16_t src_port = 0; - uint16_t dst_port = 0; - int64_t capture_time_ns = 0; // the pcap record time (Unix epoch) of the last fragment -}; + // One UDP datagram out of a capture, reassembled when it arrived in IPv4 + // fragments. `payload` is valid only during the callback that receives it. + struct UdpDatagram + { + const uint8_t* payload = nullptr; + size_t size = 0; + uint32_t src_ip = 0; // host byte order + uint32_t dst_ip = 0; + uint16_t src_port = 0; + uint16_t dst_port = 0; + int64_t capture_time_ns = 0; // the pcap record time (Unix epoch) of the last fragment + }; -struct PcapUdpStats -{ - uint64_t bytes_read = 0; // record headers and payloads consumed so far (uncompressed), for progress - uint64_t compressed_bytes_read = 0; // of the file itself; equals bytes_read + 24 for an uncompressed capture - uint64_t records = 0; - uint64_t non_udp = 0; // not IPv4, not UDP, or too short for a UDP header - uint64_t reassembled_datagrams = 0; - uint64_t dropped_fragments = 0; // IPv4 fragments of a datagram that never completed -}; + struct PcapUdpStats + { + uint64_t bytes_read = 0; // record headers and payloads consumed so far (uncompressed), for progress + uint64_t compressed_bytes_read = 0; // of the file itself; equals bytes_read + 24 for an uncompressed capture + uint64_t records = 0; + uint64_t non_udp = 0; // not IPv4, not UDP, or too short for a UDP header + uint64_t reassembled_datagrams = 0; + uint64_t dropped_fragments = 0; // IPv4 fragments of a datagram that never completed + }; -// Streams the UDP datagrams of a classic libpcap capture (tcpdump, Wireshark -// saved as "pcap", ouster-cli, Hesai's PandarView), optionally zstd-compressed -// as a whole (.pcap.zst, e.g. lidar_recorder chunks). Microsecond and -// nanosecond timestamps, either byte order; Ethernet (with VLAN tags), Linux -// cooked (SLL, SLL2), BSD loopback and raw-IP link types; IPv4 only. -// Fragmented datagrams (a 128-beam lidar packet is far above a 1500-byte MTU) -// are reassembled. pcapng is refused with a conversion hint. -class PcapUdpReader -{ -public: - explicit PcapUdpReader(const std::filesystem::path& path); - ~PcapUdpReader(); + // Streams the UDP datagrams of a classic libpcap capture (tcpdump, Wireshark + // saved as "pcap", ouster-cli, Hesai's PandarView), optionally zstd-compressed + // as a whole (.pcap.zst, e.g. lidar_recorder chunks). Microsecond and + // nanosecond timestamps, either byte order; Ethernet (with VLAN tags), Linux + // cooked (SLL, SLL2), BSD loopback and raw-IP link types; IPv4 only. + // Fragmented datagrams (a 128-beam lidar packet is far above a 1500-byte MTU) + // are reassembled. pcapng is refused with a conversion hint. + class PcapUdpReader + { + public: + explicit PcapUdpReader(const std::filesystem::path& path); + ~PcapUdpReader(); - PcapUdpReader(const PcapUdpReader&) = delete; - PcapUdpReader& operator=(const PcapUdpReader&) = delete; + PcapUdpReader(const PcapUdpReader&) = delete; + PcapUdpReader& operator=(const PcapUdpReader&) = delete; - bool isOpen() const; - const std::string& error() const; + bool isOpen() const; + const std::string& error() const; - // Hands every UDP datagram to `on_datagram`, in file order. A torn final - // record (capture killed mid-write) ends the file quietly. Returns false on - // an I/O, decompression or format error (see error()). - bool read(const std::function& on_datagram); - // Makes read() return after the datagram being handled; callable from the callback. - void requestStop(); + // Hands every UDP datagram to `on_datagram`, in file order. A torn final + // record (capture killed mid-write) ends the file quietly. Returns false on + // an I/O, decompression or format error (see error()). + bool read(const std::function& on_datagram); + // Makes read() return after the datagram being handled; callable from the callback. + void requestStop(); - const PcapUdpStats& stats() const; + const PcapUdpStats& stats() const; -private: - struct Impl; - std::unique_ptr impl_; -}; + private: + struct Impl; + std::unique_ptr impl_; + }; } // namespace rosbags diff --git a/rosbags/Ros1Bag.cpp b/rosbags/Ros1Bag.cpp index 7d400ec5..9ddee217 100644 --- a/rosbags/Ros1Bag.cpp +++ b/rosbags/Ros1Bag.cpp @@ -11,13 +11,13 @@ namespace rosbags { -// --------------------------------------------------------------------------- -// Message definitions as `rosbag record` stores them (sensor_msgs 1.13). -// --------------------------------------------------------------------------- + // --------------------------------------------------------------------------- + // Message definitions as `rosbag record` stores them (sensor_msgs 1.13). + // --------------------------------------------------------------------------- -const char* const kRos1PointCloud2Type = "sensor_msgs/PointCloud2"; -const char* const kRos1PointCloud2Md5 = "1158d486dd51d683ce2f1be655c3c181"; -const char* const kRos1PointCloud2Definition = R"(std_msgs/Header header + const char* const kRos1PointCloud2Type = "sensor_msgs/PointCloud2"; + const char* const kRos1PointCloud2Md5 = "1158d486dd51d683ce2f1be655c3c181"; + const char* const kRos1PointCloud2Definition = R"(std_msgs/Header header uint32 height uint32 width sensor_msgs/PointField[] fields @@ -47,9 +47,9 @@ uint8 datatype uint32 count )"; -const char* const kRos1ImuType = "sensor_msgs/Imu"; -const char* const kRos1ImuMd5 = "6a62c6daae103f4ff57a132d6f95cec2"; -const char* const kRos1ImuDefinition = R"(std_msgs/Header header + const char* const kRos1ImuType = "sensor_msgs/Imu"; + const char* const kRos1ImuMd5 = "6a62c6daae103f4ff57a132d6f95cec2"; + const char* const kRos1ImuDefinition = R"(std_msgs/Header header geometry_msgs/Quaternion orientation float64[9] orientation_covariance geometry_msgs/Vector3 angular_velocity @@ -74,1178 +74,1209 @@ float64 y float64 z )"; -namespace -{ - -constexpr char kMagic[] = "#ROSBAG V2.0\n"; -constexpr size_t kMagicSize = sizeof(kMagic) - 1; -constexpr size_t kBagHeaderRecordSize = 4096; - -constexpr uint8_t kOpMessageData = 0x02; -constexpr uint8_t kOpBagHeader = 0x03; -constexpr uint8_t kOpIndexData = 0x04; -constexpr uint8_t kOpChunk = 0x05; -constexpr uint8_t kOpChunkInfo = 0x06; -constexpr uint8_t kOpConnection = 0x07; - -// Little-endian cursor over a byte buffer; any read past the end clears `ok`. -struct ByteReader -{ - const uint8_t* p; - size_t n; - size_t i = 0; - bool ok = true; - - template - T get() - { - T v{}; - if(i + sizeof(T) > n) - { - ok = false; - return v; - } - std::memcpy(&v, p + i, sizeof(T)); - i += sizeof(T); - return v; - } - - const uint8_t* bytes(size_t k) - { - if(i + k > n) - { - ok = false; - return nullptr; - } - const uint8_t* out = p + i; - i += k; - return out; - } - - std::string str() - { - const uint32_t len = get(); - const uint8_t* b = ok ? bytes(len) : nullptr; - return b ? std::string(reinterpret_cast(b), len) : std::string(); - } -}; - -struct ByteWriter -{ - std::vector& out; - - template - void put(T v) - { - const auto* b = reinterpret_cast(&v); - out.insert(out.end(), b, b + sizeof(T)); - } - - void bytes(const void* data, size_t k) - { - const auto* b = static_cast(data); - out.insert(out.end(), b, b + k); - } - - void str(const std::string& s) - { - put(static_cast(s.size())); - bytes(s.data(), s.size()); - } -}; - -using HeaderFields = std::map; - -bool parseHeaderFields(const uint8_t* p, size_t n, HeaderFields& fields) -{ - ByteReader r{p, n}; - while(r.ok && r.i < n) - { - const std::string field = r.str(); - if(!r.ok) - return false; - const auto eq = field.find('='); - if(eq == std::string::npos) - return false; - fields[field.substr(0, eq)] = field.substr(eq + 1); - } - return r.ok; -} - -template -bool fieldAs(const HeaderFields& fields, const char* name, T& value) -{ - const auto it = fields.find(name); - if(it == fields.end() || it->second.size() != sizeof(T)) - return false; - std::memcpy(&value, it->second.data(), sizeof(T)); - return true; -} - -// ROS time: uint32 sec, uint32 nsec. -uint64_t timeFromField(const std::string& v) -{ - uint32_t sec = 0, nsec = 0; - if(v.size() == 8) - { - std::memcpy(&sec, v.data(), 4); - std::memcpy(&nsec, v.data() + 4, 4); - } - return uint64_t(sec) * 1'000'000'000ULL + nsec; -} - -template -std::string asField(T v) -{ - return std::string(reinterpret_cast(&v), sizeof(T)); -} - -std::string timeField(uint64_t ns) -{ - const uint32_t sec = static_cast(ns / 1'000'000'000ULL); - const uint32_t nsec = static_cast(ns % 1'000'000'000ULL); - return asField(sec) + asField(nsec); -} - -using FieldList = std::vector>; - -std::vector headerBytes(const FieldList& fields) -{ - std::vector out; - ByteWriter w{out}; - for(const auto& [name, value] : fields) - { - w.put(static_cast(name.size() + 1 + value.size())); - w.bytes(name.data(), name.size()); - w.put('='); - w.bytes(value.data(), value.size()); - } - return out; -} - -void appendRecord(std::vector& out, const FieldList& header, const uint8_t* data, size_t size) -{ - const auto h = headerBytes(header); - ByteWriter w{out}; - w.put(static_cast(h.size())); - w.bytes(h.data(), h.size()); - w.put(static_cast(size)); - w.bytes(data, size); -} - -std::vector connectionData(const Ros1Connection& c) -{ - return headerBytes( - {{"topic", c.topic}, {"type", c.type}, {"md5sum", c.md5sum}, {"message_definition", c.message_definition}}); -} - -void appendConnectionRecord(std::vector& out, const Ros1Connection& c) -{ - const auto data = connectionData(c); - appendRecord( - out, {{"op", asField(kOpConnection)}, {"conn", asField(c.id)}, {"topic", c.topic}}, data.data(), data.size()); -} - -bool decompress(const std::string& compression, const std::vector& in, size_t out_size, std::vector& out, std::string& error) -{ - if(compression == "none") - { - // The record data is the chunk; some writers put a wrong "size" in the header - // of an uncompressed chunk (e.g. 1), which rosbag itself ignores too. - out = in; - return true; - } - out.resize(out_size); - if(compression == "bz2") - { - unsigned int dst = static_cast(out_size); - const int rc = BZ2_bzBuffToBuffDecompress( - reinterpret_cast(out.data()), - &dst, - const_cast(reinterpret_cast(in.data())), - static_cast(in.size()), - 0, - 0); - if(rc != BZ_OK || dst != out_size) - { - error = "bz2 chunk decompression failed (code " + std::to_string(rc) + ")"; - return false; - } - return true; - } - if(compression == "lz4") - { - LZ4F_dctx* ctx = nullptr; - if(LZ4F_isError(LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION))) - { - error = "cannot create an LZ4 decompression context"; - return false; - } - size_t src_pos = 0, dst_pos = 0; - size_t rc = 1; - while(rc != 0 && src_pos < in.size() && dst_pos < out_size) - { - size_t src_len = in.size() - src_pos, dst_len = out_size - dst_pos; - rc = LZ4F_decompress(ctx, out.data() + dst_pos, &dst_len, in.data() + src_pos, &src_len, nullptr); - if(LZ4F_isError(rc)) - break; - src_pos += src_len; - dst_pos += dst_len; - } - LZ4F_freeDecompressionContext(ctx); - if(LZ4F_isError(rc) || dst_pos != out_size) - { - error = "lz4 chunk decompression failed"; - return false; - } - return true; - } - error = "unsupported chunk compression '" + compression + "'"; - return false; -} - -// One record read from the file: header fields plus its data. -bool readRecord(std::ifstream& f, HeaderFields& fields, std::vector& data, std::string& error) -{ - uint32_t header_len = 0; - if(!f.read(reinterpret_cast(&header_len), 4)) - return false; // clean end of file - std::vector header(header_len); - uint32_t data_len = 0; - if(!f.read(reinterpret_cast(header.data()), header_len) || !f.read(reinterpret_cast(&data_len), 4)) - { - error = "truncated record header"; - return false; - } - data.resize(data_len); - if(!f.read(reinterpret_cast(data.data()), data_len)) - { - error = "truncated record data"; - return false; - } - fields.clear(); - if(!parseHeaderFields(header.data(), header.size(), fields)) - { - error = "malformed record header"; - return false; - } - return true; -} - -Ros1Connection connectionFromRecord(const HeaderFields& header, const std::vector& data, bool& ok) -{ - Ros1Connection c; - ok = fieldAs(header, "conn", c.id); - HeaderFields info; - ok = ok && parseHeaderFields(data.data(), data.size(), info); - const auto topic = header.find("topic"); - c.topic = topic != header.end() ? topic->second : info["topic"]; - c.type = info["type"]; - c.md5sum = info["md5sum"]; - c.message_definition = info["message_definition"]; - return c; -} - -} // namespace - -// --------------------------------------------------------------------------- -// Ros1BagReader -// --------------------------------------------------------------------------- - -Ros1BagReader::Ros1BagReader(const std::filesystem::path& path) - : file_(path, std::ios::binary) -{ - if(!file_) - { - error_ = "cannot open " + path.string(); - return; - } - char magic[kMagicSize]; - if(!file_.read(magic, kMagicSize) || std::memcmp(magic, kMagic, kMagicSize) != 0) - { - error_ = path.string() + " is not a ROS1 bag (format 2.0)"; - return; - } - HeaderFields header; - std::vector data; - uint8_t op = 0; - if(!readRecord(file_, header, data, error_) || !fieldAs(header, "op", op) || op != kOpBagHeader || - !fieldAs(header, "index_pos", index_pos_)) - { - if(error_.empty()) - error_ = "missing bag header record"; - return; - } - readIndex(); -} - -bool Ros1BagReader::isOpen() const -{ - return error_.empty(); -} - -const std::string& Ros1BagReader::error() const -{ - return error_; -} - -const std::map& Ros1BagReader::connections() const -{ - return connections_; -} - -bool Ros1BagReader::readIndex() -{ - if(index_pos_ == 0) - return true; // unindexed (still recording or not reindexed): connections come from the chunks - const auto resume = file_.tellg(); - file_.seekg(static_cast(index_pos_)); - HeaderFields header; - std::vector data; - std::string err; - std::map message_counts; - while(readRecord(file_, header, data, err)) - { - uint8_t op = 0; - if(!fieldAs(header, "op", op)) - continue; - if(op == kOpConnection) - { - bool ok = false; - const auto c = connectionFromRecord(header, data, ok); - if(ok) - connections_[c.id] = c; - } - else if(op == kOpChunkInfo) - { - ByteReader r{data.data(), data.size()}; - while(r.i < data.size()) - { - const uint32_t conn = r.get(); - const uint32_t count = r.get(); - if(!r.ok) - break; - message_counts[conn] += count; - } - IndexedChunk chunk; - const auto start = header.find("start_time"); - const auto end = header.find("end_time"); - if(fieldAs(header, "chunk_pos", chunk.pos) && start != header.end() && end != header.end()) - { - chunk.start_ns = timeFromField(start->second); - chunk.end_ns = timeFromField(end->second); - chunks_.push_back(chunk); - } - } - } - std::sort(chunks_.begin(), chunks_.end(), [](const IndexedChunk& a, const IndexedChunk& b) { return a.pos < b.pos; }); - for(const auto& [conn, count] : message_counts) - { - const auto it = connections_.find(conn); - if(it != connections_.end()) - it->second.message_count = count; - } - file_.clear(); - file_.seekg(resume); - return err.empty(); -} - -bool Ros1BagReader::parseRecords(const uint8_t* data, size_t size, const MessageFn& fn, bool& stop) -{ - ByteReader r{data, size}; - while(r.i < size) - { - const uint32_t header_len = r.get(); - const uint8_t* header = r.bytes(header_len); - const uint32_t data_len = r.get(); - const uint8_t* body = r.bytes(data_len); - HeaderFields fields; - uint8_t op = 0; - if(!r.ok || !parseHeaderFields(header, header_len, fields) || !fieldAs(fields, "op", op)) - { - error_ = "malformed record inside a chunk"; - return false; - } - if(op == kOpConnection) - { - bool ok = false; - const auto c = connectionFromRecord(fields, std::vector(body, body + data_len), ok); - if(!ok) - { - error_ = "malformed connection record"; - return false; - } - connections_.try_emplace(c.id, c); - } - else if(op == kOpMessageData) - { - uint32_t conn = 0; - const auto time = fields.find("time"); - if(!fieldAs(fields, "conn", conn) || time == fields.end()) - { - error_ = "malformed message record"; - return false; - } - const auto it = connections_.find(conn); - if(it == connections_.end()) - { - error_ = "message on unknown connection " + std::to_string(conn); - return false; - } - if(!fn(it->second, timeFromField(time->second), body, data_len)) - { - stop = true; - return true; - } - } - } - return true; -} - -std::string Ros1BagReader::chunkCompression() -{ - if(!isOpen() || chunks_.empty()) - return {}; - file_.clear(); - file_.seekg(static_cast(chunks_.front().pos)); - HeaderFields header; - std::vector data; - std::string error; - if(!readRecord(file_, header, data, error)) - return {}; - const auto compression = header.find("compression"); - return compression == header.end() ? std::string{} : compression->second; -} - -std::optional Ros1BagReader::recordTimeSpan() const -{ - if(chunks_.empty()) - return std::nullopt; - LogTimeRange span{std::numeric_limits::max(), 0}; - for(const auto& chunk : chunks_) - { - span.start_ns = std::min(span.start_ns, chunk.start_ns); - span.end_ns = std::max(span.end_ns, chunk.end_ns + 1); - } - return span; -} - -bool Ros1BagReader::forEachMessage(const MessageFn& fn) -{ - if(!isOpen()) - return false; - return scanAll(fn); -} - -bool Ros1BagReader::forEachMessage(const MessageFn& fn, const LogTimeRange& range) -{ - if(!isOpen()) - return false; - const MessageFn inRange = [&](const Ros1Connection& c, uint64_t time_ns, const uint8_t* data, size_t size) - { - return time_ns < range.start_ns || time_ns >= range.end_ns || fn(c, time_ns, data, size); - }; - if(chunks_.empty()) - return scanAll(inRange); - - HeaderFields header; - std::vector data, chunk; - bool stop = false; - for(const auto& indexed : chunks_) - { - if(indexed.end_ns < range.start_ns || indexed.start_ns >= range.end_ns) - continue; - file_.clear(); - file_.seekg(static_cast(indexed.pos)); - if(!readRecord(file_, header, data, error_)) - { - if(error_.empty()) - error_ = "cannot read the chunk at offset " + std::to_string(indexed.pos); - return false; - } - uint8_t op = 0; - uint32_t size = 0; - const auto compression = header.find("compression"); - if(!fieldAs(header, "op", op) || op != kOpChunk || compression == header.end() || !fieldAs(header, "size", size)) - { - error_ = "malformed chunk record at offset " + std::to_string(indexed.pos); - return false; - } - if(!decompress(compression->second, data, size, chunk, error_)) - return false; - if(!parseRecords(chunk.data(), chunk.size(), inRange, stop)) - return false; - if(stop) - break; - } - return true; -} - -bool Ros1BagReader::scanAll(const MessageFn& fn) -{ - file_.clear(); - file_.seekg(static_cast(kMagicSize)); - HeaderFields header; - std::vector data, chunk; - if(!readRecord(file_, header, data, error_)) - return false; // bag header record - - bool stop = false; - while(!stop) - { - const auto pos = static_cast(file_.tellg()); - if(index_pos_ != 0 && pos >= index_pos_) - break; - if(!readRecord(file_, header, data, error_)) - return error_.empty(); - uint8_t op = 0; - fieldAs(header, "op", op); - if(op == kOpChunk) - { - uint32_t size = 0; - const auto compression = header.find("compression"); - if(compression == header.end() || !fieldAs(header, "size", size)) - { - error_ = "malformed chunk record"; - return false; - } - if(!decompress(compression->second, data, size, chunk, error_)) - return false; - if(!parseRecords(chunk.data(), chunk.size(), fn, stop)) - return false; - } - else if(op == kOpConnection || op == kOpMessageData) - { - // Records outside chunks: rebuild the record and reuse the chunk parser. - std::vector record; - FieldList list(header.begin(), header.end()); - appendRecord(record, list, data.data(), data.size()); - if(!parseRecords(record.data(), record.size(), fn, stop)) - return false; - } - // Index data and chunk info records carry nothing a sequential reader needs. - } - return true; -} - -// --------------------------------------------------------------------------- -// Ros1BagWriter -// --------------------------------------------------------------------------- - -namespace -{ - -std::vector bagHeaderRecord(uint64_t index_pos, uint32_t conn_count, uint32_t chunk_count) -{ - const FieldList header = { - {"op", asField(kOpBagHeader)}, - {"index_pos", asField(index_pos)}, - {"conn_count", asField(conn_count)}, - {"chunk_count", asField(chunk_count)}}; - const size_t header_len = headerBytes(header).size(); - // The bag header record is padded to 4096 bytes so it can be rewritten in place. - const std::vector padding(kBagHeaderRecordSize - 8 - header_len, ' '); - std::vector out; - appendRecord(out, header, padding.data(), padding.size()); - return out; -} - -} // namespace - -Ros1BagWriter::Ros1BagWriter(const std::filesystem::path& path, size_t chunk_threshold) - : file_(path, std::ios::binary | std::ios::trunc) - , chunk_threshold_(chunk_threshold) -{ - if(!file_) - { - error_ = "cannot create " + path.string(); - return; - } - file_.write(kMagic, kMagicSize); - const auto header = bagHeaderRecord(0, 0, 0); - file_.write(reinterpret_cast(header.data()), header.size()); -} - -Ros1BagWriter::~Ros1BagWriter() -{ - close(); -} - -bool Ros1BagWriter::isOpen() const -{ - return error_.empty() && file_.good(); -} - -const std::string& Ros1BagWriter::error() const -{ - return error_; -} - -uint32_t Ros1BagWriter::addConnection( - const std::string& topic, const std::string& type, const std::string& md5sum, const std::string& message_definition) -{ - const auto id = static_cast(connections_.size()); - connections_.push_back({id, topic, type, md5sum, message_definition}); - return id; -} - -void Ros1BagWriter::write(uint32_t connection, uint64_t time_ns, const std::vector& data) -{ - if(closed_ || connection >= connections_.size()) - return; - if(chunk_.empty()) - { - chunk_start_ns_ = time_ns; - chunk_end_ns_ = time_ns; - } - chunk_start_ns_ = std::min(chunk_start_ns_, time_ns); - chunk_end_ns_ = std::max(chunk_end_ns_, time_ns); - // A chunk must carry the connection record of every connection it uses. - if(chunk_connections_.insert(connection).second) - appendConnectionRecord(chunk_, connections_[connection]); - const auto offset = static_cast(chunk_.size()); - appendRecord( - chunk_, - {{"op", asField(kOpMessageData)}, {"conn", asField(connection)}, {"time", timeField(time_ns)}}, - data.data(), - data.size()); - chunk_index_[connection].push_back({time_ns, offset}); - if(chunk_.size() >= chunk_threshold_) - flushChunk(); -} - -void Ros1BagWriter::flushChunk() -{ - if(chunk_.empty()) - return; - ChunkInfo info{static_cast(file_.tellp()), chunk_start_ns_, chunk_end_ns_, {}}; - std::vector out; - appendRecord( - out, - {{"op", asField(kOpChunk)}, {"compression", "none"}, {"size", asField(static_cast(chunk_.size()))}}, - chunk_.data(), - chunk_.size()); - for(const auto& [conn, entries] : chunk_index_) - { - std::vector index; - ByteWriter w{index}; - for(const auto& e : entries) - { - const auto t = timeField(e.time_ns); - w.bytes(t.data(), t.size()); - w.put(e.offset); - } - appendRecord( - out, - {{"op", asField(kOpIndexData)}, - {"ver", asField(uint32_t{1})}, - {"conn", asField(conn)}, - {"count", asField(static_cast(entries.size()))}}, - index.data(), - index.size()); - info.counts[conn] = static_cast(entries.size()); - } - file_.write(reinterpret_cast(out.data()), out.size()); - chunk_infos_.push_back(std::move(info)); - chunk_.clear(); - chunk_connections_.clear(); - chunk_index_.clear(); -} - -bool Ros1BagWriter::close() -{ - if(closed_) - return isOpen(); - closed_ = true; - if(!file_.is_open()) - return false; - flushChunk(); - const auto index_pos = static_cast(file_.tellp()); - std::vector out; - for(const auto& c : connections_) - appendConnectionRecord(out, c); - for(const auto& info : chunk_infos_) - { - std::vector data; - ByteWriter w{data}; - for(const auto& [conn, count] : info.counts) - { - w.put(conn); - w.put(count); - } - appendRecord( - out, - {{"op", asField(kOpChunkInfo)}, - {"ver", asField(uint32_t{1})}, - {"chunk_pos", asField(info.pos)}, - {"start_time", timeField(info.start_ns)}, - {"end_time", timeField(info.end_ns)}, - {"count", asField(static_cast(info.counts.size()))}}, - data.data(), - data.size()); - } - file_.write(reinterpret_cast(out.data()), out.size()); - const auto header = bagHeaderRecord( - index_pos, static_cast(connections_.size()), static_cast(chunk_infos_.size())); - file_.seekp(static_cast(kMagicSize)); - file_.write(reinterpret_cast(header.data()), header.size()); - file_.close(); - if(file_.fail() && error_.empty()) - error_ = "write failed"; - return error_.empty(); -} - -// --------------------------------------------------------------------------- -// sensor_msgs -// --------------------------------------------------------------------------- - -namespace -{ - -void readHeader(ByteReader& r, uint32_t& seq, uint64_t& stamp_ns, std::string& frame_id) -{ - seq = r.get(); - const uint32_t sec = r.get(); - const uint32_t nsec = r.get(); - stamp_ns = uint64_t(sec) * 1'000'000'000ULL + nsec; - frame_id = r.str(); -} - -void writeHeader(ByteWriter& w, uint32_t seq, uint64_t stamp_ns, const std::string& frame_id) -{ - w.put(seq); - w.put(static_cast(stamp_ns / 1'000'000'000ULL)); - w.put(static_cast(stamp_ns % 1'000'000'000ULL)); - w.str(frame_id); -} - -} // namespace - -bool decodeRos1PointCloud2(const uint8_t* data, size_t size, Ros1PointCloud2& msg) -{ - ByteReader r{data, size}; - readHeader(r, msg.seq, msg.stamp_ns, msg.frame_id); - msg.height = r.get(); - msg.width = r.get(); - const uint32_t n_fields = r.get(); - msg.fields.clear(); - for(uint32_t i = 0; i < n_fields && r.ok; ++i) - { - Ros1PointField f; - f.name = r.str(); - f.offset = r.get(); - f.datatype = r.get(); - f.count = r.get(); - msg.fields.push_back(f); - } - msg.is_bigendian = r.get() != 0; - msg.point_step = r.get(); - msg.row_step = r.get(); - const uint32_t n_data = r.get(); - const uint8_t* bytes = r.ok ? r.bytes(n_data) : nullptr; - if(bytes) - msg.data.assign(bytes, bytes + n_data); - msg.is_dense = r.get() != 0; - return r.ok; -} - -std::vector encodeRos1PointCloud2(const Ros1PointCloud2& msg) -{ - std::vector out; - out.reserve(msg.data.size() + 256); - ByteWriter w{out}; - writeHeader(w, msg.seq, msg.stamp_ns, msg.frame_id); - w.put(msg.height); - w.put(msg.width); - w.put(static_cast(msg.fields.size())); - for(const auto& f : msg.fields) - { - w.str(f.name); - w.put(f.offset); - w.put(f.datatype); - w.put(f.count); - } - w.put(msg.is_bigendian ? 1 : 0); - w.put(msg.point_step); - w.put(msg.row_step); - w.put(static_cast(msg.data.size())); - w.bytes(msg.data.data(), msg.data.size()); - w.put(msg.is_dense ? 1 : 0); - return out; -} - -bool decodeRos1Imu(const uint8_t* data, size_t size, Ros1Imu& msg) -{ - ByteReader r{data, size}; - readHeader(r, msg.seq, msg.stamp_ns, msg.frame_id); - for(double& v : msg.orientation) - v = r.get(); - for(double& v : msg.orientation_covariance) - v = r.get(); - for(double& v : msg.angular_velocity) - v = r.get(); - for(double& v : msg.angular_velocity_covariance) - v = r.get(); - for(double& v : msg.linear_acceleration) - v = r.get(); - for(double& v : msg.linear_acceleration_covariance) - v = r.get(); - return r.ok; -} - -std::vector encodeRos1Imu(const Ros1Imu& msg) -{ - std::vector out; - ByteWriter w{out}; - writeHeader(w, msg.seq, msg.stamp_ns, msg.frame_id); - for(double v : msg.orientation) - w.put(v); - for(double v : msg.orientation_covariance) - w.put(v); - for(double v : msg.angular_velocity) - w.put(v); - for(double v : msg.angular_velocity_covariance) - w.put(v); - for(double v : msg.linear_acceleration) - w.put(v); - for(double v : msg.linear_acceleration_covariance) - w.put(v); - return out; -} - -// --------------------------------------------------------------------------- -// Ros1BagFileReader -// --------------------------------------------------------------------------- - -namespace -{ - -const char* const kRos1StringType = "std_msgs/String"; -const char* const kRos1StringMd5 = "992ce8a1687cec8c8bd883ec73ca41d1"; -const char* const kRos1StringDefinition = "string data\n"; - -// "sensor_msgs/PointCloud2" -> "PointCloud2", as McapReader compares schema names. -std::string_view typeName(std::string_view type) -{ - const auto slash = type.rfind('/'); - return slash == std::string_view::npos ? type : type.substr(slash + 1); -} - -// livox_ros_driver/CustomMsg, the same mapping as decodeLivoxCustomMsg(): ring = -// line, laser_id = tag, intensity = reflectivity, time = timebase + offset_time. -std::vector decodeRos1LivoxCustomMsg(const uint8_t* data, size_t size, std::string* warning) -{ - ByteReader r{data, size}; - uint32_t seq = 0; - uint64_t stamp_ns = 0; - std::string frame_id; - readHeader(r, seq, stamp_ns, frame_id); - const uint64_t timebase = r.get(); - r.get(); // point_num - r.get(); // lidar_id - r.bytes(3); // rsvd - const uint32_t n = r.get(); - std::vector points; - if(!r.ok) - { - if(warning && warning->empty()) - *warning = "truncated CustomMsg header"; - return points; - } - points.reserve(n); - const double timebase_s = static_cast(timebase) * 1e-9; - for(uint32_t i = 0; i < n; ++i) - { - const uint32_t offset_time = r.get(); - McapPoint p{}; - p.x = r.get(); - p.y = r.get(); - p.z = r.get(); - p.intensity = static_cast(r.get()); - p.laser_id = r.get(); - p.ring = r.get(); - if(!r.ok) - { - if(warning && warning->empty()) - *warning = "truncated CustomMsg point data at index " + std::to_string(i); - break; - } - p.timestamp = timebase_s + static_cast(offset_time) * 1e-9; - points.push_back(p); - } - return points; -} - -} // namespace - -Ros1BagFileReader::Ros1BagFileReader(const std::filesystem::path& path, const McapReaderOptions& options) - : reader_(path) - , options_(options) -{ - if(!reader_.isOpen()) - { - error_ = reader_.error(); - return; - } - for(const auto& [id, c] : reader_.connections()) - { - // One topic can be recorded through several connections (publishers). - const auto channel = std::find_if(channels_.begin(), channels_.end(), [&](const ChannelInfo& ch) { return ch.topic == c.topic; }); - if(channel == channels_.end()) - channels_.push_back({c.topic, c.type, "ros1", c.message_count}); - else - channel->message_count += c.message_count; - } - if(channels_.empty()) - { - error_ = "the bag has no index section (still recording or not reindexed: run `rosbag reindex`)"; - return; - } - std::sort(channels_.begin(), channels_.end(), [](const ChannelInfo& a, const ChannelInfo& b) { return a.topic < b.topic; }); - - // Same rules as McapFileReader: a requested topic must exist; otherwise the - // single channel of a matching type is used, and ambiguity is an error for the - // streams that must be unique. - const auto resolve = [&](const std::string& requested, std::initializer_list types, bool required_unique, std::string& out) - { - if(!requested.empty()) - { - if(std::none_of(channels_.begin(), channels_.end(), [&](const ChannelInfo& c) { return c.topic == requested; })) - { - error_ = "topic '" + requested + "' is not present in the bag"; - return false; - } - out = requested; - return true; - } - std::vector candidates; - for(const auto& c : channels_) - if(std::find(types.begin(), types.end(), typeName(c.schema_name)) != types.end()) - candidates.push_back(&c); - if(candidates.empty()) - return true; - if(candidates.size() > 1) - { - if(!required_unique) - return true; - error_ = "found " + std::to_string(candidates.size()) + " candidate topics ("; - for(size_t i = 0; i < candidates.size(); ++i) - error_ += (i ? ", " : "") + candidates[i]->topic; - error_ += ") - pick one explicitly"; - return false; - } - out = candidates.front()->topic; - return true; - }; - if(!resolve(options.lidar_topic, {"PointCloud2", "CustomMsg"}, true, topics_.lidar) || - !resolve(options.imu_topic, {"Imu"}, true, topics_.imu) || !resolve(options.sn_topic, {"String"}, false, topics_.sn)) - return; - - if(!topics_.lidar.empty()) - { - const auto it = std::find_if(channels_.begin(), channels_.end(), [&](const ChannelInfo& c) { return c.topic == topics_.lidar; }); - const auto type = typeName(it->schema_name); - if(type == "PointCloud2") - topics_.lidar_schema = LidarSchema::PointCloud2; - else if(type == "CustomMsg") - topics_.lidar_schema = LidarSchema::LivoxCustomMsg; - else - { - error_ = "topic '" + topics_.lidar + "' carries " + it->schema_name + ", not a point cloud"; - return; - } - } - open_ = true; -} - -bool Ros1BagFileReader::isOpen() const -{ - return open_; -} - -const std::string& Ros1BagFileReader::error() const -{ - return error_; -} - -const ResolvedTopics& Ros1BagFileReader::topics() const -{ - return topics_; -} - -const std::vector& Ros1BagFileReader::channels() const -{ - return channels_; -} - -bool Ros1BagFileReader::timeOrdered() const -{ - return true; -} - -const std::string& Ros1BagFileReader::lidarLayoutWarning() const -{ - return warning_; -} - -std::optional Ros1BagFileReader::logTimeSpan() const -{ - return reader_.recordTimeSpan(); -} - -std::string Ros1BagFileReader::compression() -{ - return reader_.chunkCompression(); -} - -bool Ros1BagFileReader::read(const Callbacks& callbacks, const LogTimeRange& range) -{ - if(!open_) - return false; - Ros1PointCloud2 cloud; - Ros1Imu imu; - const bool ok = reader_.forEachMessage( - [&](const Ros1Connection& c, uint64_t time_ns, const uint8_t* data, size_t size) - { - if(callbacks.onProgress) - callbacks.onProgress(time_ns); - if(c.topic == topics_.lidar && callbacks.onPointCloud) - { - std::vector points; - if(topics_.lidar_schema == LidarSchema::LivoxCustomMsg) - { - points = decodeRos1LivoxCustomMsg(data, size, &warning_); - } - else if(!decodeRos1PointCloud2(data, size, cloud)) - { - if(warning_.empty()) - warning_ = "truncated PointCloud2 message"; - } - else if(cloud.is_bigendian) - { - if(warning_.empty()) - warning_ = "PointCloud2 is big-endian, which is not supported"; - } - else - { - Pc2Layout msg; - for(const auto& f : cloud.fields) - addPc2Field(msg, f.name, f.offset, static_cast(f.datatype), f.count); - msg.point_step = cloud.point_step; - points = decodePc2Points( - msg, - static_cast(cloud.fields.size()), - static_cast(cloud.stamp_ns) * 1e-9, - cloud.data.data(), - cloud.data.size(), - options_.lidar_preset, - &warning_); - } - if(!points.empty()) - callbacks.onPointCloud(time_ns, std::move(points)); - } - else if(c.topic == topics_.imu && callbacks.onImu) - { - if(decodeRos1Imu(data, size, imu)) - { - McapImuSample s; - s.timestamp = static_cast(imu.stamp_ns) * 1e-9; - s.gyro_x = static_cast(imu.angular_velocity[0]); - s.gyro_y = static_cast(imu.angular_velocity[1]); - s.gyro_z = static_cast(imu.angular_velocity[2]); - s.acc_x = static_cast(imu.linear_acceleration[0]); - s.acc_y = static_cast(imu.linear_acceleration[1]); - s.acc_z = static_cast(imu.linear_acceleration[2]); - callbacks.onImu(s); - } - } - else if(c.topic == topics_.sn && callbacks.onSn) - { - ByteReader r{data, size}; - const std::string sn = r.str(); - if(r.ok) - callbacks.onSn(time_ns, sn); - } - return true; - }, - range); - if(!ok) - error_ = reader_.error(); - return ok; -} - -// --------------------------------------------------------------------------- -// Ros1BagFileWriter -// --------------------------------------------------------------------------- - -Ros1BagFileWriter::Ros1BagFileWriter(const std::filesystem::path& path, const McapWriterOptions& options) - : bag_(path) - , options_(options) -{ - lidar_ = bag_.addConnection(options_.lidar_topic, kRos1PointCloud2Type, kRos1PointCloud2Md5, kRos1PointCloud2Definition); - imu_ = bag_.addConnection(options_.imu_topic, kRos1ImuType, kRos1ImuMd5, kRos1ImuDefinition); -} - -bool Ros1BagFileWriter::isOpen() const -{ - return bag_.isOpen(); -} - -const std::string& Ros1BagFileWriter::error() const -{ - return bag_.error(); -} - -void Ros1BagFileWriter::writePointCloud(uint64_t timestamp_ns, const std::vector& points) -{ - Ros1PointCloud2 msg; - msg.seq = lidar_seq_++; - msg.stamp_ns = timestamp_ns; - msg.frame_id = options_.pointcloud_frame_id.empty() ? options_.frame_id : options_.pointcloud_frame_id; - msg.width = static_cast(points.size()); - for(const auto& f : pointCloudFields(options_.lidar_layout)) - msg.fields.push_back({f.name, f.offset, f.datatype, 1}); - msg.point_step = pointCloudPointStep(options_.lidar_layout); - msg.row_step = msg.width * msg.point_step; - msg.data = packPointCloud(points, options_.lidar_layout); - bag_.write(lidar_, timestamp_ns, encodeRos1PointCloud2(msg)); -} - -void Ros1BagFileWriter::writeImuSample(const McapImuSample& sample) -{ - Ros1Imu msg; - msg.seq = imu_seq_++; - msg.stamp_ns = static_cast(sample.timestamp * 1e9); - msg.frame_id = options_.frame_id; - msg.angular_velocity[0] = sample.gyro_x; - msg.angular_velocity[1] = sample.gyro_y; - msg.angular_velocity[2] = sample.gyro_z; - msg.linear_acceleration[0] = sample.acc_x; - msg.linear_acceleration[1] = sample.acc_y; - msg.linear_acceleration[2] = sample.acc_z; - bag_.write(imu_, msg.stamp_ns, encodeRos1Imu(msg)); -} - -void Ros1BagFileWriter::writeImu(const std::vector& imu) -{ - for(const auto& s : imu) - writeImuSample(s); -} - -void Ros1BagFileWriter::writeSn(uint64_t timestamp_ns, const std::string& data) -{ - // Added on first use, so a bag without a serial number has no empty topic. - if(!sn_) - sn_ = bag_.addConnection(options_.sn_topic, kRos1StringType, kRos1StringMd5, kRos1StringDefinition); - std::vector out; - ByteWriter w{out}; - w.str(data); - bag_.write(*sn_, timestamp_ns, out); -} - -bool Ros1BagFileWriter::close() -{ - return bag_.close(); -} + namespace + { + + constexpr char kMagic[] = "#ROSBAG V2.0\n"; + constexpr size_t kMagicSize = sizeof(kMagic) - 1; + constexpr size_t kBagHeaderRecordSize = 4096; + + constexpr uint8_t kOpMessageData = 0x02; + constexpr uint8_t kOpBagHeader = 0x03; + constexpr uint8_t kOpIndexData = 0x04; + constexpr uint8_t kOpChunk = 0x05; + constexpr uint8_t kOpChunkInfo = 0x06; + constexpr uint8_t kOpConnection = 0x07; + + // Little-endian cursor over a byte buffer; any read past the end clears `ok`. + struct ByteReader + { + const uint8_t* p; + size_t n; + size_t i = 0; + bool ok = true; + + template + T get() + { + T v{}; + if (i + sizeof(T) > n) + { + ok = false; + return v; + } + std::memcpy(&v, p + i, sizeof(T)); + i += sizeof(T); + return v; + } + + const uint8_t* bytes(size_t k) + { + if (i + k > n) + { + ok = false; + return nullptr; + } + const uint8_t* out = p + i; + i += k; + return out; + } + + std::string str() + { + const uint32_t len = get(); + const uint8_t* b = ok ? bytes(len) : nullptr; + return b ? std::string(reinterpret_cast(b), len) : std::string(); + } + }; + + struct ByteWriter + { + std::vector& out; + + template + void put(T v) + { + const auto* b = reinterpret_cast(&v); + out.insert(out.end(), b, b + sizeof(T)); + } + + void bytes(const void* data, size_t k) + { + const auto* b = static_cast(data); + out.insert(out.end(), b, b + k); + } + + void str(const std::string& s) + { + put(static_cast(s.size())); + bytes(s.data(), s.size()); + } + }; + + using HeaderFields = std::map; + + bool parseHeaderFields(const uint8_t* p, size_t n, HeaderFields& fields) + { + ByteReader r{ p, n }; + while (r.ok && r.i < n) + { + const std::string field = r.str(); + if (!r.ok) + return false; + const auto eq = field.find('='); + if (eq == std::string::npos) + return false; + fields[field.substr(0, eq)] = field.substr(eq + 1); + } + return r.ok; + } + + template + bool fieldAs(const HeaderFields& fields, const char* name, T& value) + { + const auto it = fields.find(name); + if (it == fields.end() || it->second.size() != sizeof(T)) + return false; + std::memcpy(&value, it->second.data(), sizeof(T)); + return true; + } + + // ROS time: uint32 sec, uint32 nsec. + uint64_t timeFromField(const std::string& v) + { + uint32_t sec = 0, nsec = 0; + if (v.size() == 8) + { + std::memcpy(&sec, v.data(), 4); + std::memcpy(&nsec, v.data() + 4, 4); + } + return uint64_t(sec) * 1'000'000'000ULL + nsec; + } + + template + std::string asField(T v) + { + return std::string(reinterpret_cast(&v), sizeof(T)); + } + + std::string timeField(uint64_t ns) + { + const uint32_t sec = static_cast(ns / 1'000'000'000ULL); + const uint32_t nsec = static_cast(ns % 1'000'000'000ULL); + return asField(sec) + asField(nsec); + } + + using FieldList = std::vector>; + + std::vector headerBytes(const FieldList& fields) + { + std::vector out; + ByteWriter w{ out }; + for (const auto& [name, value] : fields) + { + w.put(static_cast(name.size() + 1 + value.size())); + w.bytes(name.data(), name.size()); + w.put('='); + w.bytes(value.data(), value.size()); + } + return out; + } + + void appendRecord(std::vector& out, const FieldList& header, const uint8_t* data, size_t size) + { + const auto h = headerBytes(header); + ByteWriter w{ out }; + w.put(static_cast(h.size())); + w.bytes(h.data(), h.size()); + w.put(static_cast(size)); + w.bytes(data, size); + } + + std::vector connectionData(const Ros1Connection& c) + { + return headerBytes( + { { "topic", c.topic }, { "type", c.type }, { "md5sum", c.md5sum }, { "message_definition", c.message_definition } }); + } + + void appendConnectionRecord(std::vector& out, const Ros1Connection& c) + { + const auto data = connectionData(c); + appendRecord( + out, { { "op", asField(kOpConnection) }, { "conn", asField(c.id) }, { "topic", c.topic } }, data.data(), data.size()); + } + + bool decompress( + const std::string& compression, const std::vector& in, size_t out_size, std::vector& out, std::string& error) + { + if (compression == "none") + { + // The record data is the chunk; some writers put a wrong "size" in the header + // of an uncompressed chunk (e.g. 1), which rosbag itself ignores too. + out = in; + return true; + } + out.resize(out_size); + if (compression == "bz2") + { + unsigned int dst = static_cast(out_size); + const int rc = BZ2_bzBuffToBuffDecompress( + reinterpret_cast(out.data()), + &dst, + const_cast(reinterpret_cast(in.data())), + static_cast(in.size()), + 0, + 0); + if (rc != BZ_OK || dst != out_size) + { + error = "bz2 chunk decompression failed (code " + std::to_string(rc) + ")"; + return false; + } + return true; + } + if (compression == "lz4") + { + LZ4F_dctx* ctx = nullptr; + if (LZ4F_isError(LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION))) + { + error = "cannot create an LZ4 decompression context"; + return false; + } + size_t src_pos = 0, dst_pos = 0; + size_t rc = 1; + while (rc != 0 && src_pos < in.size() && dst_pos < out_size) + { + size_t src_len = in.size() - src_pos, dst_len = out_size - dst_pos; + rc = LZ4F_decompress(ctx, out.data() + dst_pos, &dst_len, in.data() + src_pos, &src_len, nullptr); + if (LZ4F_isError(rc)) + break; + src_pos += src_len; + dst_pos += dst_len; + } + LZ4F_freeDecompressionContext(ctx); + if (LZ4F_isError(rc) || dst_pos != out_size) + { + error = "lz4 chunk decompression failed"; + return false; + } + return true; + } + error = "unsupported chunk compression '" + compression + "'"; + return false; + } + + // One record read from the file: header fields plus its data. + bool readRecord(std::ifstream& f, HeaderFields& fields, std::vector& data, std::string& error) + { + uint32_t header_len = 0; + if (!f.read(reinterpret_cast(&header_len), 4)) + return false; // clean end of file + std::vector header(header_len); + uint32_t data_len = 0; + if (!f.read(reinterpret_cast(header.data()), header_len) || !f.read(reinterpret_cast(&data_len), 4)) + { + error = "truncated record header"; + return false; + } + data.resize(data_len); + if (!f.read(reinterpret_cast(data.data()), data_len)) + { + error = "truncated record data"; + return false; + } + fields.clear(); + if (!parseHeaderFields(header.data(), header.size(), fields)) + { + error = "malformed record header"; + return false; + } + return true; + } + + Ros1Connection connectionFromRecord(const HeaderFields& header, const std::vector& data, bool& ok) + { + Ros1Connection c; + ok = fieldAs(header, "conn", c.id); + HeaderFields info; + ok = ok && parseHeaderFields(data.data(), data.size(), info); + const auto topic = header.find("topic"); + c.topic = topic != header.end() ? topic->second : info["topic"]; + c.type = info["type"]; + c.md5sum = info["md5sum"]; + c.message_definition = info["message_definition"]; + return c; + } + + } // namespace + + // --------------------------------------------------------------------------- + // Ros1BagReader + // --------------------------------------------------------------------------- + + Ros1BagReader::Ros1BagReader(const std::filesystem::path& path) + : file_(path, std::ios::binary) + { + if (!file_) + { + error_ = "cannot open " + path.string(); + return; + } + char magic[kMagicSize]; + if (!file_.read(magic, kMagicSize) || std::memcmp(magic, kMagic, kMagicSize) != 0) + { + error_ = path.string() + " is not a ROS1 bag (format 2.0)"; + return; + } + HeaderFields header; + std::vector data; + uint8_t op = 0; + if (!readRecord(file_, header, data, error_) || !fieldAs(header, "op", op) || op != kOpBagHeader || + !fieldAs(header, "index_pos", index_pos_)) + { + if (error_.empty()) + error_ = "missing bag header record"; + return; + } + readIndex(); + } + + bool Ros1BagReader::isOpen() const + { + return error_.empty(); + } + + const std::string& Ros1BagReader::error() const + { + return error_; + } + + const std::map& Ros1BagReader::connections() const + { + return connections_; + } + + bool Ros1BagReader::readIndex() + { + if (index_pos_ == 0) + return true; // unindexed (still recording or not reindexed): connections come from the chunks + const auto resume = file_.tellg(); + file_.seekg(static_cast(index_pos_)); + HeaderFields header; + std::vector data; + std::string err; + std::map message_counts; + while (readRecord(file_, header, data, err)) + { + uint8_t op = 0; + if (!fieldAs(header, "op", op)) + continue; + if (op == kOpConnection) + { + bool ok = false; + const auto c = connectionFromRecord(header, data, ok); + if (ok) + connections_[c.id] = c; + } + else if (op == kOpChunkInfo) + { + ByteReader r{ data.data(), data.size() }; + while (r.i < data.size()) + { + const uint32_t conn = r.get(); + const uint32_t count = r.get(); + if (!r.ok) + break; + message_counts[conn] += count; + } + IndexedChunk chunk; + const auto start = header.find("start_time"); + const auto end = header.find("end_time"); + if (fieldAs(header, "chunk_pos", chunk.pos) && start != header.end() && end != header.end()) + { + chunk.start_ns = timeFromField(start->second); + chunk.end_ns = timeFromField(end->second); + chunks_.push_back(chunk); + } + } + } + std::sort( + chunks_.begin(), + chunks_.end(), + [](const IndexedChunk& a, const IndexedChunk& b) + { + return a.pos < b.pos; + }); + for (const auto& [conn, count] : message_counts) + { + const auto it = connections_.find(conn); + if (it != connections_.end()) + it->second.message_count = count; + } + file_.clear(); + file_.seekg(resume); + return err.empty(); + } + + bool Ros1BagReader::parseRecords(const uint8_t* data, size_t size, const MessageFn& fn, bool& stop) + { + ByteReader r{ data, size }; + while (r.i < size) + { + const uint32_t header_len = r.get(); + const uint8_t* header = r.bytes(header_len); + const uint32_t data_len = r.get(); + const uint8_t* body = r.bytes(data_len); + HeaderFields fields; + uint8_t op = 0; + if (!r.ok || !parseHeaderFields(header, header_len, fields) || !fieldAs(fields, "op", op)) + { + error_ = "malformed record inside a chunk"; + return false; + } + if (op == kOpConnection) + { + bool ok = false; + const auto c = connectionFromRecord(fields, std::vector(body, body + data_len), ok); + if (!ok) + { + error_ = "malformed connection record"; + return false; + } + connections_.try_emplace(c.id, c); + } + else if (op == kOpMessageData) + { + uint32_t conn = 0; + const auto time = fields.find("time"); + if (!fieldAs(fields, "conn", conn) || time == fields.end()) + { + error_ = "malformed message record"; + return false; + } + const auto it = connections_.find(conn); + if (it == connections_.end()) + { + error_ = "message on unknown connection " + std::to_string(conn); + return false; + } + if (!fn(it->second, timeFromField(time->second), body, data_len)) + { + stop = true; + return true; + } + } + } + return true; + } + + std::string Ros1BagReader::chunkCompression() + { + if (!isOpen() || chunks_.empty()) + return {}; + file_.clear(); + file_.seekg(static_cast(chunks_.front().pos)); + HeaderFields header; + std::vector data; + std::string error; + if (!readRecord(file_, header, data, error)) + return {}; + const auto compression = header.find("compression"); + return compression == header.end() ? std::string{} : compression->second; + } + + std::optional Ros1BagReader::recordTimeSpan() const + { + if (chunks_.empty()) + return std::nullopt; + LogTimeRange span{ std::numeric_limits::max(), 0 }; + for (const auto& chunk : chunks_) + { + span.start_ns = std::min(span.start_ns, chunk.start_ns); + span.end_ns = std::max(span.end_ns, chunk.end_ns + 1); + } + return span; + } + + bool Ros1BagReader::forEachMessage(const MessageFn& fn) + { + if (!isOpen()) + return false; + return scanAll(fn); + } + + bool Ros1BagReader::forEachMessage(const MessageFn& fn, const LogTimeRange& range) + { + if (!isOpen()) + return false; + const MessageFn inRange = [&](const Ros1Connection& c, uint64_t time_ns, const uint8_t* data, size_t size) + { + return time_ns < range.start_ns || time_ns >= range.end_ns || fn(c, time_ns, data, size); + }; + if (chunks_.empty()) + return scanAll(inRange); + + HeaderFields header; + std::vector data, chunk; + bool stop = false; + for (const auto& indexed : chunks_) + { + if (indexed.end_ns < range.start_ns || indexed.start_ns >= range.end_ns) + continue; + file_.clear(); + file_.seekg(static_cast(indexed.pos)); + if (!readRecord(file_, header, data, error_)) + { + if (error_.empty()) + error_ = "cannot read the chunk at offset " + std::to_string(indexed.pos); + return false; + } + uint8_t op = 0; + uint32_t size = 0; + const auto compression = header.find("compression"); + if (!fieldAs(header, "op", op) || op != kOpChunk || compression == header.end() || !fieldAs(header, "size", size)) + { + error_ = "malformed chunk record at offset " + std::to_string(indexed.pos); + return false; + } + if (!decompress(compression->second, data, size, chunk, error_)) + return false; + if (!parseRecords(chunk.data(), chunk.size(), inRange, stop)) + return false; + if (stop) + break; + } + return true; + } + + bool Ros1BagReader::scanAll(const MessageFn& fn) + { + file_.clear(); + file_.seekg(static_cast(kMagicSize)); + HeaderFields header; + std::vector data, chunk; + if (!readRecord(file_, header, data, error_)) + return false; // bag header record + + bool stop = false; + while (!stop) + { + const auto pos = static_cast(file_.tellg()); + if (index_pos_ != 0 && pos >= index_pos_) + break; + if (!readRecord(file_, header, data, error_)) + return error_.empty(); + uint8_t op = 0; + fieldAs(header, "op", op); + if (op == kOpChunk) + { + uint32_t size = 0; + const auto compression = header.find("compression"); + if (compression == header.end() || !fieldAs(header, "size", size)) + { + error_ = "malformed chunk record"; + return false; + } + if (!decompress(compression->second, data, size, chunk, error_)) + return false; + if (!parseRecords(chunk.data(), chunk.size(), fn, stop)) + return false; + } + else if (op == kOpConnection || op == kOpMessageData) + { + // Records outside chunks: rebuild the record and reuse the chunk parser. + std::vector record; + FieldList list(header.begin(), header.end()); + appendRecord(record, list, data.data(), data.size()); + if (!parseRecords(record.data(), record.size(), fn, stop)) + return false; + } + // Index data and chunk info records carry nothing a sequential reader needs. + } + return true; + } + + // --------------------------------------------------------------------------- + // Ros1BagWriter + // --------------------------------------------------------------------------- + + namespace + { + + std::vector bagHeaderRecord(uint64_t index_pos, uint32_t conn_count, uint32_t chunk_count) + { + const FieldList header = { { "op", asField(kOpBagHeader) }, + { "index_pos", asField(index_pos) }, + { "conn_count", asField(conn_count) }, + { "chunk_count", asField(chunk_count) } }; + const size_t header_len = headerBytes(header).size(); + // The bag header record is padded to 4096 bytes so it can be rewritten in place. + const std::vector padding(kBagHeaderRecordSize - 8 - header_len, ' '); + std::vector out; + appendRecord(out, header, padding.data(), padding.size()); + return out; + } + + } // namespace + + Ros1BagWriter::Ros1BagWriter(const std::filesystem::path& path, size_t chunk_threshold) + : file_(path, std::ios::binary | std::ios::trunc) + , chunk_threshold_(chunk_threshold) + { + if (!file_) + { + error_ = "cannot create " + path.string(); + return; + } + file_.write(kMagic, kMagicSize); + const auto header = bagHeaderRecord(0, 0, 0); + file_.write(reinterpret_cast(header.data()), header.size()); + } + + Ros1BagWriter::~Ros1BagWriter() + { + close(); + } + + bool Ros1BagWriter::isOpen() const + { + return error_.empty() && file_.good(); + } + + const std::string& Ros1BagWriter::error() const + { + return error_; + } + + uint32_t Ros1BagWriter::addConnection( + const std::string& topic, const std::string& type, const std::string& md5sum, const std::string& message_definition) + { + const auto id = static_cast(connections_.size()); + connections_.push_back({ id, topic, type, md5sum, message_definition }); + return id; + } + + void Ros1BagWriter::write(uint32_t connection, uint64_t time_ns, const std::vector& data) + { + if (closed_ || connection >= connections_.size()) + return; + if (chunk_.empty()) + { + chunk_start_ns_ = time_ns; + chunk_end_ns_ = time_ns; + } + chunk_start_ns_ = std::min(chunk_start_ns_, time_ns); + chunk_end_ns_ = std::max(chunk_end_ns_, time_ns); + // A chunk must carry the connection record of every connection it uses. + if (chunk_connections_.insert(connection).second) + appendConnectionRecord(chunk_, connections_[connection]); + const auto offset = static_cast(chunk_.size()); + appendRecord( + chunk_, + { { "op", asField(kOpMessageData) }, { "conn", asField(connection) }, { "time", timeField(time_ns) } }, + data.data(), + data.size()); + chunk_index_[connection].push_back({ time_ns, offset }); + if (chunk_.size() >= chunk_threshold_) + flushChunk(); + } + + void Ros1BagWriter::flushChunk() + { + if (chunk_.empty()) + return; + ChunkInfo info{ static_cast(file_.tellp()), chunk_start_ns_, chunk_end_ns_, {} }; + std::vector out; + appendRecord( + out, + { { "op", asField(kOpChunk) }, { "compression", "none" }, { "size", asField(static_cast(chunk_.size())) } }, + chunk_.data(), + chunk_.size()); + for (const auto& [conn, entries] : chunk_index_) + { + std::vector index; + ByteWriter w{ index }; + for (const auto& e : entries) + { + const auto t = timeField(e.time_ns); + w.bytes(t.data(), t.size()); + w.put(e.offset); + } + appendRecord( + out, + { { "op", asField(kOpIndexData) }, + { "ver", asField(uint32_t{ 1 }) }, + { "conn", asField(conn) }, + { "count", asField(static_cast(entries.size())) } }, + index.data(), + index.size()); + info.counts[conn] = static_cast(entries.size()); + } + file_.write(reinterpret_cast(out.data()), out.size()); + chunk_infos_.push_back(std::move(info)); + chunk_.clear(); + chunk_connections_.clear(); + chunk_index_.clear(); + } + + bool Ros1BagWriter::close() + { + if (closed_) + return isOpen(); + closed_ = true; + if (!file_.is_open()) + return false; + flushChunk(); + const auto index_pos = static_cast(file_.tellp()); + std::vector out; + for (const auto& c : connections_) + appendConnectionRecord(out, c); + for (const auto& info : chunk_infos_) + { + std::vector data; + ByteWriter w{ data }; + for (const auto& [conn, count] : info.counts) + { + w.put(conn); + w.put(count); + } + appendRecord( + out, + { { "op", asField(kOpChunkInfo) }, + { "ver", asField(uint32_t{ 1 }) }, + { "chunk_pos", asField(info.pos) }, + { "start_time", timeField(info.start_ns) }, + { "end_time", timeField(info.end_ns) }, + { "count", asField(static_cast(info.counts.size())) } }, + data.data(), + data.size()); + } + file_.write(reinterpret_cast(out.data()), out.size()); + const auto header = + bagHeaderRecord(index_pos, static_cast(connections_.size()), static_cast(chunk_infos_.size())); + file_.seekp(static_cast(kMagicSize)); + file_.write(reinterpret_cast(header.data()), header.size()); + file_.close(); + if (file_.fail() && error_.empty()) + error_ = "write failed"; + return error_.empty(); + } + + // --------------------------------------------------------------------------- + // sensor_msgs + // --------------------------------------------------------------------------- + + namespace + { + + void readHeader(ByteReader& r, uint32_t& seq, uint64_t& stamp_ns, std::string& frame_id) + { + seq = r.get(); + const uint32_t sec = r.get(); + const uint32_t nsec = r.get(); + stamp_ns = uint64_t(sec) * 1'000'000'000ULL + nsec; + frame_id = r.str(); + } + + void writeHeader(ByteWriter& w, uint32_t seq, uint64_t stamp_ns, const std::string& frame_id) + { + w.put(seq); + w.put(static_cast(stamp_ns / 1'000'000'000ULL)); + w.put(static_cast(stamp_ns % 1'000'000'000ULL)); + w.str(frame_id); + } + + } // namespace + + bool decodeRos1PointCloud2(const uint8_t* data, size_t size, Ros1PointCloud2& msg) + { + ByteReader r{ data, size }; + readHeader(r, msg.seq, msg.stamp_ns, msg.frame_id); + msg.height = r.get(); + msg.width = r.get(); + const uint32_t n_fields = r.get(); + msg.fields.clear(); + for (uint32_t i = 0; i < n_fields && r.ok; ++i) + { + Ros1PointField f; + f.name = r.str(); + f.offset = r.get(); + f.datatype = r.get(); + f.count = r.get(); + msg.fields.push_back(f); + } + msg.is_bigendian = r.get() != 0; + msg.point_step = r.get(); + msg.row_step = r.get(); + const uint32_t n_data = r.get(); + const uint8_t* bytes = r.ok ? r.bytes(n_data) : nullptr; + if (bytes) + msg.data.assign(bytes, bytes + n_data); + msg.is_dense = r.get() != 0; + return r.ok; + } + + std::vector encodeRos1PointCloud2(const Ros1PointCloud2& msg) + { + std::vector out; + out.reserve(msg.data.size() + 256); + ByteWriter w{ out }; + writeHeader(w, msg.seq, msg.stamp_ns, msg.frame_id); + w.put(msg.height); + w.put(msg.width); + w.put(static_cast(msg.fields.size())); + for (const auto& f : msg.fields) + { + w.str(f.name); + w.put(f.offset); + w.put(f.datatype); + w.put(f.count); + } + w.put(msg.is_bigendian ? 1 : 0); + w.put(msg.point_step); + w.put(msg.row_step); + w.put(static_cast(msg.data.size())); + w.bytes(msg.data.data(), msg.data.size()); + w.put(msg.is_dense ? 1 : 0); + return out; + } + + bool decodeRos1Imu(const uint8_t* data, size_t size, Ros1Imu& msg) + { + ByteReader r{ data, size }; + readHeader(r, msg.seq, msg.stamp_ns, msg.frame_id); + for (double& v : msg.orientation) + v = r.get(); + for (double& v : msg.orientation_covariance) + v = r.get(); + for (double& v : msg.angular_velocity) + v = r.get(); + for (double& v : msg.angular_velocity_covariance) + v = r.get(); + for (double& v : msg.linear_acceleration) + v = r.get(); + for (double& v : msg.linear_acceleration_covariance) + v = r.get(); + return r.ok; + } + + std::vector encodeRos1Imu(const Ros1Imu& msg) + { + std::vector out; + ByteWriter w{ out }; + writeHeader(w, msg.seq, msg.stamp_ns, msg.frame_id); + for (double v : msg.orientation) + w.put(v); + for (double v : msg.orientation_covariance) + w.put(v); + for (double v : msg.angular_velocity) + w.put(v); + for (double v : msg.angular_velocity_covariance) + w.put(v); + for (double v : msg.linear_acceleration) + w.put(v); + for (double v : msg.linear_acceleration_covariance) + w.put(v); + return out; + } + + // --------------------------------------------------------------------------- + // Ros1BagFileReader + // --------------------------------------------------------------------------- + + namespace + { + + const char* const kRos1StringType = "std_msgs/String"; + const char* const kRos1StringMd5 = "992ce8a1687cec8c8bd883ec73ca41d1"; + const char* const kRos1StringDefinition = "string data\n"; + + // "sensor_msgs/PointCloud2" -> "PointCloud2", as McapReader compares schema names. + std::string_view typeName(std::string_view type) + { + const auto slash = type.rfind('/'); + return slash == std::string_view::npos ? type : type.substr(slash + 1); + } + + // livox_ros_driver/CustomMsg, the same mapping as decodeLivoxCustomMsg(): ring = + // line, laser_id = tag, intensity = reflectivity, time = timebase + offset_time. + std::vector decodeRos1LivoxCustomMsg(const uint8_t* data, size_t size, std::string* warning) + { + ByteReader r{ data, size }; + uint32_t seq = 0; + uint64_t stamp_ns = 0; + std::string frame_id; + readHeader(r, seq, stamp_ns, frame_id); + const uint64_t timebase = r.get(); + r.get(); // point_num + r.get(); // lidar_id + r.bytes(3); // rsvd + const uint32_t n = r.get(); + std::vector points; + if (!r.ok) + { + if (warning && warning->empty()) + *warning = "truncated CustomMsg header"; + return points; + } + points.reserve(n); + const double timebase_s = static_cast(timebase) * 1e-9; + for (uint32_t i = 0; i < n; ++i) + { + const uint32_t offset_time = r.get(); + McapPoint p{}; + p.x = r.get(); + p.y = r.get(); + p.z = r.get(); + p.intensity = static_cast(r.get()); + p.laser_id = r.get(); + p.ring = r.get(); + if (!r.ok) + { + if (warning && warning->empty()) + *warning = "truncated CustomMsg point data at index " + std::to_string(i); + break; + } + p.timestamp = timebase_s + static_cast(offset_time) * 1e-9; + points.push_back(p); + } + return points; + } + + } // namespace + + Ros1BagFileReader::Ros1BagFileReader(const std::filesystem::path& path, const McapReaderOptions& options) + : reader_(path) + , options_(options) + { + if (!reader_.isOpen()) + { + error_ = reader_.error(); + return; + } + for (const auto& [id, c] : reader_.connections()) + { + // One topic can be recorded through several connections (publishers). + const auto channel = std::find_if( + channels_.begin(), + channels_.end(), + [&](const ChannelInfo& ch) + { + return ch.topic == c.topic; + }); + if (channel == channels_.end()) + channels_.push_back({ c.topic, c.type, "ros1", c.message_count }); + else + channel->message_count += c.message_count; + } + if (channels_.empty()) + { + error_ = "the bag has no index section (still recording or not reindexed: run `rosbag reindex`)"; + return; + } + std::sort( + channels_.begin(), + channels_.end(), + [](const ChannelInfo& a, const ChannelInfo& b) + { + return a.topic < b.topic; + }); + + // Same rules as McapFileReader: a requested topic must exist; otherwise the + // single channel of a matching type is used, and ambiguity is an error for the + // streams that must be unique. + const auto resolve = + [&](const std::string& requested, std::initializer_list types, bool required_unique, std::string& out) + { + if (!requested.empty()) + { + if (std::none_of( + channels_.begin(), + channels_.end(), + [&](const ChannelInfo& c) + { + return c.topic == requested; + })) + { + error_ = "topic '" + requested + "' is not present in the bag"; + return false; + } + out = requested; + return true; + } + std::vector candidates; + for (const auto& c : channels_) + if (std::find(types.begin(), types.end(), typeName(c.schema_name)) != types.end()) + candidates.push_back(&c); + if (candidates.empty()) + return true; + if (candidates.size() > 1) + { + if (!required_unique) + return true; + error_ = "found " + std::to_string(candidates.size()) + " candidate topics ("; + for (size_t i = 0; i < candidates.size(); ++i) + error_ += (i ? ", " : "") + candidates[i]->topic; + error_ += ") - pick one explicitly"; + return false; + } + out = candidates.front()->topic; + return true; + }; + if (!resolve(options.lidar_topic, { "PointCloud2", "CustomMsg" }, true, topics_.lidar) || + !resolve(options.imu_topic, { "Imu" }, true, topics_.imu) || !resolve(options.sn_topic, { "String" }, false, topics_.sn)) + return; + + if (!topics_.lidar.empty()) + { + const auto it = std::find_if( + channels_.begin(), + channels_.end(), + [&](const ChannelInfo& c) + { + return c.topic == topics_.lidar; + }); + const auto type = typeName(it->schema_name); + if (type == "PointCloud2") + topics_.lidar_schema = LidarSchema::PointCloud2; + else if (type == "CustomMsg") + topics_.lidar_schema = LidarSchema::LivoxCustomMsg; + else + { + error_ = "topic '" + topics_.lidar + "' carries " + it->schema_name + ", not a point cloud"; + return; + } + } + open_ = true; + } + + bool Ros1BagFileReader::isOpen() const + { + return open_; + } + + const std::string& Ros1BagFileReader::error() const + { + return error_; + } + + const ResolvedTopics& Ros1BagFileReader::topics() const + { + return topics_; + } + + const std::vector& Ros1BagFileReader::channels() const + { + return channels_; + } + + bool Ros1BagFileReader::timeOrdered() const + { + return true; + } + + const std::string& Ros1BagFileReader::lidarLayoutWarning() const + { + return warning_; + } + + std::optional Ros1BagFileReader::logTimeSpan() const + { + return reader_.recordTimeSpan(); + } + + std::string Ros1BagFileReader::compression() + { + return reader_.chunkCompression(); + } + + bool Ros1BagFileReader::read(const Callbacks& callbacks, const LogTimeRange& range) + { + if (!open_) + return false; + Ros1PointCloud2 cloud; + Ros1Imu imu; + const bool ok = reader_.forEachMessage( + [&](const Ros1Connection& c, uint64_t time_ns, const uint8_t* data, size_t size) + { + if (callbacks.onProgress) + callbacks.onProgress(time_ns); + if (c.topic == topics_.lidar && callbacks.onPointCloud) + { + std::vector points; + if (topics_.lidar_schema == LidarSchema::LivoxCustomMsg) + { + points = decodeRos1LivoxCustomMsg(data, size, &warning_); + } + else if (!decodeRos1PointCloud2(data, size, cloud)) + { + if (warning_.empty()) + warning_ = "truncated PointCloud2 message"; + } + else if (cloud.is_bigendian) + { + if (warning_.empty()) + warning_ = "PointCloud2 is big-endian, which is not supported"; + } + else + { + Pc2Layout msg; + for (const auto& f : cloud.fields) + addPc2Field(msg, f.name, f.offset, static_cast(f.datatype), f.count); + msg.point_step = cloud.point_step; + points = decodePc2Points( + msg, + static_cast(cloud.fields.size()), + static_cast(cloud.stamp_ns) * 1e-9, + cloud.data.data(), + cloud.data.size(), + options_.lidar_preset, + &warning_); + } + if (!points.empty()) + callbacks.onPointCloud(time_ns, std::move(points)); + } + else if (c.topic == topics_.imu && callbacks.onImu) + { + if (decodeRos1Imu(data, size, imu)) + { + McapImuSample s; + s.timestamp = static_cast(imu.stamp_ns) * 1e-9; + s.gyro_x = static_cast(imu.angular_velocity[0]); + s.gyro_y = static_cast(imu.angular_velocity[1]); + s.gyro_z = static_cast(imu.angular_velocity[2]); + s.acc_x = static_cast(imu.linear_acceleration[0]); + s.acc_y = static_cast(imu.linear_acceleration[1]); + s.acc_z = static_cast(imu.linear_acceleration[2]); + callbacks.onImu(s); + } + } + else if (c.topic == topics_.sn && callbacks.onSn) + { + ByteReader r{ data, size }; + const std::string sn = r.str(); + if (r.ok) + callbacks.onSn(time_ns, sn); + } + return true; + }, + range); + if (!ok) + error_ = reader_.error(); + return ok; + } + + // --------------------------------------------------------------------------- + // Ros1BagFileWriter + // --------------------------------------------------------------------------- + + Ros1BagFileWriter::Ros1BagFileWriter(const std::filesystem::path& path, const McapWriterOptions& options) + : bag_(path) + , options_(options) + { + lidar_ = bag_.addConnection(options_.lidar_topic, kRos1PointCloud2Type, kRos1PointCloud2Md5, kRos1PointCloud2Definition); + imu_ = bag_.addConnection(options_.imu_topic, kRos1ImuType, kRos1ImuMd5, kRos1ImuDefinition); + } + + bool Ros1BagFileWriter::isOpen() const + { + return bag_.isOpen(); + } + + const std::string& Ros1BagFileWriter::error() const + { + return bag_.error(); + } + + void Ros1BagFileWriter::writePointCloud(uint64_t timestamp_ns, const std::vector& points) + { + Ros1PointCloud2 msg; + msg.seq = lidar_seq_++; + msg.stamp_ns = timestamp_ns; + msg.frame_id = options_.pointcloud_frame_id.empty() ? options_.frame_id : options_.pointcloud_frame_id; + msg.width = static_cast(points.size()); + for (const auto& f : pointCloudFields(options_.lidar_layout)) + msg.fields.push_back({ f.name, f.offset, f.datatype, 1 }); + msg.point_step = pointCloudPointStep(options_.lidar_layout); + msg.row_step = msg.width * msg.point_step; + msg.data = packPointCloud(points, options_.lidar_layout); + bag_.write(lidar_, timestamp_ns, encodeRos1PointCloud2(msg)); + } + + void Ros1BagFileWriter::writeImuSample(const McapImuSample& sample) + { + Ros1Imu msg; + msg.seq = imu_seq_++; + msg.stamp_ns = static_cast(sample.timestamp * 1e9); + msg.frame_id = options_.frame_id; + msg.angular_velocity[0] = sample.gyro_x; + msg.angular_velocity[1] = sample.gyro_y; + msg.angular_velocity[2] = sample.gyro_z; + msg.linear_acceleration[0] = sample.acc_x; + msg.linear_acceleration[1] = sample.acc_y; + msg.linear_acceleration[2] = sample.acc_z; + bag_.write(imu_, msg.stamp_ns, encodeRos1Imu(msg)); + } + + void Ros1BagFileWriter::writeImu(const std::vector& imu) + { + for (const auto& s : imu) + writeImuSample(s); + } + + void Ros1BagFileWriter::writeSn(uint64_t timestamp_ns, const std::string& data) + { + // Added on first use, so a bag without a serial number has no empty topic. + if (!sn_) + sn_ = bag_.addConnection(options_.sn_topic, kRos1StringType, kRos1StringMd5, kRos1StringDefinition); + std::vector out; + ByteWriter w{ out }; + w.str(data); + bag_.write(*sn_, timestamp_ns, out); + } + + bool Ros1BagFileWriter::close() + { + return bag_.close(); + } } // namespace rosbags diff --git a/rosbags/Ros1Bag.h b/rosbags/Ros1Bag.h index 1b3fa791..8972ebb2 100644 --- a/rosbags/Ros1Bag.h +++ b/rosbags/Ros1Bag.h @@ -28,235 +28,235 @@ namespace rosbags { -struct Ros1Connection -{ - uint32_t id{}; - std::string topic; - std::string type; // e.g. sensor_msgs/PointCloud2 - std::string md5sum; - std::string message_definition; - uint64_t message_count{}; // from the chunk info records of the index section; 0 for an unindexed bag -}; - -class Ros1BagReader -{ -public: - explicit Ros1BagReader(const std::filesystem::path& path); - - bool isOpen() const; - const std::string& error() const; - - // Connections listed in the bag's index section (empty for an unindexed bag - // until forEachMessage() has seen them inside the chunks). - const std::map& connections() const; - - // Calls fn for every message in file order. fn returns false to stop early. - // Returns false on a read or decompression error (see error()). - using MessageFn = std::function; - bool forEachMessage(const MessageFn& fn); - // As above, for the messages whose record time lies in `range`. An indexed bag - // reads only the chunks that overlap it; an unindexed one is scanned whole. - bool forEachMessage(const MessageFn& fn, const LogTimeRange& range); - - // Record times covered by the chunks in the index section; nullopt for an - // unindexed bag. - std::optional recordTimeSpan() const; - - // Compression of the first chunk ("none", "bz2" or "lz4"), as rosbag writes - // one for the whole bag; empty for an unindexed bag or a read error. - std::string chunkCompression(); - -private: - struct IndexedChunk - { - uint64_t pos{}; - uint64_t start_ns{}; - uint64_t end_ns{}; // inclusive, as in the chunk info record - }; - - bool readIndex(); - bool parseRecords(const uint8_t* data, size_t size, const MessageFn& fn, bool& stop); - bool scanAll(const MessageFn& fn); - - std::ifstream file_; - std::string error_; - uint64_t index_pos_{}; - std::map connections_; - std::vector chunks_; // from the index section, ordered by file position -}; - -class Ros1BagWriter -{ -public: - explicit Ros1BagWriter(const std::filesystem::path& path, size_t chunk_threshold = 768 * 1024); - ~Ros1BagWriter(); - - Ros1BagWriter(const Ros1BagWriter&) = delete; - Ros1BagWriter& operator=(const Ros1BagWriter&) = delete; - - bool isOpen() const; - const std::string& error() const; - - // Returns the connection id to pass to write(). - uint32_t addConnection( - const std::string& topic, const std::string& type, const std::string& md5sum, const std::string& message_definition); - - // Writes one ROS1-serialized message; time_ns is the bag record time. - void write(uint32_t connection, uint64_t time_ns, const std::vector& data); - - // Writes the last chunk and the index section. Called by the destructor too. - bool close(); - -private: - struct IndexEntry - { - uint64_t time_ns; - uint32_t offset; - }; - struct ChunkInfo - { - uint64_t pos; - uint64_t start_ns; - uint64_t end_ns; - std::map counts; - }; - - void flushChunk(); - - std::ofstream file_; - std::string error_; - size_t chunk_threshold_; - bool closed_{false}; - std::vector connections_; - std::vector chunk_; - std::set chunk_connections_; - std::map> chunk_index_; - uint64_t chunk_start_ns_{}; - uint64_t chunk_end_ns_{}; - std::vector chunk_infos_; -}; - -// --------------------------------------------------------------------------- -// sensor_msgs in ROS1 serialization -// --------------------------------------------------------------------------- - -struct Ros1PointField -{ - std::string name; - uint32_t offset{}; - uint8_t datatype{}; // 1 INT8, 2 UINT8, 3 INT16, 4 UINT16, 5 INT32, 6 UINT32, 7 FLOAT32, 8 FLOAT64 - uint32_t count{1}; -}; - -struct Ros1PointCloud2 -{ - uint32_t seq{}; - uint64_t stamp_ns{}; - std::string frame_id; - uint32_t height{1}; - uint32_t width{}; - std::vector fields; - bool is_bigendian{false}; - uint32_t point_step{}; - uint32_t row_step{}; - std::vector data; - bool is_dense{true}; -}; - -struct Ros1Imu -{ - uint32_t seq{}; - uint64_t stamp_ns{}; - std::string frame_id; - double orientation[4]{0.0, 0.0, 0.0, 1.0}; // x, y, z, w - double orientation_covariance[9]{-1.0}; // [0] = -1: orientation unknown - double angular_velocity[3]{}; - double angular_velocity_covariance[9]{}; - double linear_acceleration[3]{}; - double linear_acceleration_covariance[9]{}; -}; - -extern const char* const kRos1PointCloud2Type; -extern const char* const kRos1PointCloud2Md5; -extern const char* const kRos1PointCloud2Definition; -extern const char* const kRos1ImuType; -extern const char* const kRos1ImuMd5; -extern const char* const kRos1ImuDefinition; - -bool decodeRos1PointCloud2(const uint8_t* data, size_t size, Ros1PointCloud2& msg); -std::vector encodeRos1PointCloud2(const Ros1PointCloud2& msg); -bool decodeRos1Imu(const uint8_t* data, size_t size, Ros1Imu& msg); -std::vector encodeRos1Imu(const Ros1Imu& msg); - -// --------------------------------------------------------------------------- -// McapFileReader / McapFileWriter counterparts -// --------------------------------------------------------------------------- - -// Reads a ROS1 bag into McapPoint/McapImuSample, like McapFileReader does for -// MCAP: topics are auto-detected or forced the same way (sensor_msgs/PointCloud2 -// or livox_ros_driver CustomMsg for the lidar, sensor_msgs/Imu, std_msgs/String), -// and PointCloud2 records go through the same decodePc2Points() as MCAP ones. -class Ros1BagFileReader -{ -public: - using Callbacks = McapFileReader::Callbacks; - - explicit Ros1BagFileReader(const std::filesystem::path& path, const McapReaderOptions& options = {}); - - bool isOpen() const; - const std::string& error() const; - const ResolvedTopics& topics() const; - const std::vector& channels() const; - // `rosbag record` writes messages in the order it received them, so a bag is - // read in ascending record time. - bool timeOrdered() const; - const std::string& lidarLayoutWarning() const; - - // Streams the messages whose record time lies in `range` (by default the whole - // bag) through `callbacks`; `log_time_ns` is the bag record time. Returns false - // on a read error (see error()). - bool read(const Callbacks& callbacks, const LogTimeRange& range = {}); - - // Record times covered by the bag's chunks; nullopt for an unindexed bag. - std::optional logTimeSpan() const; - - // Chunk compression of the bag ("none", "bz2", "lz4"); empty when unknown. - std::string compression(); - -private: - Ros1BagReader reader_; - McapReaderOptions options_; - ResolvedTopics topics_; - std::vector channels_; - std::string error_; - std::string warning_; - bool open_{false}; -}; - -// Writes McapPoint/McapImuSample to a ROS1 bag, like McapFileWriter does for -// MCAP: same topics, frame ids and PointCloud2 layouts (pointCloudFields()). -class Ros1BagFileWriter -{ -public: - explicit Ros1BagFileWriter(const std::filesystem::path& path, const McapWriterOptions& options = {}); - - bool isOpen() const; - const std::string& error() const; - - void writePointCloud(uint64_t timestamp_ns, const std::vector& points); - void writeImuSample(const McapImuSample& imu); - void writeImu(const std::vector& imu); - void writeSn(uint64_t timestamp_ns, const std::string& data); - - // Finishes the bag's index; the destructor calls it too. - bool close(); - -private: - Ros1BagWriter bag_; - McapWriterOptions options_; - uint32_t lidar_{}, imu_{}; - std::optional sn_; - uint32_t lidar_seq_{}, imu_seq_{}; -}; + struct Ros1Connection + { + uint32_t id{}; + std::string topic; + std::string type; // e.g. sensor_msgs/PointCloud2 + std::string md5sum; + std::string message_definition; + uint64_t message_count{}; // from the chunk info records of the index section; 0 for an unindexed bag + }; + + class Ros1BagReader + { + public: + explicit Ros1BagReader(const std::filesystem::path& path); + + bool isOpen() const; + const std::string& error() const; + + // Connections listed in the bag's index section (empty for an unindexed bag + // until forEachMessage() has seen them inside the chunks). + const std::map& connections() const; + + // Calls fn for every message in file order. fn returns false to stop early. + // Returns false on a read or decompression error (see error()). + using MessageFn = std::function; + bool forEachMessage(const MessageFn& fn); + // As above, for the messages whose record time lies in `range`. An indexed bag + // reads only the chunks that overlap it; an unindexed one is scanned whole. + bool forEachMessage(const MessageFn& fn, const LogTimeRange& range); + + // Record times covered by the chunks in the index section; nullopt for an + // unindexed bag. + std::optional recordTimeSpan() const; + + // Compression of the first chunk ("none", "bz2" or "lz4"), as rosbag writes + // one for the whole bag; empty for an unindexed bag or a read error. + std::string chunkCompression(); + + private: + struct IndexedChunk + { + uint64_t pos{}; + uint64_t start_ns{}; + uint64_t end_ns{}; // inclusive, as in the chunk info record + }; + + bool readIndex(); + bool parseRecords(const uint8_t* data, size_t size, const MessageFn& fn, bool& stop); + bool scanAll(const MessageFn& fn); + + std::ifstream file_; + std::string error_; + uint64_t index_pos_{}; + std::map connections_; + std::vector chunks_; // from the index section, ordered by file position + }; + + class Ros1BagWriter + { + public: + explicit Ros1BagWriter(const std::filesystem::path& path, size_t chunk_threshold = 768 * 1024); + ~Ros1BagWriter(); + + Ros1BagWriter(const Ros1BagWriter&) = delete; + Ros1BagWriter& operator=(const Ros1BagWriter&) = delete; + + bool isOpen() const; + const std::string& error() const; + + // Returns the connection id to pass to write(). + uint32_t addConnection( + const std::string& topic, const std::string& type, const std::string& md5sum, const std::string& message_definition); + + // Writes one ROS1-serialized message; time_ns is the bag record time. + void write(uint32_t connection, uint64_t time_ns, const std::vector& data); + + // Writes the last chunk and the index section. Called by the destructor too. + bool close(); + + private: + struct IndexEntry + { + uint64_t time_ns; + uint32_t offset; + }; + struct ChunkInfo + { + uint64_t pos; + uint64_t start_ns; + uint64_t end_ns; + std::map counts; + }; + + void flushChunk(); + + std::ofstream file_; + std::string error_; + size_t chunk_threshold_; + bool closed_{ false }; + std::vector connections_; + std::vector chunk_; + std::set chunk_connections_; + std::map> chunk_index_; + uint64_t chunk_start_ns_{}; + uint64_t chunk_end_ns_{}; + std::vector chunk_infos_; + }; + + // --------------------------------------------------------------------------- + // sensor_msgs in ROS1 serialization + // --------------------------------------------------------------------------- + + struct Ros1PointField + { + std::string name; + uint32_t offset{}; + uint8_t datatype{}; // 1 INT8, 2 UINT8, 3 INT16, 4 UINT16, 5 INT32, 6 UINT32, 7 FLOAT32, 8 FLOAT64 + uint32_t count{ 1 }; + }; + + struct Ros1PointCloud2 + { + uint32_t seq{}; + uint64_t stamp_ns{}; + std::string frame_id; + uint32_t height{ 1 }; + uint32_t width{}; + std::vector fields; + bool is_bigendian{ false }; + uint32_t point_step{}; + uint32_t row_step{}; + std::vector data; + bool is_dense{ true }; + }; + + struct Ros1Imu + { + uint32_t seq{}; + uint64_t stamp_ns{}; + std::string frame_id; + double orientation[4]{ 0.0, 0.0, 0.0, 1.0 }; // x, y, z, w + double orientation_covariance[9]{ -1.0 }; // [0] = -1: orientation unknown + double angular_velocity[3]{}; + double angular_velocity_covariance[9]{}; + double linear_acceleration[3]{}; + double linear_acceleration_covariance[9]{}; + }; + + extern const char* const kRos1PointCloud2Type; + extern const char* const kRos1PointCloud2Md5; + extern const char* const kRos1PointCloud2Definition; + extern const char* const kRos1ImuType; + extern const char* const kRos1ImuMd5; + extern const char* const kRos1ImuDefinition; + + bool decodeRos1PointCloud2(const uint8_t* data, size_t size, Ros1PointCloud2& msg); + std::vector encodeRos1PointCloud2(const Ros1PointCloud2& msg); + bool decodeRos1Imu(const uint8_t* data, size_t size, Ros1Imu& msg); + std::vector encodeRos1Imu(const Ros1Imu& msg); + + // --------------------------------------------------------------------------- + // McapFileReader / McapFileWriter counterparts + // --------------------------------------------------------------------------- + + // Reads a ROS1 bag into McapPoint/McapImuSample, like McapFileReader does for + // MCAP: topics are auto-detected or forced the same way (sensor_msgs/PointCloud2 + // or livox_ros_driver CustomMsg for the lidar, sensor_msgs/Imu, std_msgs/String), + // and PointCloud2 records go through the same decodePc2Points() as MCAP ones. + class Ros1BagFileReader + { + public: + using Callbacks = McapFileReader::Callbacks; + + explicit Ros1BagFileReader(const std::filesystem::path& path, const McapReaderOptions& options = {}); + + bool isOpen() const; + const std::string& error() const; + const ResolvedTopics& topics() const; + const std::vector& channels() const; + // `rosbag record` writes messages in the order it received them, so a bag is + // read in ascending record time. + bool timeOrdered() const; + const std::string& lidarLayoutWarning() const; + + // Streams the messages whose record time lies in `range` (by default the whole + // bag) through `callbacks`; `log_time_ns` is the bag record time. Returns false + // on a read error (see error()). + bool read(const Callbacks& callbacks, const LogTimeRange& range = {}); + + // Record times covered by the bag's chunks; nullopt for an unindexed bag. + std::optional logTimeSpan() const; + + // Chunk compression of the bag ("none", "bz2", "lz4"); empty when unknown. + std::string compression(); + + private: + Ros1BagReader reader_; + McapReaderOptions options_; + ResolvedTopics topics_; + std::vector channels_; + std::string error_; + std::string warning_; + bool open_{ false }; + }; + + // Writes McapPoint/McapImuSample to a ROS1 bag, like McapFileWriter does for + // MCAP: same topics, frame ids and PointCloud2 layouts (pointCloudFields()). + class Ros1BagFileWriter + { + public: + explicit Ros1BagFileWriter(const std::filesystem::path& path, const McapWriterOptions& options = {}); + + bool isOpen() const; + const std::string& error() const; + + void writePointCloud(uint64_t timestamp_ns, const std::vector& points); + void writeImuSample(const McapImuSample& imu); + void writeImu(const std::vector& imu); + void writeSn(uint64_t timestamp_ns, const std::string& data); + + // Finishes the bag's index; the destructor calls it too. + bool close(); + + private: + Ros1BagWriter bag_; + McapWriterOptions options_; + uint32_t lidar_{}, imu_{}; + std::optional sn_; + uint32_t lidar_seq_{}, imu_seq_{}; + }; } // namespace rosbags diff --git a/rosbags/cdr_serializer.hpp b/rosbags/cdr_serializer.hpp index b61173d5..73e1e074 100644 --- a/rosbags/cdr_serializer.hpp +++ b/rosbags/cdr_serializer.hpp @@ -13,92 +13,92 @@ class CdrWriter { public: - CdrWriter() - { - buf_ = {0x00, 0x01, 0x00, 0x00}; - } - - void write_bool(bool v) - { - buf_.push_back(v ? 1u : 0u); - } - void write_u8(uint8_t v) - { - buf_.push_back(v); - } - - void write_u16(uint16_t v) - { - pad_to(2); - append(&v, 2); - } - void write_i32(int32_t v) - { - pad_to(4); - append(&v, 4); - } - void write_u32(uint32_t v) - { - pad_to(4); - append(&v, 4); - } - void write_f32(float v) - { - pad_to(4); - append(&v, 4); - } - void write_f64(double v) - { - pad_to(8); - append(&v, 8); - } - - void write_string(const std::string& s) - { - write_u32(static_cast(s.size() + 1)); - buf_.insert(buf_.end(), s.begin(), s.end()); - buf_.push_back(0); - } - void write_string(const char* s) - { - const size_t len = std::strlen(s); - write_u32(static_cast(len + 1)); - buf_.insert(buf_.end(), s, s + len); - buf_.push_back(0); - } - - // Raw bytes — no alignment, for uint8[] sequence payloads. - void write_raw(const void* src, size_t n) - { - const auto* p = static_cast(src); - buf_.insert(buf_.end(), p, p + n); - } - void write_raw(const std::string& s) - { - buf_.insert(buf_.end(), s.begin(), s.end()); - } - - const std::vector& data() const - { - return buf_; - } + CdrWriter() + { + buf_ = { 0x00, 0x01, 0x00, 0x00 }; + } + + void write_bool(bool v) + { + buf_.push_back(v ? 1u : 0u); + } + void write_u8(uint8_t v) + { + buf_.push_back(v); + } + + void write_u16(uint16_t v) + { + pad_to(2); + append(&v, 2); + } + void write_i32(int32_t v) + { + pad_to(4); + append(&v, 4); + } + void write_u32(uint32_t v) + { + pad_to(4); + append(&v, 4); + } + void write_f32(float v) + { + pad_to(4); + append(&v, 4); + } + void write_f64(double v) + { + pad_to(8); + append(&v, 8); + } + + void write_string(const std::string& s) + { + write_u32(static_cast(s.size() + 1)); + buf_.insert(buf_.end(), s.begin(), s.end()); + buf_.push_back(0); + } + void write_string(const char* s) + { + const size_t len = std::strlen(s); + write_u32(static_cast(len + 1)); + buf_.insert(buf_.end(), s, s + len); + buf_.push_back(0); + } + + // Raw bytes — no alignment, for uint8[] sequence payloads. + void write_raw(const void* src, size_t n) + { + const auto* p = static_cast(src); + buf_.insert(buf_.end(), p, p + n); + } + void write_raw(const std::string& s) + { + buf_.insert(buf_.end(), s.begin(), s.end()); + } + + const std::vector& data() const + { + return buf_; + } private: - std::vector buf_; - - // Alignment is counted from byte 4 (the CDR data section start). - void pad_to(size_t n) - { - size_t mod = (buf_.size() - 4) % n; - if(mod) - buf_.resize(buf_.size() + (n - mod), 0); - } - - void append(const void* src, size_t n) - { - const auto* p = static_cast(src); - buf_.insert(buf_.end(), p, p + n); - } + std::vector buf_; + + // Alignment is counted from byte 4 (the CDR data section start). + void pad_to(size_t n) + { + size_t mod = (buf_.size() - 4) % n; + if (mod) + buf_.resize(buf_.size() + (n - mod), 0); + } + + void append(const void* src, size_t n) + { + const auto* p = static_cast(src); + buf_.insert(buf_.end(), p, p + n); + } }; // --------------------------------------------------------------------------- @@ -108,47 +108,48 @@ class CdrWriter class CdrReader { public: - CdrReader(const void* data, size_t size) - : data_(static_cast(data)) - , size_(size) - , pos_(4) - { } - - bool ok() const - { - return pos_ <= size_; - } - - bool read_bool() - { - return pos_ < size_ ? data_[pos_++] != 0 : false; - } - uint8_t read_u8() - { - return pos_ < size_ ? data_[pos_++] : 0; - } - - uint16_t read_u16() - { - align(2); - uint16_t v = 0; - safe_copy(&v, 2); - return v; - } - int32_t read_i32() - { - align(4); - int32_t v = 0; - safe_copy(&v, 4); - return v; - } - uint32_t read_u32() - { - align(4); - uint32_t v = 0; - safe_copy(&v, 4); - return v; - } + CdrReader(const void* data, size_t size) + : data_(static_cast(data)) + , size_(size) + , pos_(4) + { + } + + bool ok() const + { + return pos_ <= size_; + } + + bool read_bool() + { + return pos_ < size_ ? data_[pos_++] != 0 : false; + } + uint8_t read_u8() + { + return pos_ < size_ ? data_[pos_++] : 0; + } + + uint16_t read_u16() + { + align(2); + uint16_t v = 0; + safe_copy(&v, 2); + return v; + } + int32_t read_i32() + { + align(4); + int32_t v = 0; + safe_copy(&v, 4); + return v; + } + uint32_t read_u32() + { + align(4); + uint32_t v = 0; + safe_copy(&v, 4); + return v; + } uint64_t read_u64() { align(8); @@ -156,70 +157,70 @@ class CdrReader safe_copy(&v, 8); return v; } - float read_f32() - { - align(4); - float v = 0; - safe_copy(&v, 4); - return v; - } - double read_f64() - { - align(8); - double v = 0; - safe_copy(&v, 8); - return v; - } - - std::string read_string() - { - uint32_t len = read_u32(); - if(len == 0 || pos_ + len > size_) - { - pos_ = std::min(pos_ + len, size_); - return {}; - } - std::string s(reinterpret_cast(data_ + pos_), len - 1); - pos_ += len; - return s; - } - - // Returns raw pointer at current pos and advances by n; nullptr if out of bounds. - const uint8_t* read_raw(size_t n) - { - if(pos_ + n > size_) - return nullptr; - const uint8_t* p = data_ + pos_; - pos_ += n; - return p; - } - - void skip(size_t n) - { - pos_ = std::min(pos_ + n, size_); - } + float read_f32() + { + align(4); + float v = 0; + safe_copy(&v, 4); + return v; + } + double read_f64() + { + align(8); + double v = 0; + safe_copy(&v, 8); + return v; + } + + std::string read_string() + { + uint32_t len = read_u32(); + if (len == 0 || pos_ + len > size_) + { + pos_ = std::min(pos_ + len, size_); + return {}; + } + std::string s(reinterpret_cast(data_ + pos_), len - 1); + pos_ += len; + return s; + } + + // Returns raw pointer at current pos and advances by n; nullptr if out of bounds. + const uint8_t* read_raw(size_t n) + { + if (pos_ + n > size_) + return nullptr; + const uint8_t* p = data_ + pos_; + pos_ += n; + return p; + } + + void skip(size_t n) + { + pos_ = std::min(pos_ + n, size_); + } private: - const uint8_t* data_; - size_t size_; - size_t pos_; - - // Alignment is counted from byte 4 (the CDR data section start). - void align(size_t n) - { - size_t mod = (pos_ - 4) % n; - if(mod) - pos_ += n - mod; - } - - void safe_copy(void* dst, size_t n) - { - if(pos_ + n <= size_) - { - std::memcpy(dst, data_ + pos_, n); - pos_ += n; - } - } + const uint8_t* data_; + size_t size_; + size_t pos_; + + // Alignment is counted from byte 4 (the CDR data section start). + void align(size_t n) + { + size_t mod = (pos_ - 4) % n; + if (mod) + pos_ += n - mod; + } + + void safe_copy(void* dst, size_t n) + { + if (pos_ + n <= size_) + { + std::memcpy(dst, data_ + pos_, n); + pos_ += n; + } + } }; // --------------------------------------------------------------------------- @@ -229,622 +230,636 @@ class CdrReader namespace rosbags { -// sensor_msgs/msg/PointField datatype codes. None is our own "field absent" -// marker, not part of the ROS message. -enum class Pc2Type : uint8_t -{ - None = 0, - Int8 = 1, - UInt8 = 2, - Int16 = 3, - UInt16 = 4, - Int32 = 5, - UInt32 = 6, - Float32 = 7, - Float64 = 8, -}; + // sensor_msgs/msg/PointField datatype codes. None is our own "field absent" + // marker, not part of the ROS message. + enum class Pc2Type : uint8_t + { + None = 0, + Int8 = 1, + UInt8 = 2, + Int16 = 3, + UInt16 = 4, + Int32 = 5, + UInt32 = 6, + Float32 = 7, + Float64 = 8, + }; -inline uint32_t pc2TypeSize(Pc2Type type) -{ - switch(type) - { - case Pc2Type::Int8: - case Pc2Type::UInt8: return 1; - case Pc2Type::Int16: - case Pc2Type::UInt16: return 2; - case Pc2Type::Int32: - case Pc2Type::UInt32: - case Pc2Type::Float32: return 4; - case Pc2Type::Float64: return 8; - case Pc2Type::None: - default: return 0; - } -} - -struct Pc2Field -{ - uint32_t offset = 0; - Pc2Type type = Pc2Type::None; + inline uint32_t pc2TypeSize(Pc2Type type) + { + switch (type) + { + case Pc2Type::Int8: + case Pc2Type::UInt8: + return 1; + case Pc2Type::Int16: + case Pc2Type::UInt16: + return 2; + case Pc2Type::Int32: + case Pc2Type::UInt32: + case Pc2Type::Float32: + return 4; + case Pc2Type::Float64: + return 8; + case Pc2Type::None: + default: + return 0; + } + } - bool present() const - { - return type != Pc2Type::None; - } -}; + struct Pc2Field + { + uint32_t offset = 0; + Pc2Type type = Pc2Type::None; -// LivoxPoint -struct LivoxPoint -{ - uint32_t offset_time; - float x; - float y; - float z; - uint8_t reflectivity; - uint8_t tag; - uint8_t line; -}; + bool present() const + { + return type != Pc2Type::None; + } + }; -// Livox CustomMsg -struct LivoxCustomMsg -{ - uint64_t timebase; - uint32_t point_num; - uint8_t lidar_id; - std::vector points; -}; + // LivoxPoint + struct LivoxPoint + { + uint32_t offset_time; + float x; + float y; + float z; + uint8_t reflectivity; + uint8_t tag; + uint8_t line; + }; -// Reads one field out of a point record and widens it to double, so callers do -// not care which of the eight PointField datatypes a driver happened to use. -inline double readPc2Field(const uint8_t* point, const Pc2Field& field) -{ - const uint8_t* p = point + field.offset; - switch(field.type) - { - case Pc2Type::Int8: - { - int8_t v = 0; - std::memcpy(&v, p, 1); - return static_cast(v); - } - case Pc2Type::UInt8: return static_cast(*p); - case Pc2Type::Int16: - { - int16_t v = 0; - std::memcpy(&v, p, 2); - return static_cast(v); - } - case Pc2Type::UInt16: - { - uint16_t v = 0; - std::memcpy(&v, p, 2); - return static_cast(v); - } - case Pc2Type::Int32: - { - int32_t v = 0; - std::memcpy(&v, p, 4); - return static_cast(v); - } - case Pc2Type::UInt32: - { - uint32_t v = 0; - std::memcpy(&v, p, 4); - return static_cast(v); - } - case Pc2Type::Float32: - { - float v = 0; - std::memcpy(&v, p, 4); - return static_cast(v); - } - case Pc2Type::Float64: - { - double v = 0; - std::memcpy(&v, p, 8); - return v; - } - case Pc2Type::None: - default: return 0.0; - } -} - -// The PointCloud2 fields McapPoint can represent. Three mutually exclusive -// per-point time fields are recognized, distinguished by name because the -// message carries no unit metadata: -// timestamp - absolute seconds (Hesai convention) -// time - seconds relative to the message stamp -// t - relative; nanoseconds if an integer type, seconds if floating -// Everything else in a record (reflectivity, ambient, range, ...) is ignored. -struct Pc2Layout -{ - uint32_t point_step = 0; - Pc2Field x, y, z, intensity, ring, laser_id, time, t, timestamp; -}; + // Livox CustomMsg + struct LivoxCustomMsg + { + uint64_t timebase; + uint32_t point_num; + uint8_t lidar_id; + std::vector points; + }; -// Selects how a PointCloud2's point records are interpreted. -// Auto - trust the message's own `fields` array (correct for every bag -// laz_to_mcap writes, and for any driver that fills it in honestly) -// Hesai - force the HesaiLidar_ROS_2.0 Pandar record layout -// Ouster - force the ouster_ros Point record layout -// The presets exist for bags whose `fields` array is missing, truncated, or -// mislabelled; Auto is otherwise strictly better, since it adapts per message. -enum class Pc2Preset -{ - Auto, - Hesai, - Ouster, -}; + // Reads one field out of a point record and widens it to double, so callers do + // not care which of the eight PointField datatypes a driver happened to use. + inline double readPc2Field(const uint8_t* point, const Pc2Field& field) + { + const uint8_t* p = point + field.offset; + switch (field.type) + { + case Pc2Type::Int8: + { + int8_t v = 0; + std::memcpy(&v, p, 1); + return static_cast(v); + } + case Pc2Type::UInt8: + return static_cast(*p); + case Pc2Type::Int16: + { + int16_t v = 0; + std::memcpy(&v, p, 2); + return static_cast(v); + } + case Pc2Type::UInt16: + { + uint16_t v = 0; + std::memcpy(&v, p, 2); + return static_cast(v); + } + case Pc2Type::Int32: + { + int32_t v = 0; + std::memcpy(&v, p, 4); + return static_cast(v); + } + case Pc2Type::UInt32: + { + uint32_t v = 0; + std::memcpy(&v, p, 4); + return static_cast(v); + } + case Pc2Type::Float32: + { + float v = 0; + std::memcpy(&v, p, 4); + return static_cast(v); + } + case Pc2Type::Float64: + { + double v = 0; + std::memcpy(&v, p, 8); + return v; + } + case Pc2Type::None: + default: + return 0.0; + } + } -// Verified against a real HesaiLidar_ROS_2.0 recording (/hesai/pandar): the -// PCL-style 4-byte pad after z puts intensity at 16, not 12, and point_step is -// 48 -- notably NOT the same packing PointCloudLayout::Hesai writes. -inline Pc2Layout hesaiPandarLayout() -{ - Pc2Layout l; - l.point_step = 48; - l.x = {0, Pc2Type::Float32}; - l.y = {4, Pc2Type::Float32}; - l.z = {8, Pc2Type::Float32}; - l.intensity = {16, Pc2Type::Float32}; - l.timestamp = {24, Pc2Type::Float64}; - l.ring = {32, Pc2Type::UInt16}; - return l; -} - -// ouster_ros' Point struct: PCL_ADD_POINT4D (16 bytes) + intensity, t, -// reflectivity, ring, ambient, range, padded to 48. Transcribed from the -// driver's published layout rather than measured, and ring's width has moved -// between driver releases -- decodePc2 cross-checks any preset against the -// message's own fields array and reports a mismatch, so a wrong guess here -// surfaces as a warning instead of as silently shifted data. -inline Pc2Layout ousterRosLayout() -{ - Pc2Layout l; - l.point_step = 48; - l.x = {0, Pc2Type::Float32}; - l.y = {4, Pc2Type::Float32}; - l.z = {8, Pc2Type::Float32}; - l.intensity = {16, Pc2Type::Float32}; - l.t = {20, Pc2Type::UInt32}; - l.ring = {26, Pc2Type::UInt8}; - return l; -} - -// False for Auto, which has no fixed layout. -inline bool pc2PresetLayout(Pc2Preset preset, Pc2Layout& out) -{ - switch(preset) - { - case Pc2Preset::Hesai: out = hesaiPandarLayout(); return true; - case Pc2Preset::Ouster: out = ousterRosLayout(); return true; - case Pc2Preset::Auto: - default: return false; - } -} - -inline const char* pc2PresetName(Pc2Preset preset) -{ - switch(preset) - { - case Pc2Preset::Hesai: return "hesai"; - case Pc2Preset::Ouster: return "ouster"; - case Pc2Preset::Auto: - default: return "auto"; - } -} - -// Every present field must lie wholly inside one point record, or decoding -// would read into the following point (or off the end of the buffer for the -// last one). Only reachable with a forced preset whose point_step disagrees -// with the file. -inline bool pc2FieldFits(const Pc2Field& field, uint32_t point_step) -{ - if(!field.present()) - return true; - return static_cast(field.offset) + pc2TypeSize(field.type) <= point_step; -} + // The PointCloud2 fields McapPoint can represent. Three mutually exclusive + // per-point time fields are recognized, distinguished by name because the + // message carries no unit metadata: + // timestamp - absolute seconds (Hesai convention) + // time - seconds relative to the message stamp + // t - relative; nanoseconds if an integer type, seconds if floating + // Everything else in a record (reflectivity, ambient, range, ...) is ignored. + struct Pc2Layout + { + uint32_t point_step = 0; + Pc2Field x, y, z, intensity, ring, laser_id, time, t, timestamp; + }; -inline bool pc2LayoutFits(const Pc2Layout& l) -{ - return pc2FieldFits(l.x, l.point_step) && pc2FieldFits(l.y, l.point_step) && pc2FieldFits(l.z, l.point_step) && - pc2FieldFits(l.intensity, l.point_step) && pc2FieldFits(l.ring, l.point_step) && pc2FieldFits(l.laser_id, l.point_step) && - pc2FieldFits(l.time, l.point_step) && pc2FieldFits(l.t, l.point_step) && pc2FieldFits(l.timestamp, l.point_step); -} + // Selects how a PointCloud2's point records are interpreted. + // Auto - trust the message's own `fields` array (correct for every bag + // laz_to_mcap writes, and for any driver that fills it in honestly) + // Hesai - force the HesaiLidar_ROS_2.0 Pandar record layout + // Ouster - force the ouster_ros Point record layout + // The presets exist for bags whose `fields` array is missing, truncated, or + // mislabelled; Auto is otherwise strictly better, since it adapts per message. + enum class Pc2Preset + { + Auto, + Hesai, + Ouster, + }; -namespace detail -{ + // Verified against a real HesaiLidar_ROS_2.0 recording (/hesai/pandar): the + // PCL-style 4-byte pad after z puts intensity at 16, not 12, and point_step is + // 48 -- notably NOT the same packing PointCloudLayout::Hesai writes. + inline Pc2Layout hesaiPandarLayout() + { + Pc2Layout l; + l.point_step = 48; + l.x = { 0, Pc2Type::Float32 }; + l.y = { 4, Pc2Type::Float32 }; + l.z = { 8, Pc2Type::Float32 }; + l.intensity = { 16, Pc2Type::Float32 }; + l.timestamp = { 24, Pc2Type::Float64 }; + l.ring = { 32, Pc2Type::UInt16 }; + return l; + } -// Appends a human-readable " vs " note for one -// field whose preset and message descriptions disagree. -inline void describePc2Mismatch(const char* name, const Pc2Field& preset, const Pc2Field& message, std::string& out) -{ - if(preset.offset == message.offset && preset.type == message.type) - return; - if(!preset.present() && !message.present()) - return; - if(!out.empty()) - out += ", "; - out += name; - out += " preset@" + std::to_string(preset.offset) + "/type" + std::to_string(static_cast(preset.type)); - out += " vs file@" + std::to_string(message.offset) + "/type" + std::to_string(static_cast(message.type)); -} - -inline std::string comparePc2Layouts(const Pc2Layout& preset, const Pc2Layout& message) -{ - std::string diff; - describePc2Mismatch("x", preset.x, message.x, diff); - describePc2Mismatch("y", preset.y, message.y, diff); - describePc2Mismatch("z", preset.z, message.z, diff); - describePc2Mismatch("intensity", preset.intensity, message.intensity, diff); - describePc2Mismatch("ring", preset.ring, message.ring, diff); - describePc2Mismatch("laser_id", preset.laser_id, message.laser_id, diff); - describePc2Mismatch("time", preset.time, message.time, diff); - describePc2Mismatch("t", preset.t, message.t, diff); - describePc2Mismatch("timestamp", preset.timestamp, message.timestamp, diff); - if(preset.point_step != message.point_step) - { - if(!diff.empty()) - diff += ", "; - diff += "point_step preset=" + std::to_string(preset.point_step) + " vs file=" + std::to_string(message.point_step); - } - return diff; -} - -} // namespace detail - -// sensor_msgs/msg/PointCloud2 → std::vector -// -// By default (Pc2Preset::Auto) the record layout is taken from the message's own -// `fields` array -- offsets *and* datatypes -- so one decoder handles every -// PointCloudLayout McapWriter emits as well as foreign driver bags, which pack -// the same field names at different offsets and widths. Recognized names are -// x, y, z (required), intensity, ring, laser_id, and the three time fields -// described on Pc2Layout; anything else is ignored. -// -// Passing a preset instead forces that driver's layout and ignores the file's -// fields array, for bags whose array is missing or wrong. When the file does -// describe its fields, the preset is still compared against it and any -// disagreement is reported through `warning` -- forcing a layout that does not -// match the data is the one way this decoder can silently produce plausible -// nonsense, so it is never done quietly. - -// decode livox_ros_driver2/msg/CustomMsg -// -inline std::vector decodeLivoxCustomMsg( - const uint8_t* data, - size_t size, - double fallback_stamp = 0.0, - std::string* warning = nullptr) -{ - const auto warn = [&](std::string message) + // ouster_ros' Point struct: PCL_ADD_POINT4D (16 bytes) + intensity, t, + // reflectivity, ring, ambient, range, padded to 48. Transcribed from the + // driver's published layout rather than measured, and ring's width has moved + // between driver releases -- decodePc2 cross-checks any preset against the + // message's own fields array and reports a mismatch, so a wrong guess here + // surfaces as a warning instead of as silently shifted data. + inline Pc2Layout ousterRosLayout() { - if (warning && warning->empty()) - *warning = std::move(message); - }; + Pc2Layout l; + l.point_step = 48; + l.x = { 0, Pc2Type::Float32 }; + l.y = { 4, Pc2Type::Float32 }; + l.z = { 8, Pc2Type::Float32 }; + l.intensity = { 16, Pc2Type::Float32 }; + l.t = { 20, Pc2Type::UInt32 }; + l.ring = { 26, Pc2Type::UInt8 }; + return l; + } + + // False for Auto, which has no fixed layout. + inline bool pc2PresetLayout(Pc2Preset preset, Pc2Layout& out) + { + switch (preset) + { + case Pc2Preset::Hesai: + out = hesaiPandarLayout(); + return true; + case Pc2Preset::Ouster: + out = ousterRosLayout(); + return true; + case Pc2Preset::Auto: + default: + return false; + } + } - std::vector points; - CdrReader r(data, size); + inline const char* pc2PresetName(Pc2Preset preset) + { + switch (preset) + { + case Pc2Preset::Hesai: + return "hesai"; + case Pc2Preset::Ouster: + return "ouster"; + case Pc2Preset::Auto: + default: + return "auto"; + } + } - if (!r.ok()) + // Every present field must lie wholly inside one point record, or decoding + // would read into the following point (or off the end of the buffer for the + // last one). Only reachable with a forced preset whose point_step disagrees + // with the file. + inline bool pc2FieldFits(const Pc2Field& field, uint32_t point_step) { - warn("Livox CustomMsg data is truncated"); - return points; + if (!field.present()) + return true; + return static_cast(field.offset) + pc2TypeSize(field.type) <= point_step; + } + + inline bool pc2LayoutFits(const Pc2Layout& l) + { + return pc2FieldFits(l.x, l.point_step) && pc2FieldFits(l.y, l.point_step) && pc2FieldFits(l.z, l.point_step) && + pc2FieldFits(l.intensity, l.point_step) && pc2FieldFits(l.ring, l.point_step) && pc2FieldFits(l.laser_id, l.point_step) && + pc2FieldFits(l.time, l.point_step) && pc2FieldFits(l.t, l.point_step) && pc2FieldFits(l.timestamp, l.point_step); } - // reading header (std ROS2 header) - const int32_t stamp_sec = r.read_i32(); - const uint32_t stamp_nsec = r.read_u32(); - r.read_string(); // frame_id - - (void)stamp_sec; - (void)stamp_nsec; - (void)fallback_stamp; - - // reading Livox CustomMsg - const uint64_t timebase = r.read_u64(); - const uint32_t point_num = r.read_u32(); - r.read_u8(); // lidar_id - r.skip(3); // uint8[3] rsvd - - const uint32_t seq_len = r.read_u32(); - if (seq_len != point_num) - warn("CustomMsg point_num (" + std::to_string(point_num) + - ") != points sequence length (" + std::to_string(seq_len) + ")"); - const uint32_t n = std::min(point_num, seq_len); - - // reading points - const double timebase_sec = static_cast(timebase) * 1e-9; - - points.reserve(n); - for (uint32_t i = 0; i < n; ++i) + namespace detail { + + // Appends a human-readable " vs " note for one + // field whose preset and message descriptions disagree. + inline void describePc2Mismatch(const char* name, const Pc2Field& preset, const Pc2Field& message, std::string& out) + { + if (preset.offset == message.offset && preset.type == message.type) + return; + if (!preset.present() && !message.present()) + return; + if (!out.empty()) + out += ", "; + out += name; + out += " preset@" + std::to_string(preset.offset) + "/type" + std::to_string(static_cast(preset.type)); + out += " vs file@" + std::to_string(message.offset) + "/type" + std::to_string(static_cast(message.type)); + } + + inline std::string comparePc2Layouts(const Pc2Layout& preset, const Pc2Layout& message) + { + std::string diff; + describePc2Mismatch("x", preset.x, message.x, diff); + describePc2Mismatch("y", preset.y, message.y, diff); + describePc2Mismatch("z", preset.z, message.z, diff); + describePc2Mismatch("intensity", preset.intensity, message.intensity, diff); + describePc2Mismatch("ring", preset.ring, message.ring, diff); + describePc2Mismatch("laser_id", preset.laser_id, message.laser_id, diff); + describePc2Mismatch("time", preset.time, message.time, diff); + describePc2Mismatch("t", preset.t, message.t, diff); + describePc2Mismatch("timestamp", preset.timestamp, message.timestamp, diff); + if (preset.point_step != message.point_step) + { + if (!diff.empty()) + diff += ", "; + diff += "point_step preset=" + std::to_string(preset.point_step) + " vs file=" + std::to_string(message.point_step); + } + return diff; + } + + } // namespace detail + + // sensor_msgs/msg/PointCloud2 → std::vector + // + // By default (Pc2Preset::Auto) the record layout is taken from the message's own + // `fields` array -- offsets *and* datatypes -- so one decoder handles every + // PointCloudLayout McapWriter emits as well as foreign driver bags, which pack + // the same field names at different offsets and widths. Recognized names are + // x, y, z (required), intensity, ring, laser_id, and the three time fields + // described on Pc2Layout; anything else is ignored. + // + // Passing a preset instead forces that driver's layout and ignores the file's + // fields array, for bags whose array is missing or wrong. When the file does + // describe its fields, the preset is still compared against it and any + // disagreement is reported through `warning` -- forcing a layout that does not + // match the data is the one way this decoder can silently produce plausible + // nonsense, so it is never done quietly. + + // decode livox_ros_driver2/msg/CustomMsg + // + inline std::vector decodeLivoxCustomMsg( + const uint8_t* data, size_t size, double fallback_stamp = 0.0, std::string* warning = nullptr) + { + const auto warn = [&](std::string message) + { + if (warning && warning->empty()) + *warning = std::move(message); + }; + + std::vector points; + CdrReader r(data, size); + if (!r.ok()) { - warn("Truncated point data at index " + std::to_string(i)); - break; + warn("Livox CustomMsg data is truncated"); + return points; } - LivoxPoint pt; - pt.offset_time = r.read_u32(); - pt.x = r.read_f32(); - pt.y = r.read_f32(); - pt.z = r.read_f32(); - pt.reflectivity = r.read_u8(); - pt.tag = r.read_u8(); - pt.line = r.read_u8(); - - // to McapPoint - McapPoint mcap_pt; - mcap_pt.x = pt.x; - mcap_pt.y = pt.y; - mcap_pt.z = pt.z; - mcap_pt.intensity = static_cast(pt.reflectivity); - mcap_pt.ring = static_cast(pt.line); - mcap_pt.laser_id = pt.tag; - - // compute timestamp of point: timebase + offset_time - const double offset_sec = static_cast(pt.offset_time) * 1e-9; - mcap_pt.timestamp = timebase_sec + offset_sec; - - points.push_back(mcap_pt); - } - - return points; -} - -// Matches one PointCloud2 field description onto `msg`, as decodePc2() does for -// each entry of the `fields` array. Unrecognized names and array fields are ignored. -inline void addPc2Field(Pc2Layout& msg, const std::string& name, uint32_t offset, Pc2Type type, uint32_t count) -{ - // count > 1 is an array field (never used for the scalars below). - if(count != 1 || pc2TypeSize(type) == 0) - return; - - const Pc2Field field{offset, type}; - if(name == "x") - msg.x = field; - else if(name == "y") - msg.y = field; - else if(name == "z") - msg.z = field; - else if(name == "intensity") - msg.intensity = field; - else if(name == "ring") - msg.ring = field; - else if(name == "laser_id") - msg.laser_id = field; - else if(name == "time") - msg.time = field; - else if(name == "t") - msg.t = field; - else if(name == "timestamp") - msg.timestamp = field; -} - -// The point records of one PointCloud2, whatever its serialization: `msg` is the -// layout built from the message's fields array (point_step included), `n_fields` -// how many fields that array had, `stamp_s` the header stamp. Shared by -// decodePc2() (ROS2/CDR) and the ROS1 bag reader, so both apply the same presets, -// time-field rules and warnings. -inline std::vector decodePc2Points( - const Pc2Layout& msg, - uint32_t n_fields, - double stamp_s, - const uint8_t* rawData, - size_t dataLen, - Pc2Preset preset = Pc2Preset::Auto, - std::string* warning = nullptr) -{ - const auto warn = [&](std::string message) { - if(warning && warning->empty()) - *warning = std::move(message); - }; - - std::vector points; - - Pc2Layout layout; - if(pc2PresetLayout(preset, layout)) - { - if(n_fields > 0) - { - const std::string diff = detail::comparePc2Layouts(layout, msg); - if(!diff.empty()) - warn(std::string("forced '") + pc2PresetName(preset) + "' layout disagrees with the file's own fields (" + diff + ")"); - } - } - else - { - layout = msg; - } - - if(layout.point_step == 0) - { - warn("PointCloud2 has a zero point_step"); - return points; - } - if(!layout.x.present() || !layout.y.present() || !layout.z.present()) - { - warn("PointCloud2 has no x/y/z fields"); - return points; - } - if(!pc2LayoutFits(layout)) - { - warn(std::string("'") + pc2PresetName(preset) + "' layout has fields reaching past point_step " + - std::to_string(layout.point_step)); - return points; - } - - const size_t nPts = dataLen / layout.point_step; - points.reserve(nPts); - - for(size_t i = 0; i < nPts; ++i) - { - const uint8_t* p = rawData + i * layout.point_step; - - McapPoint pt{}; - pt.x = static_cast(readPc2Field(p, layout.x)); - pt.y = static_cast(readPc2Field(p, layout.y)); - pt.z = static_cast(readPc2Field(p, layout.z)); - if(layout.intensity.present()) - pt.intensity = static_cast(readPc2Field(p, layout.intensity)); - if(layout.ring.present()) - pt.ring = static_cast(readPc2Field(p, layout.ring)); - if(layout.laser_id.present()) - pt.laser_id = static_cast(readPc2Field(p, layout.laser_id)); - - if(layout.timestamp.present()) - { - pt.timestamp = readPc2Field(p, layout.timestamp); - } - else if(layout.time.present()) - { - pt.timestamp = stamp_s + readPc2Field(p, layout.time); - } - else if(layout.t.present()) - { - // Integer t is nanoseconds (ouster_ros); floating t is seconds. - const double raw = readPc2Field(p, layout.t); - const bool integral = layout.t.type != Pc2Type::Float32 && layout.t.type != Pc2Type::Float64; - pt.timestamp = stamp_s + (integral ? raw * 1e-9 : raw); - } - else - { - pt.timestamp = stamp_s; - } - - points.push_back(pt); - } - - return points; -} - -inline std::vector decodePc2( - const uint8_t* data, size_t size, Pc2Preset preset = Pc2Preset::Auto, std::string* warning = nullptr) -{ - const auto warn = [&](std::string message) { - if(warning && warning->empty()) - *warning = std::move(message); - }; - - CdrReader r(data, size); - - const int32_t stamp_sec = r.read_i32(); - const uint32_t stamp_nsec = r.read_u32(); - r.read_string(); // frame_id - - const double stamp_s = static_cast(stamp_sec) + static_cast(stamp_nsec) * 1e-9; - - r.read_u32(); // height - r.read_u32(); // width -- the record count is derived from data/point_step instead - - Pc2Layout msg; - const uint32_t nFields = r.read_u32(); - for(uint32_t i = 0; i < nFields; ++i) - { - const std::string name = r.read_string(); - const uint32_t offset = r.read_u32(); - const auto type = static_cast(r.read_u8()); - const uint32_t count = r.read_u32(); - addPc2Field(msg, name, offset, type, count); - } - - const bool is_bigendian = r.read_bool(); - msg.point_step = r.read_u32(); - r.read_u32(); // row_step - - const uint32_t dataLen = r.read_u32(); - const uint8_t* rawData = r.read_raw(dataLen); - - if(!rawData) - { - warn("PointCloud2 data array is truncated"); - return {}; - } - if(is_bigendian) - { - // No real ROS2 bag sets this; byte-swapping every field to support a - // hypothetical one would be untestable, so refuse rather than misread. - warn("PointCloud2 is big-endian, which is not supported"); - return {}; - } - - return decodePc2Points(msg, nFields, stamp_s, rawData, dataLen, preset, warning); -} - -// sensor_msgs/msg/Imu → McapImuSample (one sample per CDR message) -inline std::optional decodeImu(const uint8_t* data, size_t size) -{ - CdrReader r(data, size); - - const int32_t stamp_sec = r.read_i32(); - const uint32_t stamp_nsec = r.read_u32(); - r.read_string(); // frame_id - - const double stamp_s = static_cast(stamp_sec) + static_cast(stamp_nsec) * 1e-9; - - // orientation quaternion (skip) - r.read_f64(); - r.read_f64(); - r.read_f64(); - r.read_f64(); - // orientation_covariance[9] (skip) - for(int i = 0; i < 9; ++i) - r.read_f64(); - - McapImuSample imu{}; - imu.gyro_x = static_cast(r.read_f64()); - imu.gyro_y = static_cast(r.read_f64()); - imu.gyro_z = static_cast(r.read_f64()); - // angular_velocity_covariance[9] (skip) - for(int i = 0; i < 9; ++i) - r.read_f64(); - - imu.acc_x = static_cast(r.read_f64()); - imu.acc_y = static_cast(r.read_f64()); - imu.acc_z = static_cast(r.read_f64()); - - imu.timestamp = stamp_s; - if(!r.ok()) - return std::nullopt; - return imu; -} - -// std_msgs/msg/String → std::string (empty on parse error) -inline std::string decodeSn(const uint8_t* data, size_t size) -{ - CdrReader r(data, size); - std::string s = r.read_string(); - return r.ok() ? s : std::string{}; -} - -// tf2_msgs/msg/TFMessage → McapTransform (first TransformStamped only; McapWriter -// never writes more than one) -inline std::optional decodeTf(const uint8_t* data, size_t size) -{ - CdrReader r(data, size); - - const uint32_t n = r.read_u32(); // transforms[] sequence length - if(n == 0) - return std::nullopt; - - const int32_t stamp_sec = r.read_i32(); - const uint32_t stamp_nsec = r.read_u32(); - r.read_string(); // frame_id (parent) - r.read_string(); // child_frame_id - - McapTransform t{}; - t.timestamp = static_cast(stamp_sec) + static_cast(stamp_nsec) * 1e-9; - t.tx = r.read_f64(); - t.ty = r.read_f64(); - t.tz = r.read_f64(); - t.qx = r.read_f64(); - t.qy = r.read_f64(); - t.qz = r.read_f64(); - t.qw = r.read_f64(); - - if(!r.ok()) - return std::nullopt; - return t; -} + // reading header (std ROS2 header) + const int32_t stamp_sec = r.read_i32(); + const uint32_t stamp_nsec = r.read_u32(); + r.read_string(); // frame_id + + (void)stamp_sec; + (void)stamp_nsec; + (void)fallback_stamp; + + // reading Livox CustomMsg + const uint64_t timebase = r.read_u64(); + const uint32_t point_num = r.read_u32(); + r.read_u8(); // lidar_id + r.skip(3); // uint8[3] rsvd + + const uint32_t seq_len = r.read_u32(); + if (seq_len != point_num) + warn("CustomMsg point_num (" + std::to_string(point_num) + ") != points sequence length (" + std::to_string(seq_len) + ")"); + const uint32_t n = std::min(point_num, seq_len); + + // reading points + const double timebase_sec = static_cast(timebase) * 1e-9; + + points.reserve(n); + for (uint32_t i = 0; i < n; ++i) + { + if (!r.ok()) + { + warn("Truncated point data at index " + std::to_string(i)); + break; + } + + LivoxPoint pt; + pt.offset_time = r.read_u32(); + pt.x = r.read_f32(); + pt.y = r.read_f32(); + pt.z = r.read_f32(); + pt.reflectivity = r.read_u8(); + pt.tag = r.read_u8(); + pt.line = r.read_u8(); + + // to McapPoint + McapPoint mcap_pt; + mcap_pt.x = pt.x; + mcap_pt.y = pt.y; + mcap_pt.z = pt.z; + mcap_pt.intensity = static_cast(pt.reflectivity); + mcap_pt.ring = static_cast(pt.line); + mcap_pt.laser_id = pt.tag; + + // compute timestamp of point: timebase + offset_time + const double offset_sec = static_cast(pt.offset_time) * 1e-9; + mcap_pt.timestamp = timebase_sec + offset_sec; + + points.push_back(mcap_pt); + } + + return points; + } + + // Matches one PointCloud2 field description onto `msg`, as decodePc2() does for + // each entry of the `fields` array. Unrecognized names and array fields are ignored. + inline void addPc2Field(Pc2Layout& msg, const std::string& name, uint32_t offset, Pc2Type type, uint32_t count) + { + // count > 1 is an array field (never used for the scalars below). + if (count != 1 || pc2TypeSize(type) == 0) + return; + + const Pc2Field field{ offset, type }; + if (name == "x") + msg.x = field; + else if (name == "y") + msg.y = field; + else if (name == "z") + msg.z = field; + else if (name == "intensity") + msg.intensity = field; + else if (name == "ring") + msg.ring = field; + else if (name == "laser_id") + msg.laser_id = field; + else if (name == "time") + msg.time = field; + else if (name == "t") + msg.t = field; + else if (name == "timestamp") + msg.timestamp = field; + } + + // The point records of one PointCloud2, whatever its serialization: `msg` is the + // layout built from the message's fields array (point_step included), `n_fields` + // how many fields that array had, `stamp_s` the header stamp. Shared by + // decodePc2() (ROS2/CDR) and the ROS1 bag reader, so both apply the same presets, + // time-field rules and warnings. + inline std::vector decodePc2Points( + const Pc2Layout& msg, + uint32_t n_fields, + double stamp_s, + const uint8_t* rawData, + size_t dataLen, + Pc2Preset preset = Pc2Preset::Auto, + std::string* warning = nullptr) + { + const auto warn = [&](std::string message) + { + if (warning && warning->empty()) + *warning = std::move(message); + }; + + std::vector points; + + Pc2Layout layout; + if (pc2PresetLayout(preset, layout)) + { + if (n_fields > 0) + { + const std::string diff = detail::comparePc2Layouts(layout, msg); + if (!diff.empty()) + warn(std::string("forced '") + pc2PresetName(preset) + "' layout disagrees with the file's own fields (" + diff + ")"); + } + } + else + { + layout = msg; + } + + if (layout.point_step == 0) + { + warn("PointCloud2 has a zero point_step"); + return points; + } + if (!layout.x.present() || !layout.y.present() || !layout.z.present()) + { + warn("PointCloud2 has no x/y/z fields"); + return points; + } + if (!pc2LayoutFits(layout)) + { + warn( + std::string("'") + pc2PresetName(preset) + "' layout has fields reaching past point_step " + + std::to_string(layout.point_step)); + return points; + } + + const size_t nPts = dataLen / layout.point_step; + points.reserve(nPts); + + for (size_t i = 0; i < nPts; ++i) + { + const uint8_t* p = rawData + i * layout.point_step; + + McapPoint pt{}; + pt.x = static_cast(readPc2Field(p, layout.x)); + pt.y = static_cast(readPc2Field(p, layout.y)); + pt.z = static_cast(readPc2Field(p, layout.z)); + if (layout.intensity.present()) + pt.intensity = static_cast(readPc2Field(p, layout.intensity)); + if (layout.ring.present()) + pt.ring = static_cast(readPc2Field(p, layout.ring)); + if (layout.laser_id.present()) + pt.laser_id = static_cast(readPc2Field(p, layout.laser_id)); + + if (layout.timestamp.present()) + { + pt.timestamp = readPc2Field(p, layout.timestamp); + } + else if (layout.time.present()) + { + pt.timestamp = stamp_s + readPc2Field(p, layout.time); + } + else if (layout.t.present()) + { + // Integer t is nanoseconds (ouster_ros); floating t is seconds. + const double raw = readPc2Field(p, layout.t); + const bool integral = layout.t.type != Pc2Type::Float32 && layout.t.type != Pc2Type::Float64; + pt.timestamp = stamp_s + (integral ? raw * 1e-9 : raw); + } + else + { + pt.timestamp = stamp_s; + } + + points.push_back(pt); + } + + return points; + } + + inline std::vector decodePc2( + const uint8_t* data, size_t size, Pc2Preset preset = Pc2Preset::Auto, std::string* warning = nullptr) + { + const auto warn = [&](std::string message) + { + if (warning && warning->empty()) + *warning = std::move(message); + }; + + CdrReader r(data, size); + + const int32_t stamp_sec = r.read_i32(); + const uint32_t stamp_nsec = r.read_u32(); + r.read_string(); // frame_id + + const double stamp_s = static_cast(stamp_sec) + static_cast(stamp_nsec) * 1e-9; + + r.read_u32(); // height + r.read_u32(); // width -- the record count is derived from data/point_step instead + + Pc2Layout msg; + const uint32_t nFields = r.read_u32(); + for (uint32_t i = 0; i < nFields; ++i) + { + const std::string name = r.read_string(); + const uint32_t offset = r.read_u32(); + const auto type = static_cast(r.read_u8()); + const uint32_t count = r.read_u32(); + addPc2Field(msg, name, offset, type, count); + } + + const bool is_bigendian = r.read_bool(); + msg.point_step = r.read_u32(); + r.read_u32(); // row_step + + const uint32_t dataLen = r.read_u32(); + const uint8_t* rawData = r.read_raw(dataLen); + + if (!rawData) + { + warn("PointCloud2 data array is truncated"); + return {}; + } + if (is_bigendian) + { + // No real ROS2 bag sets this; byte-swapping every field to support a + // hypothetical one would be untestable, so refuse rather than misread. + warn("PointCloud2 is big-endian, which is not supported"); + return {}; + } + + return decodePc2Points(msg, nFields, stamp_s, rawData, dataLen, preset, warning); + } + + // sensor_msgs/msg/Imu → McapImuSample (one sample per CDR message) + inline std::optional decodeImu(const uint8_t* data, size_t size) + { + CdrReader r(data, size); + + const int32_t stamp_sec = r.read_i32(); + const uint32_t stamp_nsec = r.read_u32(); + r.read_string(); // frame_id + + const double stamp_s = static_cast(stamp_sec) + static_cast(stamp_nsec) * 1e-9; + + // orientation quaternion (skip) + r.read_f64(); + r.read_f64(); + r.read_f64(); + r.read_f64(); + // orientation_covariance[9] (skip) + for (int i = 0; i < 9; ++i) + r.read_f64(); + + McapImuSample imu{}; + imu.gyro_x = static_cast(r.read_f64()); + imu.gyro_y = static_cast(r.read_f64()); + imu.gyro_z = static_cast(r.read_f64()); + // angular_velocity_covariance[9] (skip) + for (int i = 0; i < 9; ++i) + r.read_f64(); + + imu.acc_x = static_cast(r.read_f64()); + imu.acc_y = static_cast(r.read_f64()); + imu.acc_z = static_cast(r.read_f64()); + + imu.timestamp = stamp_s; + if (!r.ok()) + return std::nullopt; + return imu; + } + + // std_msgs/msg/String → std::string (empty on parse error) + inline std::string decodeSn(const uint8_t* data, size_t size) + { + CdrReader r(data, size); + std::string s = r.read_string(); + return r.ok() ? s : std::string{}; + } + + // tf2_msgs/msg/TFMessage → McapTransform (first TransformStamped only; McapWriter + // never writes more than one) + inline std::optional decodeTf(const uint8_t* data, size_t size) + { + CdrReader r(data, size); + + const uint32_t n = r.read_u32(); // transforms[] sequence length + if (n == 0) + return std::nullopt; + + const int32_t stamp_sec = r.read_i32(); + const uint32_t stamp_nsec = r.read_u32(); + r.read_string(); // frame_id (parent) + r.read_string(); // child_frame_id + + McapTransform t{}; + t.timestamp = static_cast(stamp_sec) + static_cast(stamp_nsec) * 1e-9; + t.tx = r.read_f64(); + t.ty = r.read_f64(); + t.tz = r.read_f64(); + t.qx = r.read_f64(); + t.qy = r.read_f64(); + t.qz = r.read_f64(); + t.qw = r.read_f64(); + + if (!r.ok()) + return std::nullopt; + return t; + } } // namespace rosbags \ No newline at end of file diff --git a/rosbags/tests/test_mcap_reader.cpp b/rosbags/tests/test_mcap_reader.cpp index 1d05231e..0799e5ba 100644 --- a/rosbags/tests/test_mcap_reader.cpp +++ b/rosbags/tests/test_mcap_reader.cpp @@ -2,8 +2,8 @@ // header (including , which pulls in plenty of its own) gets a // chance to lock in the project-wide _HAS_STD_BYTE=0 MSVC workaround. #if defined(_MSC_VER) -# undef _HAS_STD_BYTE -# define _HAS_STD_BYTE 1 +#undef _HAS_STD_BYTE +#define _HAS_STD_BYTE 1 #endif // No DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN here: test_mcap_writer.cpp (linked into @@ -34,117 +34,117 @@ namespace fs = std::filesystem; namespace { -fs::path tempPath(const char* name) -{ - return fs::temp_directory_path() / name; -} + fs::path tempPath(const char* name) + { + return fs::temp_directory_path() / name; + } -std::vector makeReaderPoints(size_t n, double t0) -{ - std::mt19937 rng(7); - std::uniform_real_distribution coord(-50.0f, 50.0f); - - std::vector points; - points.reserve(n); - for (size_t i = 0; i < n; ++i) - { - rosbags::McapPoint p{}; - p.x = coord(rng); - p.y = coord(rng); - p.z = coord(rng); - p.intensity = static_cast(i % 256); - p.ring = static_cast(i % 16); - p.laser_id = static_cast(1 + i % 3); // non-zero, so the round trip can be checked - p.timestamp = t0 + static_cast(i) * 1e-6; - points.push_back(p); - } - return points; -} + std::vector makeReaderPoints(size_t n, double t0) + { + std::mt19937 rng(7); + std::uniform_real_distribution coord(-50.0f, 50.0f); -std::vector makeImuSamples(size_t n, double t0) -{ - std::vector samples; - samples.reserve(n); - for (size_t i = 0; i < n; ++i) - { - rosbags::McapImuSample s{}; - s.timestamp = t0 + static_cast(i) * 0.005; - s.gyro_x = 0.01f * static_cast(i); - s.gyro_y = -0.02f * static_cast(i); - s.gyro_z = 0.03f * static_cast(i); - s.acc_x = 0.1f; - s.acc_y = 0.2f; - s.acc_z = 9.81f; - samples.push_back(s); - } - return samples; -} + std::vector points; + points.reserve(n); + for (size_t i = 0; i < n; ++i) + { + rosbags::McapPoint p{}; + p.x = coord(rng); + p.y = coord(rng); + p.z = coord(rng); + p.intensity = static_cast(i % 256); + p.ring = static_cast(i % 16); + p.laser_id = static_cast(1 + i % 3); // non-zero, so the round trip can be checked + p.timestamp = t0 + static_cast(i) * 1e-6; + points.push_back(p); + } + return points; + } -// One point as stored in a LAZ file, decoded exactly the way -// load_point_cloud() (apps/lidar_odometry_step_1/lidar_odometry_utils.cpp) does: -// coordinates from the header scale/offset, timestamp straight out of gps_time, -// lidar id out of user_data. point_format and rgb are not read by -// load_point_cloud(); they are here to check what the writer stores. -struct LazPoint -{ - double x, y, z; - double gps_time; - uint16_t intensity; - uint8_t user_data; - uint8_t point_format; - uint16_t rgb[3]; -}; - -std::vector readLaz(const fs::path& path) -{ - std::vector out; + std::vector makeImuSamples(size_t n, double t0) + { + std::vector samples; + samples.reserve(n); + for (size_t i = 0; i < n; ++i) + { + rosbags::McapImuSample s{}; + s.timestamp = t0 + static_cast(i) * 0.005; + s.gyro_x = 0.01f * static_cast(i); + s.gyro_y = -0.02f * static_cast(i); + s.gyro_z = 0.03f * static_cast(i); + s.acc_x = 0.1f; + s.acc_y = 0.2f; + s.acc_z = 9.81f; + samples.push_back(s); + } + return samples; + } - laszip_POINTER reader = nullptr; - REQUIRE(laszip_create(&reader) == 0); + // One point as stored in a LAZ file, decoded exactly the way + // load_point_cloud() (apps/lidar_odometry_step_1/lidar_odometry_utils.cpp) does: + // coordinates from the header scale/offset, timestamp straight out of gps_time, + // lidar id out of user_data. point_format and rgb are not read by + // load_point_cloud(); they are here to check what the writer stores. + struct LazPoint + { + double x, y, z; + double gps_time; + uint16_t intensity; + uint8_t user_data; + uint8_t point_format; + uint16_t rgb[3]; + }; - laszip_BOOL is_compressed = 0; - REQUIRE(laszip_open_reader(reader, path.string().c_str(), &is_compressed) == 0); + std::vector readLaz(const fs::path& path) + { + std::vector out; - laszip_header* header = nullptr; - REQUIRE(laszip_get_header_pointer(reader, &header) == 0); + laszip_POINTER reader = nullptr; + REQUIRE(laszip_create(&reader) == 0); - laszip_point* point = nullptr; - REQUIRE(laszip_get_point_pointer(reader, &point) == 0); + laszip_BOOL is_compressed = 0; + REQUIRE(laszip_open_reader(reader, path.string().c_str(), &is_compressed) == 0); - out.reserve(header->number_of_point_records); - for (laszip_U32 i = 0; i < header->number_of_point_records; ++i) - { - REQUIRE(laszip_read_point(reader) == 0); - LazPoint p{}; - p.x = header->x_offset + header->x_scale_factor * static_cast(point->X); - p.y = header->y_offset + header->y_scale_factor * static_cast(point->Y); - p.z = header->z_offset + header->z_scale_factor * static_cast(point->Z); - p.gps_time = point->gps_time; - p.intensity = point->intensity; - p.user_data = point->user_data; - p.point_format = header->point_data_format; - for (int k = 0; k < 3; ++k) - p.rgb[k] = point->rgb[k]; - out.push_back(p); - } + laszip_header* header = nullptr; + REQUIRE(laszip_get_header_pointer(reader, &header) == 0); - laszip_close_reader(reader); - laszip_destroy(reader); - return out; -} + laszip_point* point = nullptr; + REQUIRE(laszip_get_point_pointer(reader, &point) == 0); -std::vector readLines(const fs::path& path) -{ - std::vector lines; - std::ifstream in(path); - std::string line; - while (std::getline(in, line)) + out.reserve(header->number_of_point_records); + for (laszip_U32 i = 0; i < header->number_of_point_records; ++i) + { + REQUIRE(laszip_read_point(reader) == 0); + LazPoint p{}; + p.x = header->x_offset + header->x_scale_factor * static_cast(point->X); + p.y = header->y_offset + header->y_scale_factor * static_cast(point->Y); + p.z = header->z_offset + header->z_scale_factor * static_cast(point->Z); + p.gps_time = point->gps_time; + p.intensity = point->intensity; + p.user_data = point->user_data; + p.point_format = header->point_data_format; + for (int k = 0; k < 3; ++k) + p.rgb[k] = point->rgb[k]; + out.push_back(p); + } + + laszip_close_reader(reader); + laszip_destroy(reader); + return out; + } + + std::vector readLines(const fs::path& path) { - if (!line.empty()) - lines.push_back(line); + std::vector lines; + std::ifstream in(path); + std::string line; + while (std::getline(in, line)) + { + if (!line.empty()) + lines.push_back(line); + } + return lines; } - return lines; -} } // namespace @@ -157,10 +157,10 @@ TEST_CASE("McapFileReader: PointCloud2 round-trip through every layout") bool carries_laser_id; }; const Case cases[] = { - {"hdmapping_reader_generic.mcap", rosbags::PointCloudLayout::Generic, true}, - {"hdmapping_reader_velodyne.mcap", rosbags::PointCloudLayout::Velodyne, false}, - {"hdmapping_reader_ouster.mcap", rosbags::PointCloudLayout::Ouster, false}, - {"hdmapping_reader_hesai.mcap", rosbags::PointCloudLayout::Hesai, false}, + { "hdmapping_reader_generic.mcap", rosbags::PointCloudLayout::Generic, true }, + { "hdmapping_reader_velodyne.mcap", rosbags::PointCloudLayout::Velodyne, false }, + { "hdmapping_reader_ouster.mcap", rosbags::PointCloudLayout::Ouster, false }, + { "hdmapping_reader_hesai.mcap", rosbags::PointCloudLayout::Hesai, false }, }; for (const auto& c : cases) @@ -231,8 +231,14 @@ TEST_CASE("McapFileReader: IMU round-trip and serial number") REQUIRE_MESSAGE(reader.isOpen(), reader.error()); rosbags::McapFileReader::Callbacks callbacks; - callbacks.onImu = [&](const rosbags::McapImuSample& s) { decoded.push_back(s); }; - callbacks.onSn = [&](uint64_t, const std::string& sn) { serial = sn; }; + callbacks.onImu = [&](const rosbags::McapImuSample& s) + { + decoded.push_back(s); + }; + callbacks.onSn = [&](uint64_t, const std::string& sn) + { + serial = sn; + }; REQUIRE(reader.read(callbacks)); } @@ -319,11 +325,17 @@ TEST_CASE("McapFileReader: the same reader can be read twice") REQUIRE_MESSAGE(reader.isOpen(), reader.error()); rosbags::McapFileReader::Callbacks imu_pass; - imu_pass.onImu = [&](const rosbags::McapImuSample&) { ++imu_count; }; + imu_pass.onImu = [&](const rosbags::McapImuSample&) + { + ++imu_count; + }; REQUIRE(reader.read(imu_pass)); rosbags::McapFileReader::Callbacks lidar_pass; - lidar_pass.onPointCloud = [&](uint64_t, std::vector&& pts) { point_count += pts.size(); }; + lidar_pass.onPointCloud = [&](uint64_t, std::vector&& pts) + { + point_count += pts.size(); + }; REQUIRE(reader.read(lidar_pass)); } @@ -448,14 +460,15 @@ TEST_CASE("MandeyeSessionWriter: with_rgb writes point format 3 with 16-bit colo const auto points = makeReaderPoints(50, 1234.5); std::vector rgb; for (size_t i = 0; i < points.size(); ++i) - rgb.push_back({static_cast(i * 1000), static_cast(65535 - i), static_cast(i)}); + rgb.push_back({ static_cast(i * 1000), static_cast(65535 - i), static_cast(i) }); { rosbags::MandeyeSessionWriter writer(dir, /*with_rgb=*/true); REQUIRE_MESSAGE(writer.isOpen(), writer.error()); REQUIRE(writer.beginChunk(0)); REQUIRE(writer.addPoints(points, rgb)); REQUIRE(writer.addPoints(points)); // no colours given: black - CHECK_FALSE(writer.addPoints(points, std::vector(rgb.begin(), rgb.begin() + 3))); // not one colour per point + CHECK_FALSE(writer.addPoints( + points, std::vector(rgb.begin(), rgb.begin() + 3))); // not one colour per point REQUIRE(writer.endChunk()); } @@ -577,88 +590,87 @@ TEST_CASE("MandeyeSessionWriter: bag -> session round trip preserves points per namespace { -struct Pc2TestField -{ - std::string name; - uint32_t offset; - uint8_t datatype; -}; - -// Builds a sensor_msgs/msg/PointCloud2 CDR payload with an arbitrary field -// description and raw record blob, so a test can present layouts McapWriter -// itself never emits (foreign datatypes, padding gaps, malformed offsets). -std::vector buildPc2Message( - double stamp_s, const std::vector& fields, uint32_t point_step, const std::vector& raw, - bool is_bigendian = false) -{ - CdrWriter w; - const auto ns = static_cast(stamp_s * 1e9); - w.write_i32(static_cast(ns / 1000000000ULL)); - w.write_u32(static_cast(ns % 1000000000ULL)); - w.write_string("test_frame"); - - w.write_u32(1); // height - w.write_u32(point_step ? static_cast(raw.size() / point_step) : 0); // width - - w.write_u32(static_cast(fields.size())); - for (const auto& f : fields) - { - w.write_string(f.name); - w.write_u32(f.offset); - w.write_u8(f.datatype); - w.write_u32(1); // count - } - - w.write_bool(is_bigendian); - w.write_u32(point_step); - w.write_u32(static_cast(raw.size())); // row_step - w.write_u32(static_cast(raw.size())); // data length - w.write_raw(raw.data(), raw.size()); - w.write_bool(true); // is_dense - return w.data(); -} + struct Pc2TestField + { + std::string name; + uint32_t offset; + uint8_t datatype; + }; -template -void poke(std::vector& buffer, size_t offset, T value) -{ - REQUIRE(offset + sizeof(T) <= buffer.size()); - std::memcpy(buffer.data() + offset, &value, sizeof(T)); -} + // Builds a sensor_msgs/msg/PointCloud2 CDR payload with an arbitrary field + // description and raw record blob, so a test can present layouts McapWriter + // itself never emits (foreign datatypes, padding gaps, malformed offsets). + std::vector buildPc2Message( + double stamp_s, + const std::vector& fields, + uint32_t point_step, + const std::vector& raw, + bool is_bigendian = false) + { + CdrWriter w; + const auto ns = static_cast(stamp_s * 1e9); + w.write_i32(static_cast(ns / 1000000000ULL)); + w.write_u32(static_cast(ns % 1000000000ULL)); + w.write_string("test_frame"); -constexpr uint8_t PF_UINT8 = 2; -constexpr uint8_t PF_UINT16 = 4; -constexpr uint8_t PF_UINT32 = 6; -constexpr uint8_t PF_FLOAT32 = 7; -constexpr uint8_t PF_FLOAT64 = 8; + w.write_u32(1); // height + w.write_u32(point_step ? static_cast(raw.size() / point_step) : 0); // width -// The record layout of a real HesaiLidar_ROS_2.0 /hesai/pandar message, as -// measured from a recording: a 4-byte pad after z, so intensity sits at 16 and -// point_step is 48 -- not the packing PointCloudLayout::Hesai writes. -std::vector buildRealHesaiMessage(double stamp_s, size_t n) -{ - constexpr uint32_t kStep = 48; - std::vector raw(kStep * n, 0); - for (size_t i = 0; i < n; ++i) + w.write_u32(static_cast(fields.size())); + for (const auto& f : fields) + { + w.write_string(f.name); + w.write_u32(f.offset); + w.write_u8(f.datatype); + w.write_u32(1); // count + } + + w.write_bool(is_bigendian); + w.write_u32(point_step); + w.write_u32(static_cast(raw.size())); // row_step + w.write_u32(static_cast(raw.size())); // data length + w.write_raw(raw.data(), raw.size()); + w.write_bool(true); // is_dense + return w.data(); + } + + template + void poke(std::vector& buffer, size_t offset, T value) { - const size_t base = i * kStep; - poke(raw, base + 0, 1.0f + static_cast(i)); - poke(raw, base + 4, 2.0f + static_cast(i)); - poke(raw, base + 8, 3.0f + static_cast(i)); - poke(raw, base + 16, static_cast(100 + i)); - poke(raw, base + 24, stamp_s + static_cast(i) * 1e-6); - poke(raw, base + 32, static_cast(i % 32)); + REQUIRE(offset + sizeof(T) <= buffer.size()); + std::memcpy(buffer.data() + offset, &value, sizeof(T)); } - const std::vector fields = { - {"x", 0, PF_FLOAT32}, - {"y", 4, PF_FLOAT32}, - {"z", 8, PF_FLOAT32}, - {"intensity", 16, PF_FLOAT32}, - {"timestamp", 24, PF_FLOAT64}, - {"ring", 32, PF_UINT16}, - }; - return buildPc2Message(stamp_s, fields, kStep, raw); -} + constexpr uint8_t PF_UINT8 = 2; + constexpr uint8_t PF_UINT16 = 4; + constexpr uint8_t PF_UINT32 = 6; + constexpr uint8_t PF_FLOAT32 = 7; + constexpr uint8_t PF_FLOAT64 = 8; + + // The record layout of a real HesaiLidar_ROS_2.0 /hesai/pandar message, as + // measured from a recording: a 4-byte pad after z, so intensity sits at 16 and + // point_step is 48 -- not the packing PointCloudLayout::Hesai writes. + std::vector buildRealHesaiMessage(double stamp_s, size_t n) + { + constexpr uint32_t kStep = 48; + std::vector raw(kStep * n, 0); + for (size_t i = 0; i < n; ++i) + { + const size_t base = i * kStep; + poke(raw, base + 0, 1.0f + static_cast(i)); + poke(raw, base + 4, 2.0f + static_cast(i)); + poke(raw, base + 8, 3.0f + static_cast(i)); + poke(raw, base + 16, static_cast(100 + i)); + poke(raw, base + 24, stamp_s + static_cast(i) * 1e-6); + poke(raw, base + 32, static_cast(i % 32)); + } + + const std::vector fields = { + { "x", 0, PF_FLOAT32 }, { "y", 4, PF_FLOAT32 }, { "z", 8, PF_FLOAT32 }, + { "intensity", 16, PF_FLOAT32 }, { "timestamp", 24, PF_FLOAT64 }, { "ring", 32, PF_UINT16 }, + }; + return buildPc2Message(stamp_s, fields, kStep, raw); + } } // namespace @@ -728,11 +740,7 @@ TEST_CASE("decodePc2: honors each field's datatype rather than assuming float32" } const std::vector fields = { - {"x", 0, PF_FLOAT64}, - {"y", 8, PF_FLOAT64}, - {"z", 16, PF_FLOAT64}, - {"intensity", 24, PF_UINT8}, - {"ring", 25, PF_UINT16}, + { "x", 0, PF_FLOAT64 }, { "y", 8, PF_FLOAT64 }, { "z", 16, PF_FLOAT64 }, { "intensity", 24, PF_UINT8 }, { "ring", 25, PF_UINT16 }, }; const auto msg = buildPc2Message(1000.0, fields, kStep, raw); @@ -764,7 +772,7 @@ TEST_CASE("decodePc2: integer 't' is nanoseconds, float 't' is seconds, both rel poke(raw, 8, 3.0f); poke(raw, 12, 250000000u); // 0.25 s in ns const auto msg = buildPc2Message( - 500.0, {{"x", 0, PF_FLOAT32}, {"y", 4, PF_FLOAT32}, {"z", 8, PF_FLOAT32}, {"t", 12, PF_UINT32}}, kStep, raw); + 500.0, { { "x", 0, PF_FLOAT32 }, { "y", 4, PF_FLOAT32 }, { "z", 8, PF_FLOAT32 }, { "t", 12, PF_UINT32 } }, kStep, raw); const auto points = rosbags::decodePc2(msg.data(), msg.size()); REQUIRE(points.size() == 1); @@ -779,7 +787,7 @@ TEST_CASE("decodePc2: integer 't' is nanoseconds, float 't' is seconds, both rel poke(raw, 8, 3.0f); poke(raw, 12, 0.25f); const auto msg = buildPc2Message( - 500.0, {{"x", 0, PF_FLOAT32}, {"y", 4, PF_FLOAT32}, {"z", 8, PF_FLOAT32}, {"t", 12, PF_FLOAT32}}, kStep, raw); + 500.0, { { "x", 0, PF_FLOAT32 }, { "y", 4, PF_FLOAT32 }, { "z", 8, PF_FLOAT32 }, { "t", 12, PF_FLOAT32 } }, kStep, raw); const auto points = rosbags::decodePc2(msg.data(), msg.size()); REQUIRE(points.size() == 1); @@ -796,7 +804,7 @@ TEST_CASE("decodePc2: intensity is optional") poke(raw, 4, 8.0f); poke(raw, 8, 9.0f); - const auto msg = buildPc2Message(42.0, {{"x", 0, PF_FLOAT32}, {"y", 4, PF_FLOAT32}, {"z", 8, PF_FLOAT32}}, kStep, raw); + const auto msg = buildPc2Message(42.0, { { "x", 0, PF_FLOAT32 }, { "y", 4, PF_FLOAT32 }, { "z", 8, PF_FLOAT32 } }, kStep, raw); std::string warning; const auto points = rosbags::decodePc2(msg.data(), msg.size(), rosbags::Pc2Preset::Auto, &warning); @@ -810,7 +818,7 @@ TEST_CASE("decodePc2: intensity is optional") TEST_CASE("decodePc2: malformed clouds are refused with a reason") { - const std::vector xyz = {{"x", 0, PF_FLOAT32}, {"y", 4, PF_FLOAT32}, {"z", 8, PF_FLOAT32}}; + const std::vector xyz = { { "x", 0, PF_FLOAT32 }, { "y", 4, PF_FLOAT32 }, { "z", 8, PF_FLOAT32 } }; SUBCASE("big-endian is refused rather than misread") { @@ -830,7 +838,7 @@ TEST_CASE("decodePc2: malformed clouds are refused with a reason") SUBCASE("no x/y/z") { - const auto msg = buildPc2Message(1.0, {{"intensity", 0, PF_FLOAT32}}, 4, std::vector(4, 0)); + const auto msg = buildPc2Message(1.0, { { "intensity", 0, PF_FLOAT32 } }, 4, std::vector(4, 0)); std::string warning; CHECK(rosbags::decodePc2(msg.data(), msg.size(), rosbags::Pc2Preset::Auto, &warning).empty()); CHECK(warning.find("x/y/z") != std::string::npos); @@ -865,10 +873,7 @@ TEST_CASE("decodePc2: point timestamps come from the payload header stamp") poke(raw, base + 12, static_cast(i) * 0.01); // "time", relative seconds } const auto msg = buildPc2Message( - kSensorTime, - {{"x", 0, PF_FLOAT32}, {"y", 4, PF_FLOAT32}, {"z", 8, PF_FLOAT32}, {"time", 12, PF_FLOAT64}}, - kStep, - raw); + kSensorTime, { { "x", 0, PF_FLOAT32 }, { "y", 4, PF_FLOAT32 }, { "z", 8, PF_FLOAT32 }, { "time", 12, PF_FLOAT64 } }, kStep, raw); const auto points = rosbags::decodePc2(msg.data(), msg.size()); REQUIRE(points.size() == 3); @@ -893,7 +898,7 @@ TEST_CASE("decodePc2: an absolute per-point timestamp ignores the header stamp e const auto msg = buildPc2Message( kHeaderStamp, - {{"x", 0, PF_FLOAT32}, {"y", 4, PF_FLOAT32}, {"z", 8, PF_FLOAT32}, {"timestamp", 12, PF_FLOAT64}}, + { { "x", 0, PF_FLOAT32 }, { "y", 4, PF_FLOAT32 }, { "z", 8, PF_FLOAT32 }, { "timestamp", 12, PF_FLOAT64 } }, kStep, raw); @@ -905,76 +910,76 @@ TEST_CASE("decodePc2: an absolute per-point timestamp ignores the header stamp e namespace { -// Copies every message of `in` into `out` with chunks of `compression`, small enough to give several chunks. -void recompressMcap(const fs::path& in, const fs::path& out, mcap::Compression compression) -{ - mcap::McapReader reader; - REQUIRE(reader.open(in.string()).ok()); - mcap::McapWriter writer; - mcap::McapWriterOptions options("ros2"); - options.compression = compression; - options.chunkSize = 16 * 1024; - REQUIRE(writer.open(out.string(), options).ok()); - - std::map channels; - const auto onProblem = [](const mcap::Status& status) - { - FAIL(status.message); - }; - for (const auto& view : reader.readMessages(onProblem)) + // Copies every message of `in` into `out` with chunks of `compression`, small enough to give several chunks. + void recompressMcap(const fs::path& in, const fs::path& out, mcap::Compression compression) { - auto it = channels.find(view.channel->id); - if (it == channels.end()) + mcap::McapReader reader; + REQUIRE(reader.open(in.string()).ok()); + mcap::McapWriter writer; + mcap::McapWriterOptions options("ros2"); + options.compression = compression; + options.chunkSize = 16 * 1024; + REQUIRE(writer.open(out.string(), options).ok()); + + std::map channels; + const auto onProblem = [](const mcap::Status& status) { - mcap::Schema schema(view.schema->name, view.schema->encoding, view.schema->data); - writer.addSchema(schema); - mcap::Channel channel(view.channel->topic, view.channel->messageEncoding, schema.id, view.channel->metadata); - writer.addChannel(channel); - it = channels.emplace(view.channel->id, channel.id).first; + FAIL(status.message); + }; + for (const auto& view : reader.readMessages(onProblem)) + { + auto it = channels.find(view.channel->id); + if (it == channels.end()) + { + mcap::Schema schema(view.schema->name, view.schema->encoding, view.schema->data); + writer.addSchema(schema); + mcap::Channel channel(view.channel->topic, view.channel->messageEncoding, schema.id, view.channel->metadata); + writer.addChannel(channel); + it = channels.emplace(view.channel->id, channel.id).first; + } + mcap::Message message = view.message; + message.channelId = it->second; + REQUIRE(writer.write(message).ok()); } - mcap::Message message = view.message; - message.channelId = it->second; - REQUIRE(writer.write(message).ok()); + writer.close(); + reader.close(); } - writer.close(); - reader.close(); -} - -std::vector chunkCompressions(const fs::path& path) -{ - mcap::McapReader reader; - REQUIRE(reader.open(path.string()).ok()); - REQUIRE(reader.readSummary(mcap::ReadSummaryMethod::NoFallbackScan).ok()); - std::vector compressions; - for (const auto& index : reader.chunkIndexes()) - compressions.push_back(index.compression); - reader.close(); - return compressions; -} -struct McapContent -{ - std::vector points; - std::vector imu_timestamps; -}; + std::vector chunkCompressions(const fs::path& path) + { + mcap::McapReader reader; + REQUIRE(reader.open(path.string()).ok()); + REQUIRE(reader.readSummary(mcap::ReadSummaryMethod::NoFallbackScan).ok()); + std::vector compressions; + for (const auto& index : reader.chunkIndexes()) + compressions.push_back(index.compression); + reader.close(); + return compressions; + } -McapContent readMcapContent(const fs::path& path) -{ - McapContent content; - rosbags::McapFileReader reader(path); - REQUIRE_MESSAGE(reader.isOpen(), reader.error()); - rosbags::McapFileReader::Callbacks callbacks; - callbacks.onPointCloud = [&](uint64_t, std::vector&& cloud) + struct McapContent { - content.points.insert(content.points.end(), cloud.begin(), cloud.end()); + std::vector points; + std::vector imu_timestamps; }; - callbacks.onImu = [&](const rosbags::McapImuSample& s) + + McapContent readMcapContent(const fs::path& path) { - content.imu_timestamps.push_back(s.timestamp); - }; - REQUIRE_MESSAGE(reader.read(callbacks), reader.error()); - return content; -} + McapContent content; + rosbags::McapFileReader reader(path); + REQUIRE_MESSAGE(reader.isOpen(), reader.error()); + rosbags::McapFileReader::Callbacks callbacks; + callbacks.onPointCloud = [&](uint64_t, std::vector&& cloud) + { + content.points.insert(content.points.end(), cloud.begin(), cloud.end()); + }; + callbacks.onImu = [&](const rosbags::McapImuSample& s) + { + content.imu_timestamps.push_back(s.timestamp); + }; + REQUIRE_MESSAGE(reader.read(callbacks), reader.error()); + return content; + } } // namespace diff --git a/rosbags/tests/test_mcap_writer.cpp b/rosbags/tests/test_mcap_writer.cpp index 01dc044b..4f74f2a5 100644 --- a/rosbags/tests/test_mcap_writer.cpp +++ b/rosbags/tests/test_mcap_writer.cpp @@ -2,8 +2,8 @@ // header (including , which pulls in plenty of its own) gets a // chance to lock in the project-wide _HAS_STD_BYTE=0 MSVC workaround. #if defined(_MSC_VER) -# undef _HAS_STD_BYTE -# define _HAS_STD_BYTE 1 +#undef _HAS_STD_BYTE +#define _HAS_STD_BYTE 1 #endif #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN @@ -26,53 +26,53 @@ namespace fs = std::filesystem; namespace { -fs::path tempMcapPath(const char* name) -{ - return fs::temp_directory_path() / name; -} - -std::vector makePoints(size_t n, double t0) -{ - std::mt19937 rng(42); - std::uniform_real_distribution coord(-50.0f, 50.0f); - - std::vector points; - points.reserve(n); - for (size_t i = 0; i < n; ++i) + fs::path tempMcapPath(const char* name) { - rosbags::McapPoint p{}; - p.x = coord(rng); - p.y = coord(rng); - p.z = coord(rng); - p.intensity = static_cast(i % 256); - p.ring = static_cast(i % 16); - p.laser_id = static_cast(i % 4); - p.timestamp = t0 + static_cast(i) * 1e-6; - points.push_back(p); + return fs::temp_directory_path() / name; } - return points; -} -// Reads every message on `topic` back out of an mcap file and decodes it with `decode`. -template -std::vector readTopic(const fs::path& path, const std::string& topic, Decode decode) -{ - std::vector out; - mcap::McapReader reader; - auto status = reader.open(path.string()); - REQUIRE(status.ok()); + std::vector makePoints(size_t n, double t0) + { + std::mt19937 rng(42); + std::uniform_real_distribution coord(-50.0f, 50.0f); + + std::vector points; + points.reserve(n); + for (size_t i = 0; i < n; ++i) + { + rosbags::McapPoint p{}; + p.x = coord(rng); + p.y = coord(rng); + p.z = coord(rng); + p.intensity = static_cast(i % 256); + p.ring = static_cast(i % 16); + p.laser_id = static_cast(i % 4); + p.timestamp = t0 + static_cast(i) * 1e-6; + points.push_back(p); + } + return points; + } - auto messages = reader.readMessages(); - for (const auto& view : messages) + // Reads every message on `topic` back out of an mcap file and decodes it with `decode`. + template + std::vector readTopic(const fs::path& path, const std::string& topic, Decode decode) { - if (view.channel->topic != topic) - continue; - auto decoded = decode(reinterpret_cast(view.message.data), view.message.dataSize); - out.push_back(std::move(decoded)); + std::vector out; + mcap::McapReader reader; + auto status = reader.open(path.string()); + REQUIRE(status.ok()); + + auto messages = reader.readMessages(); + for (const auto& view : messages) + { + if (view.channel->topic != topic) + continue; + auto decoded = decode(reinterpret_cast(view.message.data), view.message.dataSize); + out.push_back(std::move(decoded)); + } + reader.close(); + return out; } - reader.close(); - return out; -} } // namespace @@ -89,7 +89,9 @@ TEST_CASE("McapFileWriter: PointCloud2 round-trip (Generic layout)") } const auto clouds = readTopic>( - path, "/lidar_points", [](const uint8_t* d, size_t n) + path, + "/lidar_points", + [](const uint8_t* d, size_t n) { return rosbags::decodePc2(d, n); }); @@ -126,7 +128,9 @@ TEST_CASE("McapFileWriter: PointCloud2 round-trip (Velodyne layout drops laser_i } const auto clouds = readTopic>( - path, "/lidar_points", [](const uint8_t* d, size_t n) + path, + "/lidar_points", + [](const uint8_t* d, size_t n) { return rosbags::decodePc2(d, n); }); @@ -160,7 +164,9 @@ TEST_CASE("McapFileWriter: PointCloud2 round-trip (Ouster layout, relative uint3 } const auto clouds = readTopic>( - path, "/lidar_points", [](const uint8_t* d, size_t n) + path, + "/lidar_points", + [](const uint8_t* d, size_t n) { return rosbags::decodePc2(d, n); }); @@ -195,7 +201,9 @@ TEST_CASE("McapFileWriter: PointCloud2 round-trip (Hesai layout, absolute timest } const auto clouds = readTopic>( - path, "/lidar_points", [](const uint8_t* d, size_t n) + path, + "/lidar_points", + [](const uint8_t* d, size_t n) { return rosbags::decodePc2(d, n); }); @@ -230,7 +238,9 @@ TEST_CASE("McapFileWriter: PointCloud2 round-trip (Canonical layout, float32 tim } const auto clouds = readTopic>( - path, "/lidar_points", [](const uint8_t* d, size_t n) + path, + "/lidar_points", + [](const uint8_t* d, size_t n) { return rosbags::decodePc2(d, n); }); @@ -250,13 +260,15 @@ TEST_CASE("McapFileWriter: PointCloud2 round-trip (Canonical layout, float32 tim // The field table is the point of this layout: float32 `time` (what FAST-LIO/LIO-SAM // Velodyne point types match) and uint32 `t`, both relative to the first point. const auto raw = readTopic>( - path, "/lidar_points", [](const uint8_t* d, size_t n) + path, + "/lidar_points", + [](const uint8_t* d, size_t n) { return std::vector(d, d + n); }); REQUIRE(raw.size() == 1); const std::string bytes(raw.front().begin(), raw.front().end()); - for (const char* name : {"intensity", "ring", "time", "t"}) + for (const char* name : { "intensity", "ring", "time", "t" }) CHECK(bytes.find(name) != std::string::npos); fs::remove(path); @@ -287,7 +299,9 @@ TEST_CASE("McapFileWriter: IMU round-trip") } const auto decoded = readTopic>( - path, "/imu", [](const uint8_t* d, size_t n) + path, + "/imu", + [](const uint8_t* d, size_t n) { return rosbags::decodeImu(d, n); }); @@ -337,7 +351,9 @@ TEST_CASE("McapFileWriter: TF round-trip") } const auto decoded = readTopic>( - path, "/tf", [](const uint8_t* d, size_t n) + path, + "/tf", + [](const uint8_t* d, size_t n) { return rosbags::decodeTf(d, n); }); diff --git a/rosbags/tests/test_ouster_pcap_reader.cpp b/rosbags/tests/test_ouster_pcap_reader.cpp index 722ce725..4d31cf11 100644 --- a/rosbags/tests/test_ouster_pcap_reader.cpp +++ b/rosbags/tests/test_ouster_pcap_reader.cpp @@ -2,8 +2,8 @@ // header (including , which pulls in plenty of its own) gets a // chance to lock in the project-wide _HAS_STD_BYTE=0 MSVC workaround. #if defined(_MSC_VER) -# undef _HAS_STD_BYTE -# define _HAS_STD_BYTE 1 +#undef _HAS_STD_BYTE +#define _HAS_STD_BYTE 1 #endif // No DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN here: test_mcap_writer.cpp (linked into @@ -28,170 +28,175 @@ namespace fs = std::filesystem; namespace { -using pcap_test::putBe16; -using pcap_test::putLe; -using pcap_test::udpFrames; -using pcap_test::writePcap; + using pcap_test::putBe16; + using pcap_test::putLe; + using pcap_test::udpFrames; + using pcap_test::writePcap; -constexpr uint64_t kInitId = 12345; -constexpr uint64_t kSerial = 992612000030; + constexpr uint64_t kInitId = 12345; + constexpr uint64_t kSerial = 992612000030; -// A 4-beam sensor, 4 columns per frame, 2 columns per packet. Beams look -// straight out at 0, 0, +30 and -30 degrees with no beam offset, so the SDK's -// XYZ model reduces to plain spherical coordinates: measurement id 0 points -// along +X, id 1 along -Y. The lidar sits 10 mm above the sensor origin; the -// IMU is turned 90 degrees about Z. -std::string metadataJson(const std::string& profile, const std::string& pixel_data_format = "") -{ - std::string json = R"({ + // A 4-beam sensor, 4 columns per frame, 2 columns per packet. Beams look + // straight out at 0, 0, +30 and -30 degrees with no beam offset, so the SDK's + // XYZ model reduces to plain spherical coordinates: measurement id 0 points + // along +X, id 1 along -Y. The lidar sits 10 mm above the sensor origin; the + // IMU is turned 90 degrees about Z. + std::string metadataJson(const std::string& profile, const std::string& pixel_data_format = "") + { + std::string json = R"({ "sensor_info": {"prod_line": "OS-TEST", "prod_sn": ")" + - std::to_string(kSerial) + R"(", "image_rev": "test", "initialization_id": )" + std::to_string(kInitId) + R"(}, + std::to_string(kSerial) + R"(", "image_rev": "test", "initialization_id": )" + std::to_string(kInitId) + R"(}, "config_params": {"udp_port_lidar": 7502, "udp_port_imu": 7503, "udp_profile_lidar": ")" + - profile + R"(", "udp_profile_imu": "LEGACY"}, + profile + R"(", "udp_profile_imu": "LEGACY"}, "lidar_data_format": {"pixels_per_column": 4, "columns_per_packet": 2, "columns_per_frame": 4, "udp_profile_lidar": ")" + - profile + R"(", "header_type": "STANDARD"}, + profile + R"(", "header_type": "STANDARD"}, "beam_intrinsics": {"beam_altitude_angles": [0, 0, 30, -30], "beam_azimuth_angles": [0, 0, 0, 0], "beam_to_lidar_transform": [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1], "lidar_origin_to_beam_origin_mm": 0}, "lidar_intrinsics": {"lidar_to_sensor_transform": [1,0,0,0, 0,1,0,0, 0,0,1,10, 0,0,0,1]}, "imu_intrinsics": {"imu_to_sensor_transform": [0,-1,0,0, 1,0,0,0, 0,0,1,0, 0,0,0,1]})"; - if (!pixel_data_format.empty()) - json += R"(, "pixel_data_format": )" + pixel_data_format; - return json + "}"; -} + if (!pixel_data_format.empty()) + json += R"(, "pixel_data_format": )" + pixel_data_format; + return json + "}"; + } -rosbags::OusterMetadata parseOrFail(const std::string& json) -{ - rosbags::OusterMetadata m; - std::string error; - const bool ok = rosbags::parseOusterMetadata(json, m, error); - INFO(error); - REQUIRE(ok); - return m; -} + rosbags::OusterMetadata parseOrFail(const std::string& json) + { + rosbags::OusterMetadata m; + std::string error; + const bool ok = rosbags::parseOusterMetadata(json, m, error); + INFO(error); + REQUIRE(ok); + return m; + } -struct Column -{ - uint64_t timestamp_ns; - uint16_t measurement_id; - bool valid; - uint32_t range_mm[4]; - uint8_t reflectivity[4]; - uint16_t rgb[4][3]; // only written into 16-byte (RGB16) pixels -}; - -// One lidar packet for the sensor above: RNG19_RFL8_SIG16_NIR16 (12-byte pixels) -// or, with pixel_bytes = 16, RNG19_RFL8_SIG16_NIR16_RGB16. -std::vector lidarPacket(const Column (&columns)[2], uint64_t init_id = kInitId, size_t pixel_bytes = 12) -{ - const size_t kPixel = pixel_bytes; - const size_t kColumn = 12 + 4 * kPixel; - std::vector p(32 + 2 * kColumn + 32, 0); - putLe(p, 0, 1, 2); // packet type - putLe(p, 4, init_id, 3); - putLe(p, 7, kSerial, 5); - for (size_t c = 0; c < 2; ++c) + struct Column + { + uint64_t timestamp_ns; + uint16_t measurement_id; + bool valid; + uint32_t range_mm[4]; + uint8_t reflectivity[4]; + uint16_t rgb[4][3]; // only written into 16-byte (RGB16) pixels + }; + + // One lidar packet for the sensor above: RNG19_RFL8_SIG16_NIR16 (12-byte pixels) + // or, with pixel_bytes = 16, RNG19_RFL8_SIG16_NIR16_RGB16. + std::vector lidarPacket(const Column (&columns)[2], uint64_t init_id = kInitId, size_t pixel_bytes = 12) { - const size_t col = 32 + c * kColumn; - putLe(p, col, columns[c].timestamp_ns, 8); - putLe(p, col + 8, columns[c].measurement_id, 2); - putLe(p, col + 10, columns[c].valid ? 1 : 0, 2); - for (size_t u = 0; u < 4; ++u) + const size_t kPixel = pixel_bytes; + const size_t kColumn = 12 + 4 * kPixel; + std::vector p(32 + 2 * kColumn + 32, 0); + putLe(p, 0, 1, 2); // packet type + putLe(p, 4, init_id, 3); + putLe(p, 7, kSerial, 5); + for (size_t c = 0; c < 2; ++c) { - const size_t px = col + 12 + u * kPixel; - // Bit 19 set on purpose: reserved/bloom bits must not leak into the range. - putLe(p, px, columns[c].range_mm[u] | (1u << 19) | (uint32_t{columns[c].reflectivity[u]} << 24), 4); - putLe(p, px + 4, 0xBEEF, 2); // signal - if (pixel_bytes >= 14) + const size_t col = 32 + c * kColumn; + putLe(p, col, columns[c].timestamp_ns, 8); + putLe(p, col + 8, columns[c].measurement_id, 2); + putLe(p, col + 10, columns[c].valid ? 1 : 0, 2); + for (size_t u = 0; u < 4; ++u) { - for (size_t k = 0; k < 3; ++k) - putLe(p, px + 8 + 2 * k, columns[c].rgb[u][k], 2); + const size_t px = col + 12 + u * kPixel; + // Bit 19 set on purpose: reserved/bloom bits must not leak into the range. + putLe(p, px, columns[c].range_mm[u] | (1u << 19) | (uint32_t{ columns[c].reflectivity[u] } << 24), 4); + putLe(p, px + 4, 0xBEEF, 2); // signal + if (pixel_bytes >= 14) + { + for (size_t k = 0; k < 3; ++k) + putLe(p, px + 8 + 2 * k, columns[c].rgb[u][k], 2); + } } } + return p; } - return p; -} -std::vector legacyImuPacket(uint64_t gyro_ts_ns, const float (&acc_g)[3], const float (&gyro_dps)[3]) -{ - std::vector p(48, 0); - putLe(p, 0, 1, 8); // system timestamp: a different clock, must be ignored - putLe(p, 8, gyro_ts_ns - 1000, 8); - putLe(p, 16, gyro_ts_ns, 8); - for (int i = 0; i < 3; ++i) + std::vector legacyImuPacket(uint64_t gyro_ts_ns, const float (&acc_g)[3], const float (&gyro_dps)[3]) { - std::memcpy(&p[24 + 4 * i], &acc_g[i], 4); - std::memcpy(&p[36 + 4 * i], &gyro_dps[i], 4); + std::vector p(48, 0); + putLe(p, 0, 1, 8); // system timestamp: a different clock, must be ignored + putLe(p, 8, gyro_ts_ns - 1000, 8); + putLe(p, 16, gyro_ts_ns, 8); + for (int i = 0; i < 3; ++i) + { + std::memcpy(&p[24 + 4 * i], &acc_g[i], 4); + std::memcpy(&p[36 + 4 * i], &gyro_dps[i], 4); + } + return p; } - return p; -} -struct ImuMeasurement -{ - uint64_t timestamp_ns; - bool valid; - float acc_ms2[3]; - float gyro_rads[3]; -}; - -// ACCEL32_GYRO32_NMEA with two measurements per packet. -std::vector accel32Gyro32NmeaImuPacket(const ImuMeasurement (&measurements)[2], uint64_t init_id = kInitId) -{ - std::vector p(32 + 100 + 2 * 36 + 32, 0); - putLe(p, 0, 2, 2); // packet type - putLe(p, 4, init_id, 3); - putLe(p, 7, kSerial, 5); - for (size_t i = 0; i < 2; ++i) + struct ImuMeasurement + { + uint64_t timestamp_ns; + bool valid; + float acc_ms2[3]; + float gyro_rads[3]; + }; + + // ACCEL32_GYRO32_NMEA with two measurements per packet. + std::vector accel32Gyro32NmeaImuPacket(const ImuMeasurement (&measurements)[2], uint64_t init_id = kInitId) { - const size_t m = 32 + 100 + i * 36; - putLe(p, m, measurements[i].timestamp_ns, 8); - putLe(p, m + 8, 31 + 32 * i, 2); - putLe(p, m + 10, measurements[i].valid ? 1 : 0, 2); - for (int k = 0; k < 3; ++k) + std::vector p(32 + 100 + 2 * 36 + 32, 0); + putLe(p, 0, 2, 2); // packet type + putLe(p, 4, init_id, 3); + putLe(p, 7, kSerial, 5); + for (size_t i = 0; i < 2; ++i) { - std::memcpy(&p[m + 12 + 4 * k], &measurements[i].acc_ms2[k], 4); - std::memcpy(&p[m + 24 + 4 * k], &measurements[i].gyro_rads[k], 4); + const size_t m = 32 + 100 + i * 36; + putLe(p, m, measurements[i].timestamp_ns, 8); + putLe(p, m + 8, 31 + 32 * i, 2); + putLe(p, m + 10, measurements[i].valid ? 1 : 0, 2); + for (int k = 0; k < 3; ++k) + { + std::memcpy(&p[m + 12 + 4 * k], &measurements[i].acc_ms2[k], 4); + std::memcpy(&p[m + 24 + 4 * k], &measurements[i].gyro_rads[k], 4); + } } + return p; } - return p; -} -struct ReadResult -{ - std::vector points; - std::vector> rgb; - std::vector imu; - rosbags::OusterPcapStats stats; -}; - -ReadResult readAll(const fs::path& path, const rosbags::OusterMetadata& meta, const rosbags::OusterPcapReaderOptions& options = {}) -{ - rosbags::OusterPcapReader reader(path, meta, options); - INFO(reader.error()); - REQUIRE(reader.isOpen()); - ReadResult r; - rosbags::OusterPcapReader::Callbacks callbacks; - callbacks.onPoints = [&](std::vector&& points, std::vector>&& rgb) + struct ReadResult { - if (!rgb.empty()) - REQUIRE(rgb.size() == points.size()); - r.points.insert(r.points.end(), points.begin(), points.end()); - r.rgb.insert(r.rgb.end(), rgb.begin(), rgb.end()); + std::vector points; + std::vector> rgb; + std::vector imu; + rosbags::OusterPcapStats stats; }; - callbacks.onImu = [&](const rosbags::McapImuSample& s) + + ReadResult readAll(const fs::path& path, const rosbags::OusterMetadata& meta, const rosbags::OusterPcapReaderOptions& options = {}) { - r.imu.push_back(s); - }; - REQUIRE(reader.read(callbacks)); - r.stats = reader.stats(); - return r; -} + rosbags::OusterPcapReader reader(path, meta, options); + INFO(reader.error()); + REQUIRE(reader.isOpen()); + ReadResult r; + rosbags::OusterPcapReader::Callbacks callbacks; + callbacks.onPoints = [&](std::vector&& points, std::vector>&& rgb) + { + if (!rgb.empty()) + REQUIRE(rgb.size() == points.size()); + r.points.insert(r.points.end(), points.begin(), points.end()); + r.rgb.insert(r.rgb.end(), rgb.begin(), rgb.end()); + }; + callbacks.onImu = [&](const rosbags::McapImuSample& s) + { + r.imu.push_back(s); + }; + REQUIRE(reader.read(callbacks)); + r.stats = reader.stats(); + return r; + } -const Column kColumns[2] = { - {5'000'000'000, 0, true, {1000, 0, 2000, 3000}, {10, 0, 30, 40}, {{100, 200, 300}, {1, 2, 3}, {400, 500, 600}, {0xFFFF, 0xFFFF, 0xFFFF}}}, - {5'000'100'000, 1, true, {0, 2000, 0, 0}, {0, 20, 0, 0}, {{0, 0, 0}, {7, 8, 9}, {0, 0, 0}, {0, 0, 0}}}, -}; + const Column kColumns[2] = { + { 5'000'000'000, + 0, + true, + { 1000, 0, 2000, 3000 }, + { 10, 0, 30, 40 }, + { { 100, 200, 300 }, { 1, 2, 3 }, { 400, 500, 600 }, { 0xFFFF, 0xFFFF, 0xFFFF } } }, + { 5'000'100'000, 1, true, { 0, 2000, 0, 0 }, { 0, 20, 0, 0 }, { { 0, 0, 0 }, { 7, 8, 9 }, { 0, 0, 0 }, { 0, 0, 0 } } }, + }; } // namespace @@ -216,7 +221,7 @@ TEST_CASE("parseOusterMetadata: profile table, pixel_data_format, and refusals") CHECK(m.pixel_bytes == 16); CHECK(m.rgb_width == 16); CHECK(m.rgb_float16); - CHECK(m.rgb_start_bit == std::array{64, 80, 96}); + CHECK(m.rgb_start_bit == std::array{ 64, 80, 96 }); } SUBCASE("pixel_data_format describes a profile no table knows") { @@ -236,7 +241,7 @@ TEST_CASE("parseOusterMetadata: profile table, pixel_data_format, and refusals") CHECK(m.reflectivity_start_bit == 24); CHECK(m.rgb_width == 16); CHECK(m.rgb_float16); - CHECK(m.rgb_start_bit == std::array{112, 128, 144}); // rgb_r, not rgb_r1 + CHECK(m.rgb_start_bit == std::array{ 112, 128, 144 }); // rgb_r, not rgb_r1 } SUBCASE("an unknown profile without pixel_data_format is refused by name") { @@ -279,10 +284,10 @@ TEST_CASE("OusterPcapReader: points follow the SDK XYZ model, from fragmented da double t; }; const Expected expected[4] = { - {1.0, 0.0, 0.010, 10, 0, 5.0}, // id 0, level beam: +X, lifted by lidar_to_sensor - {2.0 * c30, 0.0, 2.0 * s30 + 0.010, 30, 2, 5.0}, - {3.0 * c30, 0.0, -3.0 * s30 + 0.010, 40, 3, 5.0}, - {0.0, -2.0, 0.010, 20, 1, 5.0001}, // id 1 of 4: a quarter turn clockwise, -Y + { 1.0, 0.0, 0.010, 10, 0, 5.0 }, // id 0, level beam: +X, lifted by lidar_to_sensor + { 2.0 * c30, 0.0, 2.0 * s30 + 0.010, 30, 2, 5.0 }, + { 3.0 * c30, 0.0, -3.0 * s30 + 0.010, 40, 3, 5.0 }, + { 0.0, -2.0, 0.010, 20, 1, 5.0001 }, // id 1 of 4: a quarter turn clockwise, -Y }; for (size_t i = 0; i < 4; ++i) { @@ -317,7 +322,7 @@ TEST_CASE("OusterPcapReader: an RGB profile hands each point's colour words alon REQUIRE(r.points.size() == 4); REQUIRE(r.rgb.size() == 4); // Same point order as the 12-byte profile; zero-range pixels drop their colour too. - const std::array expected[4] = {{100, 200, 300}, {400, 500, 600}, {0xFFFF, 0xFFFF, 0xFFFF}, {7, 8, 9}}; + const std::array expected[4] = { { 100, 200, 300 }, { 400, 500, 600 }, { 0xFFFF, 0xFFFF, 0xFFFF }, { 7, 8, 9 } }; for (size_t i = 0; i < 4; ++i) { CAPTURE(i); @@ -330,7 +335,7 @@ TEST_CASE("OusterPcapReader: LEGACY IMU is rotated into the sensor frame, deg/s { const auto meta = parseOrFail(metadataJson("RNG19_RFL8_SIG16_NIR16")); const fs::path path = fs::temp_directory_path() / "hdmapping_ouster_reader_imu.pcap"; - writePcap(path, udpFrames(legacyImuPacket(7'000'000'000, {1.0f, 0.0f, 0.0f}, {90.0f, 0.0f, 0.0f}), 7503, 2)); + writePcap(path, udpFrames(legacyImuPacket(7'000'000'000, { 1.0f, 0.0f, 0.0f }, { 90.0f, 0.0f, 0.0f }), 7503, 2)); const auto r = readAll(path, meta); REQUIRE(r.imu.size() == 1); @@ -356,8 +361,8 @@ TEST_CASE("OusterPcapReader: ACCEL32_GYRO32_NMEA IMU is rotated into the sensor const fs::path path = fs::temp_directory_path() / "hdmapping_ouster_reader_imu_nmea.pcap"; const ImuMeasurement measurements[2] = { - {7'000'000'000, true, {9.80665f, 0.0f, 0.0f}, {0.5f, 0.0f, 0.0f}}, - {7'001'562'500, false, {1.0f, 2.0f, 3.0f}, {1.0f, 2.0f, 3.0f}}, + { 7'000'000'000, true, { 9.80665f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f } }, + { 7'001'562'500, false, { 1.0f, 2.0f, 3.0f }, { 1.0f, 2.0f, 3.0f } }, }; std::vector> frames = udpFrames(accel32Gyro32NmeaImuPacket(measurements), 7503, 1); const auto foreign = udpFrames(accel32Gyro32NmeaImuPacket(measurements, kInitId + 1), 7503, 2); @@ -394,7 +399,7 @@ TEST_CASE("OusterPcapReader: foreign, mis-sized and unrelated packets are counte truncated.resize(truncated.size() - 4); add(udpFrames(truncated, 7502, 2)); add(udpFrames(std::vector(16, 0), 9999, 3)); - add({udpFrames(lidarPacket(kColumns), 7502, 4, 64).front()}); // a fragment whose siblings never arrive + add({ udpFrames(lidarPacket(kColumns), 7502, 4, 64).front() }); // a fragment whose siblings never arrive writePcap(path, frames); const auto r = readAll(path, meta); diff --git a/rosbags/tests/test_ros1_bag.cpp b/rosbags/tests/test_ros1_bag.cpp index d68204e0..7c2c6c2b 100644 --- a/rosbags/tests/test_ros1_bag.cpp +++ b/rosbags/tests/test_ros1_bag.cpp @@ -1,8 +1,8 @@ // See rosbags/McapWriter.h for why this needs to come before any standard // header (including ) on MSVC. #if defined(_MSC_VER) -# undef _HAS_STD_BYTE -# define _HAS_STD_BYTE 1 +#undef _HAS_STD_BYTE +#define _HAS_STD_BYTE 1 #endif #include @@ -20,33 +20,33 @@ namespace fs = std::filesystem; namespace { -rosbags::Ros1PointCloud2 makeCloud(uint32_t seq, uint64_t stamp_ns, uint32_t n) -{ - rosbags::Ros1PointCloud2 c; - c.seq = seq; - c.stamp_ns = stamp_ns; - c.frame_id = "lidar"; - c.width = n; - c.fields = {{"x", 0, 7, 1}, {"y", 4, 7, 1}, {"z", 8, 7, 1}, {"ring", 12, 4, 1}}; - c.point_step = 16; - c.row_step = n * c.point_step; - c.data.resize(c.row_step); - for (size_t i = 0; i < c.data.size(); ++i) - c.data[i] = static_cast((i * 7 + seq) & 0xff); - return c; -} + rosbags::Ros1PointCloud2 makeCloud(uint32_t seq, uint64_t stamp_ns, uint32_t n) + { + rosbags::Ros1PointCloud2 c; + c.seq = seq; + c.stamp_ns = stamp_ns; + c.frame_id = "lidar"; + c.width = n; + c.fields = { { "x", 0, 7, 1 }, { "y", 4, 7, 1 }, { "z", 8, 7, 1 }, { "ring", 12, 4, 1 } }; + c.point_step = 16; + c.row_step = n * c.point_step; + c.data.resize(c.row_step); + for (size_t i = 0; i < c.data.size(); ++i) + c.data[i] = static_cast((i * 7 + seq) & 0xff); + return c; + } -rosbags::Ros1Imu makeImu(uint32_t seq, uint64_t stamp_ns) -{ - rosbags::Ros1Imu m; - m.seq = seq; - m.stamp_ns = stamp_ns; - m.frame_id = "lidar"; - m.angular_velocity[0] = 0.1 * seq; - m.angular_velocity[2] = -0.5; - m.linear_acceleration[2] = 9.81; - return m; -} + rosbags::Ros1Imu makeImu(uint32_t seq, uint64_t stamp_ns) + { + rosbags::Ros1Imu m; + m.seq = seq; + m.stamp_ns = stamp_ns; + m.frame_id = "lidar"; + m.angular_velocity[0] = 0.1 * seq; + m.angular_velocity[2] = -0.5; + m.linear_acceleration[2] = 9.81; + return m; + } } // namespace @@ -98,12 +98,8 @@ TEST_CASE("Ros1Bag: writer output reads back message for message across chunks") rosbags::Ros1BagWriter writer(path, 4096); REQUIRE(writer.isOpen()); const auto lidar = writer.addConnection( - "/lidar/pointcloud", - rosbags::kRos1PointCloud2Type, - rosbags::kRos1PointCloud2Md5, - rosbags::kRos1PointCloud2Definition); - const auto imu = writer.addConnection( - "/lidar/imu", rosbags::kRos1ImuType, rosbags::kRos1ImuMd5, rosbags::kRos1ImuDefinition); + "/lidar/pointcloud", rosbags::kRos1PointCloud2Type, rosbags::kRos1PointCloud2Md5, rosbags::kRos1PointCloud2Definition); + const auto imu = writer.addConnection("/lidar/imu", rosbags::kRos1ImuType, rosbags::kRos1ImuMd5, rosbags::kRos1ImuDefinition); for (uint32_t i = 0; i < 20; ++i) { const uint64_t t = t0 + i * 100'000'000ULL; @@ -207,7 +203,7 @@ TEST_CASE("Ros1BagFileWriter -> Ros1BagFileReader: canonical layout and IMU roun } std::vector imu; for (int k = 0; k < 120; ++k) - imu.push_back({t0 + 0.0025 * k, 0.01f * k, -0.02f, 0.3f, 0.1f, -0.2f, 9.81f}); + imu.push_back({ t0 + 0.0025 * k, 0.01f * k, -0.02f, 0.3f, 0.1f, -0.2f, 9.81f }); { rosbags::McapWriterOptions options; @@ -292,7 +288,7 @@ TEST_CASE("Ros1BagFileReader: livox_ros_driver CustomMsg becomes points with rin put(&nsec, 4); put(&frame_len, 4); const uint32_t point_num = 3, n_points = 3; - const uint8_t lidar_id = 192, rsvd[3] = {0, 0, 0}; + const uint8_t lidar_id = 192, rsvd[3] = { 0, 0, 0 }; put(&timebase, 8); put(&point_num, 4); put(&lidar_id, 1); @@ -301,7 +297,7 @@ TEST_CASE("Ros1BagFileReader: livox_ros_driver CustomMsg becomes points with rin for (uint32_t i = 0; i < 3; ++i) { const uint32_t offset_time = i * 1000; - const float xyz[3] = {1.0f + i, 2.0f, 3.0f}; + const float xyz[3] = { 1.0f + i, 2.0f, 3.0f }; const uint8_t reflectivity = static_cast(10 * i), tag = 0x10, line = static_cast(i); put(&offset_time, 4); put(xyz, 12); diff --git a/scripts/README.md b/scripts/README.md index 69da329f..2af47376 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -7,6 +7,8 @@ * `pybind` * `shared` * `raylib_widgets` + * `rosbags` + * `recording_sources` * `run_check_clang_format.py` — checks whether running `clang-format` would modify any tracked project files. The script runs `run_clang_format.py` and then checks the Git working tree for changes. If formatting would produce changes, the check fails and lists the affected files. diff --git a/scripts/run_check_clang_format.py b/scripts/run_check_clang_format.py index 61170116..c7f3e05d 100644 --- a/scripts/run_check_clang_format.py +++ b/scripts/run_check_clang_format.py @@ -13,6 +13,8 @@ os.path.join(PROJECT_DIRECTORY, "pybind"), os.path.join(PROJECT_DIRECTORY, "shared"), os.path.join(PROJECT_DIRECTORY, "raylib_widgets"), + os.path.join(PROJECT_DIRECTORY, "rosbags"), + os.path.join(PROJECT_DIRECTORY, "recording_sources"), ] FILE_EXTENSIONS = [ diff --git a/scripts/run_clang_format.py b/scripts/run_clang_format.py index c7293cf8..906c67e2 100644 --- a/scripts/run_clang_format.py +++ b/scripts/run_clang_format.py @@ -10,7 +10,9 @@ os.path.join(PROJECT_DIRECTORY, 'apps'), os.path.join(PROJECT_DIRECTORY, 'pybind'), os.path.join(PROJECT_DIRECTORY, 'shared'), - os.path.join(PROJECT_DIRECTORY, 'raylib_widgets')] + os.path.join(PROJECT_DIRECTORY, 'raylib_widgets'), + os.path.join(PROJECT_DIRECTORY, 'rosbags'), + os.path.join(PROJECT_DIRECTORY, 'recording_sources')] FILE_EXTENSIONS = ['.cpp', '.hpp', From 4d5c197253ee861cfe8dddbb63137c2ee84c793f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pe=C5=82ka?= Date: Wed, 2 Dec 2026 20:05:50 +0100 Subject: [PATCH 20/21] rosbags tests: close the capture before removing it The zstd test of PcapUdpReader read the plain capture through an ifstream that stayed open until the end of the test case, so removing the file threw on Windows ("being used by another process") and the test failed there. Linux allows removing an open file. Co-Authored-By: Claude Opus 5.5 --- rosbags/tests/test_pcap_udp_reader.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/rosbags/tests/test_pcap_udp_reader.cpp b/rosbags/tests/test_pcap_udp_reader.cpp index 0bee486b..10407dd9 100644 --- a/rosbags/tests/test_pcap_udp_reader.cpp +++ b/rosbags/tests/test_pcap_udp_reader.cpp @@ -107,6 +107,7 @@ TEST_CASE("PcapUdpReader: a zstd-compressed capture reads the same as the plain pcap_test::writePcap(plain, sampleFrames()); std::ifstream in(plain, std::ios::binary); const std::vector bytes((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + in.close(); // Windows cannot remove a file that is still open std::vector packed(ZSTD_compressBound(bytes.size())); const size_t packed_size = ZSTD_compress(packed.data(), packed.size(), bytes.data(), bytes.size(), 3); REQUIRE_FALSE(ZSTD_isError(packed_size)); From 4348c13a1fcdecfc76cfaa3a1774e0fc170eea94 Mon Sep 17 00:00:00 2001 From: Michal Date: Wed, 2 Dec 2026 23:42:26 +0100 Subject: [PATCH 21/21] rosbags: read MCAP through an ifstream to handle files over 2 GB on Windows mcap::FileReader seeks with fseek((long)offset) and sizes the file with ftell. long is 32 bits on Windows, so past 2 GB it reads from the wrong offset, takes garbage as a record length and throws std::bad_alloc (seen in lidar_odometry_step_1 loading a large .mcap). Open the file as a std::ifstream and use mcap's stream reader, whose offsets are 64-bit. Opening from std::filesystem::path also handles non-ASCII paths. Co-Authored-By: Claude Opus 5.5 --- rosbags/McapReader.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/rosbags/McapReader.cpp b/rosbags/McapReader.cpp index 2c718f2c..a5200049 100644 --- a/rosbags/McapReader.cpp +++ b/rosbags/McapReader.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -31,6 +32,9 @@ namespace rosbags struct McapFileReader::Impl { + // Read through an ifstream, not mcap's FILE* reader: that one seeks with fseek((long)offset), which is 32 bits + // on Windows and breaks past 2 GB. Declared before `reader`, which reads from it until it is destroyed. + std::ifstream stream; mcap::McapReader reader; McapReaderOptions options; ResolvedTopics resolved; @@ -98,7 +102,13 @@ namespace rosbags { impl_->options = options; - auto status = impl_->reader.open(path.string()); + impl_->stream.open(path, std::ios::binary); + if (!impl_->stream.is_open()) + { + impl_->error = "failed to open " + path.string(); + return; + } + auto status = impl_->reader.open(impl_->stream); if (!status.ok()) { impl_->error = "failed to open " + path.string() + ": " + status.message;