From 2761b81ce2c2ba6b283bf7d8f8d3422ab9ad2c7f Mon Sep 17 00:00:00 2001 From: Dariusz Lubomski Date: Tue, 1 Dec 2026 17:17:17 +0100 Subject: [PATCH 1/5] Filter exact zero XYZ returns from Livox Cartesian High recordings Report pre-decimation counts for each discovered head, including silent heads. Keep the existing LiDAR plugin ABI and support older recorder browsers. --- README.md | 24 ++++++++- code/lidars/LidarChunk.h | 35 +++++++++++++ code/lidars/LidarImplementation.cpp | 11 +++- code/lidars/ZeroPointStats.h | 72 +++++++++++++++++++++++++++ code/lidars/livoxsdk2/LivoxClient.cpp | 64 +++++++++++++++++------- code/lidars/livoxsdk2/LivoxClient.h | 10 +++- code/main.cpp | 24 +++++---- code/save_laz.cpp | 7 ++- html/index.htm | 16 ++++-- 9 files changed, 223 insertions(+), 40 deletions(-) create mode 100644 code/lidars/LidarChunk.h create mode 100644 code/lidars/ZeroPointStats.h diff --git a/README.md b/README.md index 9a57dd2..176e8df 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,9 @@ sudo make package The package will be available in the build directory. -# Choosing Lidar SDK +# LiDAR configuration + +## Choosing Lidar SDK The software supports different SDKs for the Lidar: | SDK | Variable | Description | @@ -225,6 +227,26 @@ You can set the SDK to use in two ways: } ``` +## Livox zero-return filter + +The Livox plugin records high-resolution Cartesian packets (Cartesian High). +It skips Cartesian Low and spherical packets in both filter modes. By default, +the plugin drops exact raw `(0, 0, 0)` returns before buffering. To keep those +returns, add `"drop_zero_xyz": false` to `/media/usb/mandeye_config.json` and +restart the controller. + +The web status table shows whether the filter is on or off. If the controller +loads an older Livox plugin, it shows `N/A` and recording continues with that +plugin's unfiltered output. Install the matching `liblivox2_lib.so` to enable +the filter and its diagnostics. + +Each Livox `statusNNNN.json` from the updated plugin reports `zero_xyz` counts +and percentages for eligible Cartesian High returns before filtering and +decimation, in total and per head, even when filtering is off. A discovered +head that sent no points in the chunk has `input_points` equal to zero and +`zero_percent` equal to `null`. `filtered_points` counts the returns removed by +the filter. Decimation uses the number of points left in the buffer. + # Installation and usage of the package To install the package, you need to copy it to the target device and install it with `dpkg`: ```bash diff --git a/code/lidars/LidarChunk.h b/code/lidars/LidarChunk.h new file mode 100644 index 0000000..c65ece4 --- /dev/null +++ b/code/lidars/LidarChunk.h @@ -0,0 +1,35 @@ +#pragma once + +#include "lidars/BaseLidarClient.h" +#include "lidars/ZeroPointStats.h" +#include +#include + +namespace mandeye +{ + +struct LidarChunk +{ + LidarPointsBufferPtr points; + LidarIMUBufferPtr imu; + std::optional zeroPoints; +}; + +// Keep chunk diagnostics optional so previously built LiDAR plugins retain their BaseLidarClient ABI. +class ChunkedLidarClient : public BaseLidarClient +{ +public: + virtual LidarChunk retrieveChunk() = 0; +}; + +inline LidarChunk retrieveChunk(BaseLidarClient& client) +{ + if(auto* chunked = dynamic_cast(&client)) + { + return chunked->retrieveChunk(); + } + auto [points, imu] = client.retrieveData(); + return {std::move(points), std::move(imu), std::nullopt}; +} + +} // namespace mandeye diff --git a/code/lidars/LidarImplementation.cpp b/code/lidars/LidarImplementation.cpp index eb60bcc..52418ba 100644 --- a/code/lidars/LidarImplementation.cpp +++ b/code/lidars/LidarImplementation.cpp @@ -1,4 +1,5 @@ #include "LidarImplementations.h" +#include "lidars/LidarChunk.h" #include "lidars/dummy/ButterLidar.h" #include @@ -93,7 +94,13 @@ BaseLidarClientPtr createLidarClient(const std::string& lidarType, const nlohman { try { - return make_dynamic_client("liblivox2_lib.so", "create_livox_client", "destroy_livox_client"); + auto client = make_dynamic_client("liblivox2_lib.so", "create_livox_client", "destroy_livox_client"); + if(!dynamic_cast(client.get())) + { + std::cerr << "This Livox plugin records unfiltered points. Update liblivox2_lib.so to enable the zero-return filter." << std::endl; + } + client->Init(config); + return client; } catch(const std::exception& e) { @@ -150,4 +157,4 @@ BaseLidarClientPtr createLidarClient(const std::string& lidarType, const nlohman } } -} // namespace mandeye \ No newline at end of file +} // namespace mandeye diff --git a/code/lidars/ZeroPointStats.h b/code/lidars/ZeroPointStats.h new file mode 100644 index 0000000..e40ce0c --- /dev/null +++ b/code/lidars/ZeroPointStats.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace mandeye +{ + +inline bool dropZeroXyzFromConfig(const nlohmann::json& config) +{ + const auto setting = config.find("drop_zero_xyz"); + return setting == config.end() || !setting->is_boolean() || setting->get(); +} + +struct ZeroPointCounts +{ + uint64_t inputPoints{0}; + uint64_t zeroPoints{0}; + + bool record(int32_t x, int32_t y, int32_t z, bool filterEnabled) + { + const bool zero = x == 0 && y == 0 && z == 0; + ++inputPoints; + zeroPoints += zero; + return zero && filterEnabled; + } + + nlohmann::json produceStatus(bool filterEnabled) const + { + return { + {"input_points", inputPoints}, + {"zero_points", zeroPoints}, + {"zero_percent", inputPoints ? nlohmann::json(100.0 * zeroPoints / inputPoints) : nlohmann::json(nullptr)}, + {"filtered_points", filterEnabled ? zeroPoints : 0}, + }; + } +}; + +struct ZeroPointStats +{ + struct Head : ZeroPointCounts + { + std::string serialNumber; + }; + + bool filterEnabled{true}; + std::map byHandle; + + nlohmann::json produceStatus() const + { + ZeroPointCounts total; + auto heads = nlohmann::json::array(); + for(const auto& [handle, head] : byHandle) + { + total.inputPoints += head.inputPoints; + total.zeroPoints += head.zeroPoints; + auto entry = head.produceStatus(filterEnabled); + entry["handle"] = handle; + entry["serial_number"] = head.serialNumber.empty() ? nlohmann::json(nullptr) : nlohmann::json(head.serialNumber); + heads.push_back(std::move(entry)); + } + auto status = total.produceStatus(filterEnabled); + status["filter_enabled"] = filterEnabled; + status["by_head"] = std::move(heads); + return status; + } +}; + +} // namespace mandeye diff --git a/code/lidars/livoxsdk2/LivoxClient.cpp b/code/lidars/livoxsdk2/LivoxClient.cpp index 73c507f..6b681b0 100644 --- a/code/lidars/livoxsdk2/LivoxClient.cpp +++ b/code/lidars/livoxsdk2/LivoxClient.cpp @@ -32,10 +32,16 @@ std::string ReplaceAll(std::string str, const std::string& from, const std::stri return str; } +void LivoxClient::Init(const nlohmann::json& config) +{ + m_dropZeroXyz = dropZeroXyzFromConfig(config); +} + nlohmann::json LivoxClient::produceStatus() { nlohmann::json data; data["init_success"] = init_succes; + data["drop_zero_xyz"] = m_dropZeroXyz; data["is_synced"] = isSynced(); data["data_flowing"] = isDataFlowing(); if(!m_LivoxLidarInfo.empty()) @@ -163,6 +169,7 @@ void LivoxClient::startLog() std::lock_guard lcK2(m_bufferImuMutex); m_bufferLivoxPtr = std::make_shared(); m_bufferIMUPtr = std::make_shared(); + m_zeroPointsByHandle.clear(); } void LivoxClient::stopLog() @@ -171,17 +178,33 @@ void LivoxClient::stopLog() std::lock_guard lcK2(m_bufferImuMutex); m_bufferLivoxPtr = nullptr; m_bufferIMUPtr = nullptr; + m_zeroPointsByHandle.clear(); } std::pair LivoxClient::retrieveData() { - std::lock_guard lck1(m_bufferLidarMutex); - std::lock_guard lck2(m_bufferImuMutex); - LidarPointsBufferPtr returnPointerLidar{std::make_shared()}; - LidarIMUBufferPtr returnPointerImu{std::make_shared()}; - std::swap(m_bufferIMUPtr, returnPointerImu); - std::swap(m_bufferLivoxPtr, returnPointerLidar); - return std::pair(returnPointerLidar, returnPointerImu); + auto chunk = retrieveChunk(); + return {std::move(chunk.points), std::move(chunk.imu)}; +} + +LidarChunk LivoxClient::retrieveChunk() +{ + LidarChunk chunk{std::make_shared(), std::make_shared(), ZeroPointStats{}}; + chunk.zeroPoints->filterEnabled = m_dropZeroXyz; + { + std::lock_guard lck1(m_bufferLidarMutex); + std::lock_guard lck2(m_bufferImuMutex); + std::swap(m_bufferLivoxPtr, chunk.points); + std::swap(m_bufferIMUPtr, chunk.imu); + std::swap(m_zeroPointsByHandle, chunk.zeroPoints->byHandle); + } + + std::lock_guard lock(m_lidarInfoMutex); + for(const auto& [handle, serial] : m_handleToSerialNumber) + { + chunk.zeroPoints->byHandle[handle].serialNumber = serial; + } + return chunk; } void LivoxClient::testThread() { @@ -289,22 +312,25 @@ void LivoxClient::PointCloudCallback(uint32_t handle, const uint8_t dev_type, Li return; } auto& buffer = this_ptr->m_bufferLivoxPtr; - // buffer->resize(buffer->size() + data->dot_num); + auto& counts = this_ptr->m_zeroPointsByHandle[handle]; for(uint32_t i = 0; i < data->dot_num; i++) { - LidarPoint point; - point.x = 0.001 * p_point_data[i].x; - point.y = 0.001 * p_point_data[i].y; - point.z = 0.001 * p_point_data[i].z; - point.intensity = p_point_data[i].reflectivity; - point.tag = p_point_data[i].tag; - point.laser_id = laser_id; - point.timestamp = + const uint64_t timestamp = toUint64.data + static_cast(i) * (double(data->time_interval * 100) / data->dot_num); //unit for interval is 0.1 us = 100 ns - if(point.timestamp > 0) + const auto& raw = p_point_data[i]; + if(timestamp == 0 || counts.record(raw.x, raw.y, raw.z, this_ptr->m_dropZeroXyz)) { - buffer->push_back(point); + continue; } + LidarPoint point; + point.x = 0.001 * raw.x; + point.y = 0.001 * raw.y; + point.z = 0.001 * raw.z; + point.intensity = raw.reflectivity; + point.tag = raw.tag; + point.laser_id = laser_id; + point.timestamp = timestamp; + buffer->push_back(point); } } else if(data->data_type == kLivoxLidarCartesianCoordinateLowData) @@ -586,4 +612,4 @@ uint16_t LivoxClient::handleToLidarId(uint32_t handle) const return 255; } -} // namespace mandeye \ No newline at end of file +} // namespace mandeye diff --git a/code/lidars/livoxsdk2/LivoxClient.h b/code/lidars/livoxsdk2/LivoxClient.h index 5309d5b..236539e 100644 --- a/code/lidars/livoxsdk2/LivoxClient.h +++ b/code/lidars/livoxsdk2/LivoxClient.h @@ -1,6 +1,6 @@ #pragma once -#include "lidars/BaseLidarClient.h" +#include "lidars/LidarChunk.h" #include "livox_lidar_def.h" #include "utils/TimeStampProvider.h" #include @@ -14,9 +14,11 @@ namespace mandeye { -class LivoxClient : public BaseLidarClient +class LivoxClient : public ChunkedLidarClient { public: + void Init(const nlohmann::json& config) override; + nlohmann::json produceStatus() override; //! starts LivoxSDK2, interface is IP of listen interface (IP of network cards with Livox connected @@ -29,6 +31,7 @@ class LivoxClient : public BaseLidarClient void stopLog() override; std::pair retrieveData() override; + LidarChunk retrieveChunk() override; //! Return current mapping from serial number to lidar id std::unordered_map getSerialNumberToLidarIdMapping() const override; @@ -55,6 +58,9 @@ class LivoxClient : public BaseLidarClient LidarPointsBufferPtr m_bufferLivoxPtr{nullptr}; LidarIMUBufferPtr m_bufferIMUPtr{nullptr}; + std::map m_zeroPointsByHandle; + // Older controllers skip Init() and expect the original unfiltered stream. + bool m_dropZeroXyz{false}; std::mutex m_timestampMutex; uint64_t m_timestamp{0}; diff --git a/code/main.cpp b/code/main.cpp index 424813a..18592f4 100644 --- a/code/main.cpp +++ b/code/main.cpp @@ -10,7 +10,7 @@ #include "state.h" #include -#include "lidars/BaseLidarClient.h" +#include "lidars/LidarChunk.h" #include "lidars/LidarImplementations.h" #include "compilation_constants.h" @@ -100,7 +100,7 @@ MemInfo readMemInfo() return info; } -std::string produceReport(bool reportUSB = true) +std::string produceReport(bool reportUSB = true, const ZeroPointStats* zeroPoints = nullptr) { json j; j["name"] = "Mandeye"; @@ -149,6 +149,10 @@ std::string produceReport(bool reportUSB = true) } j["lastLazStatus"] = lastFileSaveStats.produceStatus(); + if(zeroPoints) + { + j["zero_xyz"] = zeroPoints->produceStatus(); + } std::ostringstream s; s << std::setw(4) << j; @@ -248,7 +252,7 @@ bool TriggerContinousScanning() return false; } -void saveStatusData(const std::string& directory, int chunk) +void saveStatusData(const std::string& directory, int chunk, const std::optional& zeroPoints) { using namespace std::chrono_literals; char statusName[256]; @@ -256,7 +260,7 @@ void saveStatusData(const std::string& directory, int chunk) std::filesystem::path lidarFilePath = std::filesystem::path(directory) / std::filesystem::path(statusName); std::cout << "Savig status to " << lidarFilePath << std::endl; std::ofstream lidarStream(lidarFilePath); - lidarStream << produceReport(false); + lidarStream << produceReport(false, zeroPoints ? &*zeroPoints : nullptr); system("sync"); } @@ -495,7 +499,7 @@ void stateWatcher() chunkStart = std::chrono::steady_clock::now(); - auto [lidarBuffer, imuBuffer] = lidarClientPtr->retrieveData(); + auto [lidarBuffer, imuBuffer, zeroPoints] = retrieveChunk(*lidarClientPtr); std::deque gnssBuffer; std::deque gnssRawBuffer; @@ -514,7 +518,7 @@ void stateWatcher() if(saveStats) lastFileSaveStats = *saveStats; saveImuData(imuBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - saveStatusData(continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); + saveStatusData(continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS, zeroPoints); auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); if(gnssClientPtr) @@ -581,7 +585,7 @@ void stateWatcher() mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_CONTINOUS_SCANNING, true); mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, true); - auto [lidarBuffer, imuBuffer] = lidarClientPtr->retrieveData(); + auto [lidarBuffer, imuBuffer, zeroPoints] = retrieveChunk(*lidarClientPtr); std::deque gnssData; lidarClientPtr->stopLog(); if(gnssClientPtr) @@ -611,7 +615,7 @@ void stateWatcher() if(saveStats) lastFileSaveStats = *saveStats; saveImuData(imuBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - saveStatusData(continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); + saveStatusData(continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS, zeroPoints); auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); @@ -688,7 +692,7 @@ void stateWatcher() { mandeye::gpioClientPtr->setLed(hardware::LED::LED_GPIO_COPY_DATA, true); } - auto [lidarBuffer, imuBuffer] = lidarClientPtr->retrieveData(); + auto [lidarBuffer, imuBuffer, zeroPoints] = retrieveChunk(*lidarClientPtr); std::deque gnssData; lidarClientPtr->stopLog(); if(gnssClientPtr) @@ -706,7 +710,7 @@ void stateWatcher() if(saveStats) lastFileSaveStats = *saveStats; saveImuData(imuBuffer, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - saveStatusData(stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); + saveStatusData(stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS, zeroPoints); auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); diff --git a/code/save_laz.cpp b/code/save_laz.cpp index 10cca73..bb17a27 100644 --- a/code/save_laz.cpp +++ b/code/save_laz.cpp @@ -50,6 +50,11 @@ std::optional mandeye::saveLaz(const std::string& filename, L } } + if(buffer->empty()) + { + min_x = min_y = min_z = max_x = max_y = max_z = 0.0; + } + std::cout << "processing: " << filename << "points " << buffer->size() << std::endl; laszip_POINTER laszip_writer; @@ -204,4 +209,4 @@ std::optional mandeye::saveLaz(const std::string& filename, L TracyPlot("laz_save_duration_sec", (double)stats.m_saveDurationSec1); return stats; -} \ No newline at end of file +} diff --git a/html/index.htm b/html/index.htm index eceb2c2..a6c75e3 100644 --- a/html/index.htm +++ b/html/index.htm @@ -30,7 +30,7 @@ list.innerHTML += "
  • "+obj.fs.FileSystemClient.dirs[i] +"
  • "; } } - if (obj.hasOwnProperty('gnss')) + if (obj.gnss && obj.gnss.gga) { $('.gnss').text( obj.gnss.gga.satellites_tracked); } @@ -51,11 +51,15 @@ }).then(function(data) { var obj = jQuery.parseJSON(data); - $('.msgs_lidar').text( obj.lidar.counters.lidar); - $('.msgs_imu').text( obj.lidar.counters.imu); + var lidar = obj.lidar || {}; + var counters = lidar.counters || {}; + $('.msgs_lidar').text(counters.lidar == null ? 'N/A' : counters.lidar); + $('.msgs_imu').text(counters.imu == null ? 'N/A' : counters.imu); + $('.zero_xyz_filter').text(lidar.drop_zero_xyz === true ? 'On' : + lidar.drop_zero_xyz === false ? 'Off' : 'N/A'); $('.state').text( obj.state); - if (obj.hasOwnProperty('gnss')) + if (obj.gnss && obj.gnss.gga) { $('.gnss').text( obj.gnss.gga.satellites_tracked); } @@ -196,6 +200,7 @@ + @@ -205,6 +210,7 @@ + @@ -216,4 +222,4 @@
  • - \ No newline at end of file + From 9dcd69c462a18e546f875c4ecd94b9e0d4ca4750 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Fry=C5=84?= <81593823+siju-mf@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:24:32 +0000 Subject: [PATCH 2/5] Add lossless mLAZ writer next to LAZ (code only, switch follows) saveMlaz() writes exactly the LAS records and header saveLaz() writes for the same buffer (same decimation, bounds, quantization), except generating_software = "Mandeye mLAZ ". Codec from the 3rd/mlaz submodule pinned to 1.0.2; zstd and zlib from the system. test/mlaz builds without LiDAR SDKs and compares saveMlaz against saveLaz byte for byte (records decoded by laspy/lazrs). Co-Authored-By: Claude Opus 5.5 --- .gitmodules | 3 + 3rd/mlaz | 1 + CMakeLists.txt | 10 +- cmake/Mlaz.cmake | 39 ++++++ code/save_mlaz.cpp | 230 +++++++++++++++++++++++++++++++++++ code/save_mlaz.h | 40 ++++++ test/mlaz/CMakeLists.txt | 26 ++++ test/mlaz/check_save_mlaz.py | 75 ++++++++++++ test/mlaz/test_save_mlaz.cpp | 123 +++++++++++++++++++ 9 files changed, 544 insertions(+), 3 deletions(-) create mode 160000 3rd/mlaz create mode 100644 cmake/Mlaz.cmake create mode 100644 code/save_mlaz.cpp create mode 100644 code/save_mlaz.h create mode 100644 test/mlaz/CMakeLists.txt create mode 100644 test/mlaz/check_save_mlaz.py create mode 100644 test/mlaz/test_save_mlaz.cpp diff --git a/.gitmodules b/.gitmodules index bb1d88b..616e885 100644 --- a/.gitmodules +++ b/.gitmodules @@ -25,3 +25,6 @@ [submodule "3rd/tracy"] path = 3rd/tracy url = https://github.com/wolfpld/tracy.git +[submodule "3rd/mlaz"] + path = 3rd/mlaz + url = https://gitlab.com/GitMF/mlaz.git diff --git a/3rd/mlaz b/3rd/mlaz new file mode 160000 index 0000000..3d19ff7 --- /dev/null +++ b/3rd/mlaz @@ -0,0 +1 @@ +Subproject commit 3d19ff789e128217603f0886ed2773f751fad2b6 diff --git a/CMakeLists.txt b/CMakeLists.txt index a6d0767..f3927e3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,6 +21,10 @@ message("LASzip library") add_subdirectory(3rd/LASzip) include_directories(3rd/LASzip/include) +message("mLAZ writer") +# mLAZ writer (3rd/mlaz submodule, pinned to a codec release tag) +include(cmake/Mlaz.cmake) + message("INCBIN") # INCBIN include_directories(3rd/incbin) @@ -160,13 +164,13 @@ endif() add_executable(control_program code/main.cpp code/gnss.cpp code/web_page.h ${LIDAR_SOURCES} ${LIDAR_SOURCES} - code/gpios.cpp code/FileSystemClient.cpp code/save_laz.cpp code/save_data.cpp + code/gpios.cpp code/FileSystemClient.cpp code/save_laz.cpp code/save_mlaz.cpp code/save_data.cpp code/utils/TimeStampReceiver.cpp code/publisher.cpp) set(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS} -latomic " ) -target_link_libraries(control_program pthread ${LIDAR_LIBRARIES} pistache atomic laszip ${LIBSERIAL_LIBRARY} minea gpiod zmq) +target_link_libraries(control_program pthread ${LIDAR_LIBRARIES} pistache atomic laszip mlaz_writer ${LIBSERIAL_LIBRARY} minea gpiod zmq) if(MANDEYE_USE_TRACY) target_link_libraries(control_program TracyClient) @@ -220,6 +224,6 @@ set(CPACK_GENERATOR "DEB") set(CPACK_PACKAGE_NAME "mandeye-multisensor") set(CPACK_PACKAGE_VERSION "${MANDEYE_VERSION}-${GIT_HASH}-${MANDEYE_HARDWARE_HEADER}-${SYSTEM_ARCH}") set(CPACK_PACKAGE_CONTACT "Michał Pełka ") -set(CPACK_DEBIAN_PACKAGE_DEPENDS "rapidjson-dev,libserial-dev, libgpiod-dev, libzmq3-dev") +set(CPACK_DEBIAN_PACKAGE_DEPENDS "rapidjson-dev,libserial-dev, libgpiod-dev, libzmq3-dev, libzstd1, zlib1g") set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_CURRENT_SOURCE_DIR}/packing/postinst/postinst") include(CPack) diff --git a/cmake/Mlaz.cmake b/cmake/Mlaz.cmake new file mode 100644 index 0000000..345291b --- /dev/null +++ b/cmake/Mlaz.cmake @@ -0,0 +1,39 @@ +# mLAZ writer (lossless point-cloud codec, https://gitlab.com/GitMF/mlaz) built from the 3rd/mlaz +# submodule pinned to a release tag. Defines: +# mlaz_writer static library with mlaz::Writer (3rd/mlaz/mlaz_writer.h) +# MLAZ_VERSION codec version read from 3rd/mlaz/mlaz_core.h (also passed to users as MANDEYE_MLAZ_VERSION) +# Needs zstd and zlib (Debian/Raspberry Pi OS: apt install libzstd-dev zlib1g-dev). +# Other locations: -DCMAKE_PREFIX_PATH=";". + +set(MLAZ_DIR ${CMAKE_CURRENT_LIST_DIR}/../3rd/mlaz) +if(NOT EXISTS ${MLAZ_DIR}/mlaz_writer.cpp) + message(FATAL_ERROR "3rd/mlaz is empty. Run: git submodule update --init 3rd/mlaz") +endif() + +file(STRINGS ${MLAZ_DIR}/mlaz_core.h MLAZ_VERSION_LINE REGEX "constexpr const char\\* VERSION = ") +string(REGEX REPLACE ".*VERSION = \"([0-9.]+)\".*" "\\1" MLAZ_VERSION "${MLAZ_VERSION_LINE}") +if(NOT MLAZ_VERSION MATCHES "^[0-9]+\\.[0-9]+\\.[0-9]+$") + message(FATAL_ERROR "Cannot read the mLAZ version from ${MLAZ_DIR}/mlaz_core.h") +endif() +message(STATUS "mLAZ codec version: ${MLAZ_VERSION}") + +find_package(Threads REQUIRED) +find_package(ZLIB REQUIRED) +find_path(ZSTD_INCLUDE_DIR zstd.h) +find_library(ZSTD_LIBRARY NAMES zstd) +if(NOT ZSTD_INCLUDE_DIR OR NOT ZSTD_LIBRARY) + message(FATAL_ERROR "zstd not found. Install: apt install libzstd-dev") +endif() + +add_library(mlaz_writer STATIC ${MLAZ_DIR}/mlaz_writer.cpp) +set_property(TARGET mlaz_writer PROPERTY POSITION_INDEPENDENT_CODE ON) +target_include_directories(mlaz_writer PUBLIC ${MLAZ_DIR}) +target_include_directories(mlaz_writer PRIVATE ${ZSTD_INCLUDE_DIR}) +target_link_libraries(mlaz_writer PRIVATE ${ZSTD_LIBRARY} ZLIB::ZLIB Threads::Threads) +target_compile_options(mlaz_writer PRIVATE -O3) +# Every Raspberry Pi 4/5 and CM4/CM5 core (Cortex-A72/A76) has the ARMv8 CRC32 instructions; NEON is +# part of AArch64. Without +crc the codec falls back to the slower zlib CRC. +if(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|arm64") + target_compile_options(mlaz_writer PRIVATE -march=armv8-a+crc) +endif() +target_compile_definitions(mlaz_writer INTERFACE MANDEYE_MLAZ_VERSION="${MLAZ_VERSION}") diff --git a/code/save_mlaz.cpp b/code/save_mlaz.cpp new file mode 100644 index 0000000..32ed642 --- /dev/null +++ b/code/save_mlaz.cpp @@ -0,0 +1,230 @@ +#include "save_mlaz.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mandeye +{ +namespace +{ +// LiDAR SDKs whose recordings were measured with mLAZ (lossless, never larger than LAZ). +const std::array MlazLidarSdks{"LIVOX_SDK2"}; + +constexpr size_t LasHeaderSize = 227; // LAS 1.2 public header block, no VLRs +constexpr size_t LasRecordSize = 28; // point data format 1 + +void put16(uint8_t* p, uint16_t v) +{ + p[0] = uint8_t(v); + p[1] = uint8_t(v >> 8); +} +void put32(uint8_t* p, uint32_t v) +{ + for(int i = 0; i < 4; i++) + p[i] = uint8_t(v >> (8 * i)); +} +void putI32(uint8_t* p, int32_t v) +{ + put32(p, uint32_t(v)); +} +void putF64(uint8_t* p, double v) +{ + uint64_t u; + std::memcpy(&u, &v, 8); + for(int i = 0; i < 8; i++) + p[i] = uint8_t(u >> (8 * i)); +} +// Same rounding as LASzip's I32_QUANTIZE (laszip_set_coordinates). +int32_t quantize(double n) +{ + return (n >= 0) ? int32_t(n + 0.5) : int32_t(n - 0.5); +} +} // namespace + +const char* toString(PointFormat format) +{ + switch(format) + { + case PointFormat::Mlaz: + return "mlaz"; + case PointFormat::Both: + return "both"; + default: + return "laz"; + } +} + +PointFormatSetting resolvePointFormat(const nlohmann::json& config, const std::string& lidarSdk) +{ + PointFormatSetting s; + if(!config.is_object() || !config.contains("point_format")) + return s; + const auto& value = config["point_format"]; + if(!value.is_string()) + { + s.configured = value.dump(); + s.warning = "point_format must be \"laz\", \"mlaz\" or \"both\" (got " + s.configured + "); saving LAZ"; + return s; + } + s.configured = value.get(); + PointFormat requested; + if(s.configured == "laz") + return s; + else if(s.configured == "mlaz") + requested = PointFormat::Mlaz; + else if(s.configured == "both") + requested = PointFormat::Both; + else + { + s.warning = "unknown point_format \"" + s.configured + "\" (use \"laz\", \"mlaz\" or \"both\"); saving LAZ"; + return s; + } + if(std::find(MlazLidarSdks.begin(), MlazLidarSdks.end(), lidarSdk) == MlazLidarSdks.end()) + { + s.warning = "mLAZ is not cleared for lidar_sdk \"" + lidarSdk + "\"; saving LAZ"; + return s; + } + s.format = requested; + return s; +} + +std::string mlazGeneratingSoftware() +{ + return std::string("Mandeye mLAZ ") + MANDEYE_MLAZ_VERSION; +} + +std::optional saveMlaz(const std::string& filename, LidarPointsBufferPtr buffer, const std::string& sn) +try +{ + // Everything up to the records must match saveLaz() (save_laz.cpp) for the same buffer; + // test/mlaz/test_save_mlaz.cpp checks it byte for byte. + LazStats stats; + stats.m_filename = filename; + constexpr float scale = 0.0001f; // one tenth of milimeter, as in saveLaz() + const double scale_d = scale; // LASzip stores and divides by the float widened to double + + double max_x{std::numeric_limits::lowest()}; + double max_y{std::numeric_limits::lowest()}; + double max_z{std::numeric_limits::lowest()}; + double min_x{std::numeric_limits::max()}; + double min_y{std::numeric_limits::max()}; + double min_z{std::numeric_limits::max()}; + for(const auto& p : *buffer) + { + max_x = std::max(max_x, double(p.x)); + max_y = std::max(max_y, double(p.y)); + max_z = std::max(max_z, double(p.z)); + min_x = std::min(min_x, double(p.x)); + min_y = std::min(min_y, double(p.y)); + min_z = std::min(min_z, double(p.z)); + } + if(buffer->empty()) + { + min_x = min_y = min_z = max_x = max_y = max_z = 0.0; + } + + // same decimation as saveLaz() + int step = 1; + if(buffer->size() > 4000000) + { + step = ceil((double)buffer->size() / 2000000.0); + } + if(step < 1) + { + step = 1; + } + uint32_t num_points = 0; + for(size_t i = 0; i < buffer->size(); i += step) + { + num_points++; + } + stats.m_decimationStep = step; + + // LAS 1.2 header as LASzip writes it for an uncompressed .las (laszip_clean defaults + saveLaz fields) + std::array h{}; + std::memcpy(&h[0], "LASF", 4); + put16(&h[4], 4711); // file_source_ID + put16(&h[6], 1); // global_encoding: GPS time is adjusted standard GPS time + h[24] = 1; // version_major + h[25] = 2; // version_minor + const std::string software = mlazGeneratingSoftware(); + std::memcpy(&h[58], software.data(), std::min(software.size(), 31)); + put16(&h[94], LasHeaderSize); // header_size + put32(&h[96], LasHeaderSize); // offset_to_point_data + h[104] = 1; // point_data_format + put16(&h[105], LasRecordSize); + put32(&h[107], num_points); // number_of_point_records + put32(&h[111], num_points); // number_of_points_by_return[0] + putF64(&h[131], scale_d); + putF64(&h[139], scale_d); + putF64(&h[147], scale_d); + // offsets 155..178 stay 0 + putF64(&h[179], max_x); + putF64(&h[187], min_x); + putF64(&h[195], max_y); + putF64(&h[203], min_y); + putF64(&h[211], max_z); + putF64(&h[219], min_z); + + std::cout << "processing: " << filename << " points " << buffer->size() << std::endl; + const auto start = std::chrono::high_resolution_clock::now(); + + mlaz::WriterOptions options; + mlaz::Writer writer(filename, h.data(), h.size(), sn.data(), sn.size(), options); + + // records in frame-sized batches, so the RAM cost is one frame, not the whole chunk + std::vector batch(size_t(options.block) * LasRecordSize); + size_t inBatch = 0; + for(size_t i = 0; i < buffer->size(); i += step) + { + const auto& p = buffer->at(i); + uint8_t* r = &batch[inBatch * LasRecordSize]; + putI32(r + 0, quantize((p.x - 0.0) / scale_d)); + putI32(r + 4, quantize((p.y - 0.0) / scale_d)); + putI32(r + 8, quantize((p.z - 0.0) / scale_d)); + put16(r + 12, static_cast(p.intensity)); + r[14] = 0; // return number, number of returns, scan direction, edge of flight line + r[15] = p.tag & 0x1F; // LAS 1.2 classification has 5 bits (as LASzip's bit field) + r[16] = 0; // scan_angle_rank + r[17] = static_cast(p.laser_id); // user_data + put16(r + 18, 0); // point_source_ID + putF64(r + 20, p.timestamp * 1e-9); // gps_time + if(++inBatch == options.block) + { + writer.append(batch.data(), inBatch); + inBatch = 0; + } + } + if(inBatch) + { + writer.append(batch.data(), inBatch); + } + writer.close(); + stats.m_pointsCount = writer.points(); + + const auto end = std::chrono::high_resolution_clock::now(); + const std::chrono::duration elapsed_seconds = end - start; + stats.m_saveDurationSec1 = elapsed_seconds.count(); + stats.m_sizeMb = static_cast(writer.bytes()) / (1024 * 1024); + std::cout << "exportMlaz DONE " << stats.m_pointsCount << " points" << std::endl; + return stats; +} +catch(const std::exception& e) +{ + std::cerr << "mLAZ ERROR: saving '" << filename << "': " << e.what() << std::endl; + return std::nullopt; +} +catch(...) +{ + std::cerr << "mLAZ ERROR: saving '" << filename << "': unknown error" << std::endl; + return std::nullopt; +} +} // namespace mandeye diff --git a/code/save_mlaz.h b/code/save_mlaz.h new file mode 100644 index 0000000..dfbd577 --- /dev/null +++ b/code/save_mlaz.h @@ -0,0 +1,40 @@ +#pragma once +#include "lidars/BaseLidarClient.h" +#include "save_laz.h" +#include +#include +#include + +namespace mandeye +{ +// Point-cloud file format chosen by "point_format" in mandeye_config.json on the USB drive. +enum class PointFormat +{ + Laz, // lidarNNNN.laz only (default, also when the key is missing) + Mlaz, // lidarNNNN.mlaz only (lossless mLAZ, https://gitlab.com/GitMF/mlaz) + Both, // lidarNNNN.laz and lidarNNNN.mlaz from the same buffer +}; + +struct PointFormatSetting +{ + PointFormat format{PointFormat::Laz}; + std::string configured; // value from the config ("" when the key is missing) + std::string warning; // non-empty when the configured value was not honoured +}; + +const char* toString(PointFormat format); + +// Reads "point_format" from mandeye_config.json. Never throws: a missing key gives LAZ; an unknown or +// non-string value, or mLAZ requested for a LiDAR SDK not cleared for mLAZ, gives LAZ and a warning. +PointFormatSetting resolvePointFormat(const nlohmann::json& config, const std::string& lidarSdk); + +// "Mandeye mLAZ ", the generating_software of LAS headers stored in .mlaz files. +std::string mlazGeneratingSoftware(); + +// Saves the buffer as a lossless .mlaz file holding exactly the LAS 1.2 point format 1 file saveLaz() +// writes for the same buffer with a ".las" name (same decimation, bounds, quantization and header), +// except generating_software = mlazGeneratingSoftware(). sn (content of lidarNNNN.sn) is stored in the +// file. The file appears under its name only when complete (written as NAME.part, fsync, rename). +// Never throws; returns nullopt on error. +std::optional saveMlaz(const std::string& filename, LidarPointsBufferPtr buffer, const std::string& sn); +} // namespace mandeye diff --git a/test/mlaz/CMakeLists.txt b/test/mlaz/CMakeLists.txt new file mode 100644 index 0000000..565803c --- /dev/null +++ b/test/mlaz/CMakeLists.txt @@ -0,0 +1,26 @@ +# Stand-alone check of the mLAZ writer against saveLaz(); needs no LiDAR SDK, GPIO or web server. +# cmake -S test/mlaz -B build-mlaz-test && cmake --build build-mlaz-test -j +# python3 test/mlaz/check_save_mlaz.py --test build-mlaz-test/test_save_mlaz --mlaz 3rd/mlaz/mlaz +# SAVE_LAZ_SOURCE: save_laz.cpp to compile (default: code/save_laz.cpp), e.g. from another commit, +# to show that LAZ files are unchanged. +cmake_minimum_required(VERSION 3.13) +project(mandeye_mlaz_test C CXX) +set(CMAKE_CXX_STANDARD 17) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() + +get_filename_component(MANDEYE_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../.. ABSOLUTE) +set(SAVE_LAZ_SOURCE ${MANDEYE_ROOT}/code/save_laz.cpp CACHE FILEPATH "save_laz.cpp to test against") + +add_subdirectory(${MANDEYE_ROOT}/3rd/LASzip LASzip) +include(${MANDEYE_ROOT}/cmake/Mlaz.cmake) +find_path(NLOHMANN_JSON_INCLUDE_DIR nlohmann/json.hpp) +if(NOT NLOHMANN_JSON_INCLUDE_DIR) + message(FATAL_ERROR "nlohmann/json.hpp not found. Install: apt install nlohmann-json3-dev") +endif() + +add_executable(test_save_mlaz test_save_mlaz.cpp ${SAVE_LAZ_SOURCE} ${MANDEYE_ROOT}/code/save_mlaz.cpp) +target_include_directories(test_save_mlaz PRIVATE + ${MANDEYE_ROOT}/code ${MANDEYE_ROOT}/3rd/LASzip/include ${MANDEYE_ROOT}/3rd/tracy/public ${NLOHMANN_JSON_INCLUDE_DIR}) +target_link_libraries(test_save_mlaz PRIVATE laszip mlaz_writer) diff --git a/test/mlaz/check_save_mlaz.py b/test/mlaz/check_save_mlaz.py new file mode 100644 index 0000000..a8b1ed1 --- /dev/null +++ b/test/mlaz/check_save_mlaz.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Check the firmware mLAZ writer against saveLaz() on the same LidarPoint buffers. + +Runs test_save_mlaz (writes NAME.laz, NAME.las and NAME.mlaz per case), decodes every .mlaz with the +mlaz tool and checks: + 1. decoded .mlaz == NAME.las (saveLaz, uncompressed) byte for byte, except generating_software + (LAS header bytes 58..89), which must be "Mandeye mLAZ "; + 2. point records of NAME.laz decoded by laspy/lazrs (independent of LASzip) == records of the + decoded .mlaz; header point count and bounds equal; + 3. the serial-number text stored in .mlaz comes back unchanged. +Optional --laz-ref DIR: NAME.laz files written by another build (e.g. save_laz.cpp of the firmware +without mLAZ) must be byte-identical to the ones written here. + + check_save_mlaz.py --test BUILD/test_save_mlaz --mlaz PATH/mlaz [--out DIR] [--laz-ref DIR] +""" +import argparse +import pathlib +import subprocess +import sys +import tempfile + +CASES = ["small", "empty", "one", "decimated"] +SN = b"0 47MDL9A0020061\n" +SOFTWARE = slice(58, 90) +HEADER = 227 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--test", required=True) + ap.add_argument("--mlaz", required=True) + ap.add_argument("--out") + ap.add_argument("--laz-ref") + a = ap.parse_args() + import laspy # with the lazrs backend + + tmp = None if a.out else tempfile.TemporaryDirectory() + out = pathlib.Path(a.out or tmp.name) + subprocess.run([a.test, str(out)], check=True) + version = subprocess.run([a.mlaz, "--version"], capture_output=True, text=True).stdout.split()[1] # "mlaz 1.0.2 format=..." + fails = 0 + + def check(ok, what): + nonlocal fails + print(("ok " if ok else "FAIL ") + what) + fails += not ok + + for name in CASES: + las = (out / f"{name}.las").read_bytes() + dec, sn = out / f"{name}.dec.las", out / f"{name}.dec.sn" + subprocess.run([a.mlaz, "decompress", str(out / f"{name}.mlaz"), str(dec), "--sn", str(sn)], check=True) + m = dec.read_bytes() + same_rest = len(m) == len(las) and m[:SOFTWARE.start] == las[:SOFTWARE.start] and m[SOFTWARE.stop:] == las[SOFTWARE.stop:] + check(same_rest, f"{name}: decoded .mlaz == saveLaz .las except generating_software ({len(m)} B)") + want = f"Mandeye mLAZ {version}".encode().ljust(32, b"\0") + check(m[SOFTWARE] == want, f"{name}: generating_software = {m[SOFTWARE].rstrip(bytes(1))!r}") + check(sn.read_bytes() == SN, f"{name}: serial numbers stored in .mlaz") + + lz = laspy.read(out / f"{name}.laz") + recs = lz.points.array.tobytes() + n = int(lz.header.point_count) + check(len(recs) == n * 28 and recs == m[HEADER:], f"{name}: {n} LAZ records (laspy) == .mlaz records") + hm = laspy.LasHeader.read_from(open(dec, "rb")) + check(hm.point_count == n and list(hm.mins) == list(lz.header.mins) and list(hm.maxs) == list(lz.header.maxs), + f"{name}: point count and bounds equal") + if a.laz_ref: + ref = pathlib.Path(a.laz_ref) / f"{name}.laz" + check(ref.read_bytes() == (out / f"{name}.laz").read_bytes(), f"{name}: .laz identical to {ref}") + + print("ALL OK" if not fails else f"{fails} FAILED") + return 1 if fails else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/mlaz/test_save_mlaz.cpp b/test/mlaz/test_save_mlaz.cpp new file mode 100644 index 0000000..881e0fb --- /dev/null +++ b/test/mlaz/test_save_mlaz.cpp @@ -0,0 +1,123 @@ +// Writes the same LidarPoint buffers with saveLaz (.laz and .las) and saveMlaz (.mlaz) into OUTDIR, +// for check_save_mlaz.py to compare. Also checks the "point_format" switch parsing. +// test_save_mlaz OUTDIR +#include "save_laz.h" +#include "save_mlaz.h" + +#include +#include +#include +#include + +using mandeye::LidarPoint; +using mandeye::LidarPointsBuffer; +using mandeye::LidarPointsBufferPtr; + +namespace +{ +int failures = 0; + +void expect(bool ok, const std::string& what) +{ + if(!ok) + { + std::cerr << "FAIL: " << what << std::endl; + failures++; + } +} + +// Deterministic buffer covering values the LAS record has to cut down: tag bits 5-7, laser_id > 255, +// fractional and > 255 intensity, negative/zero/far coordinates, nanosecond timestamps near 2026. +LidarPointsBufferPtr makeBuffer(size_t n) +{ + auto buffer = std::make_shared(); + uint64_t s = 0x9E3779B97F4A7C15ull; + auto next = [&s]() { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + return s; + }; + const uint64_t t0 = 1772284800000000000ull; // 2026-02-28 in ns + for(size_t i = 0; i < n; i++) + { + LidarPoint p; + const uint64_t r = next(); + p.x = float(int64_t(r % 400001) - 200000) / 1000.0f; // +-200 m + p.y = float(int64_t((r >> 20) % 400001) - 200000) / 1000.0f; + p.z = float(int64_t((r >> 40) % 60001) - 30000) / 1000.0f; + if(i % 97 == 0) + p.x = p.y = p.z = 0.0f; + p.intensity = float(i % 300) + 0.37f; + p.tag = uint8_t(i % 256); + p.timestamp = t0 + i * 4167 + (r % 7); + p.line_id = uint8_t(i % 4); + p.laser_id = uint16_t(i % 300); + buffer->push_back(p); + } + return buffer; +} + +void writeCase(const std::filesystem::path& dir, const std::string& name, size_t n) +{ + auto buffer = makeBuffer(n); + const std::string sn = "0 47MDL9A0020061\n"; + const auto laz = mandeye::saveLaz((dir / (name + ".laz")).string(), buffer); + const auto las = mandeye::saveLaz((dir / (name + ".las")).string(), buffer); + const auto mlaz = mandeye::saveMlaz((dir / (name + ".mlaz")).string(), buffer, sn); + expect(laz && las && mlaz, name + ": all three files written"); + if(laz && mlaz) + { + expect(laz->m_pointsCount == mlaz->m_pointsCount, name + ": same point count in stats"); + expect(laz->m_decimationStep == mlaz->m_decimationStep, name + ": same decimation step in stats"); + } + std::cout << name << ": " << n << " points in buffer, " << (mlaz ? mlaz->m_pointsCount : 0) << " written, step " + << (mlaz ? mlaz->m_decimationStep : 0) << std::endl; +} + +void checkSwitch() +{ + using mandeye::PointFormat; + using mandeye::resolvePointFormat; + const std::string livox = "LIVOX_SDK2"; + auto fmt = [&](const char* json, const std::string& sdk) { return resolvePointFormat(nlohmann::json::parse(json), sdk); }; + + auto s = fmt("{}", livox); + expect(s.format == PointFormat::Laz && s.warning.empty(), "missing key -> LAZ, no warning"); + s = resolvePointFormat(nlohmann::json(), livox); + expect(s.format == PointFormat::Laz && s.warning.empty(), "no config -> LAZ, no warning"); + s = fmt(R"({"point_format":"laz"})", livox); + expect(s.format == PointFormat::Laz && s.warning.empty(), "laz -> LAZ"); + s = fmt(R"({"point_format":"mlaz"})", livox); + expect(s.format == PointFormat::Mlaz && s.warning.empty(), "mlaz + Livox -> mLAZ"); + s = fmt(R"({"point_format":"both"})", livox); + expect(s.format == PointFormat::Both && s.warning.empty(), "both + Livox -> both"); + s = fmt(R"({"point_format":"MLAZ"})", livox); + expect(s.format == PointFormat::Laz && !s.warning.empty(), "unknown value -> LAZ + warning"); + s = fmt(R"({"point_format":1})", livox); + expect(s.format == PointFormat::Laz && !s.warning.empty(), "non-string -> LAZ + warning"); + s = fmt(R"({"point_format":"mlaz"})", "OUSTER"); + expect(s.format == PointFormat::Laz && !s.warning.empty(), "mlaz + other LiDAR -> LAZ + warning"); + s = fmt(R"({"point_format":"both"})", "BUTTER_LIDAR"); + expect(s.format == PointFormat::Laz && !s.warning.empty(), "both + other LiDAR -> LAZ + warning"); + expect(mandeye::mlazGeneratingSoftware() == std::string("Mandeye mLAZ ") + MANDEYE_MLAZ_VERSION, "generating software"); +} +} // namespace + +int main(int argc, char** argv) +{ + if(argc != 2) + { + std::cerr << "usage: test_save_mlaz OUTDIR" << std::endl; + return 2; + } + const std::filesystem::path dir = argv[1]; + std::filesystem::create_directories(dir); + checkSwitch(); + writeCase(dir, "small", 123457); // several mLAZ frames, last one partial + writeCase(dir, "empty", 0); + writeCase(dir, "one", 1); + writeCase(dir, "decimated", 4500001); // > 4 mln -> step 3, bounds from the whole buffer + std::cout << (failures ? "FAILED" : "OK") << std::endl; + return failures ? 1 : 0; +} From 02ca003c6bbd0d527b1b37cbd7fbdf45070eb825 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Fry=C5=84?= <81593823+siju-mf@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:24:32 +0000 Subject: [PATCH 3/5] Select LAZ, mLAZ or both per chunk with point_format on the USB drive "point_format" in /media/usb/mandeye_config.json, read at start: laz (default, also when missing), mlaz, both. Unknown value or a LiDAR SDK other than LIVOX_SDK2 -> LAZ and a warning on the web page. In both mode LAZ is written first; a failed mLAZ-only save falls back to LAZ. The .mlaz file stores the same LiDAR list as lidarNNNN.sn. statusNNNN.json reports point_format (configured, effective, warning, last_chunk) and lastMlazStatus. Co-Authored-By: Claude Opus 5.5 --- README.md | 47 +++++++++++++++++++++++- code/main.cpp | 91 ++++++++++++++++++++++++++++++++++++++++------ code/save_data.cpp | 36 ++++++++++++++++-- code/save_data.h | 5 +++ html/index.htm | 7 ++++ 5 files changed, 170 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 176e8df..f59d3ef 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ The software can run other distros (e.g. Ubuntu), but it is not tested and maint ```bash sudo apt-get update sudo apt-get upgrade -sudo apt-get install build-essential cmake git rapidjson-dev debhelper build-essential ntfs-3g libserial-dev libgpiod-dev libzmq3-dev libpistache-dev libcamera-dev linuxptp debhelper libopencv-dev pps-tools ppsh nlohmann-json3-dev +sudo apt-get install build-essential cmake git rapidjson-dev debhelper build-essential ntfs-3g libserial-dev libgpiod-dev libzmq3-dev libpistache-dev libcamera-dev linuxptp debhelper libopencv-dev pps-tools ppsh nlohmann-json3-dev libzstd-dev zlib1g-dev ``` ## Static IP for eth0 @@ -247,6 +247,51 @@ head that sent no points in the chunk has `input_points` equal to zero and `zero_percent` equal to `null`. `filtered_points` counts the returns removed by the filter. Decimation uses the number of points left in the buffer. +## Point-cloud format: LAZ or lossless mLAZ + +By default every chunk is saved as `lidarNNNN.laz`, exactly as before. The +controller can also save chunks as `lidarNNNN.mlaz`, a lossless format from the +mLAZ codec (https://gitlab.com/GitMF/mlaz, submodule `3rd/mlaz`). Choose the +format with `point_format` in `/media/usb/mandeye_config.json` and restart the +controller: + +| `point_format` | Files per chunk | +|-------------------|------------------------------------------------------| +| missing or `laz` | `lidarNNNN.laz` (default) | +| `mlaz` | `lidarNNNN.mlaz` | +| `both` | `lidarNNNN.laz` and `lidarNNNN.mlaz` from one buffer | + +```json +{ "point_format": "mlaz" } +``` + +To go back to LAZ, remove the key or set it to `laz`. mLAZ is enabled only for +`LIVOX_SDK2`; with another LiDAR SDK, or with an unknown value, the controller +saves LAZ and the web page shows a warning. If an mLAZ file cannot be saved, +the chunk is saved as LAZ instead. + +`lidarNNNN.mlaz` holds the same LAS 1.2 file the controller would save as +uncompressed `lidarNNNN.las` (same points, decimation and header), except the +header's generating software is `Mandeye mLAZ `. The serial +numbers from `lidarNNNN.sn` are stored inside the file as well. Decode it with +the `mlaz` tool from the codec repository: + +```bash +mlaz decompress lidar0001.mlaz lidar0001.las --sn lidar0001.sn +mlaz verify lidar0001.mlaz +``` + +Each `statusNNNN.json` reports `point_format` (`configured`, `effective`, +`warning` and `last_chunk`, the format the chunk was saved in) and, when mLAZ +is on, `lastMlazStatus`. The web status table shows the format. + +`test/mlaz` checks the mLAZ writer against the LAZ writer without LiDAR SDKs: + +```bash +cmake -S test/mlaz -B build-mlaz-test && cmake --build build-mlaz-test -j +python3 test/mlaz/check_save_mlaz.py --test build-mlaz-test/test_save_mlaz --mlaz PATH/TO/mlaz +``` + # Installation and usage of the package To install the package, you need to copy it to the target device and install it with `dpkg`: ```bash diff --git a/code/main.cpp b/code/main.cpp index 18592f4..f986952 100644 --- a/code/main.cpp +++ b/code/main.cpp @@ -7,6 +7,7 @@ #include "save_data.h" #include "save_laz.h" +#include "save_mlaz.h" #include "state.h" #include @@ -48,6 +49,10 @@ std::shared_ptr gnssClientPtr; std::shared_ptr fileSystemClientPtr; std::shared_ptr publisherPtr; mandeye::LazStats lastFileSaveStats; // updated by savePointcloudData return value +mandeye::PointFormatSetting pointFormat; // "point_format" from mandeye_config.json, resolved at start +std::mutex lastMlazMutex; // guards the two below, read by the web status thread +mandeye::LazStats lastMlazSaveStats; +std::string lastChunkFormat; // what the last chunk was saved as: laz, mlaz, both, laz (mlaz failed), ... double usbWriteSpeed10Mb = 0.0; double usbWriteSpeed1Mb = 0.0; @@ -149,6 +154,17 @@ std::string produceReport(bool reportUSB = true, const ZeroPointStats* zeroPoint } j["lastLazStatus"] = lastFileSaveStats.produceStatus(); + j["point_format"]["configured"] = pointFormat.configured; + j["point_format"]["effective"] = toString(pointFormat.format); + j["point_format"]["warning"] = pointFormat.warning; + { + std::lock_guard lock(lastMlazMutex); + j["point_format"]["last_chunk"] = lastChunkFormat; + if(pointFormat.format != PointFormat::Laz) + { + j["lastMlazStatus"] = lastMlazSaveStats.produceStatus(); + } + } if(zeroPoints) { j["zero_xyz"] = zeroPoints->produceStatus(); @@ -264,6 +280,57 @@ void saveStatusData(const std::string& directory, int chunk, const std::optional system("sync"); } +// Saves the chunk's points in the configured point format. With "laz" the calls are the same as before +// mLAZ existed. Returns the LiDAR list stored in the .mlaz file (if one was written), so that +// lidarNNNN.sn gets the same list. +std::optional> savePoints(LidarPointsBufferPtr buffer, const std::string& directory, int chunk) +{ + if(pointFormat.format == PointFormat::Laz) + { + auto [fn, saveStats] = savePointcloudData(buffer, directory, chunk); + if(saveStats) + lastFileSaveStats = *saveStats; + std::lock_guard lock(lastMlazMutex); + lastChunkFormat = saveStats ? "laz" : "none"; + return std::nullopt; + } + + auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); + bool lazSaved = false; + if(pointFormat.format == PointFormat::Both) + { + // LAZ first: an mLAZ error never costs the LAZ file + auto [fn, saveStats] = savePointcloudData(buffer, directory, chunk); + if(saveStats) + lastFileSaveStats = *saveStats; + lazSaved = saveStats.has_value(); + } + auto [mlazFn, mlazStats] = savePointcloudMlaz(buffer, directory, chunk, lidarListText(lidarList)); + std::string written; + if(pointFormat.format == PointFormat::Both) + { + written = lazSaved && mlazStats ? "both" : lazSaved ? "laz (mlaz failed)" : mlazStats ? "mlaz (laz failed)" : "none"; + } + else if(mlazStats) + { + hardware::OnSavedLaz(mlazFn); + written = "mlaz"; + } + else + { + // mLAZ only, but it failed: keep the chunk as LAZ + auto [fn, saveStats] = savePointcloudData(buffer, directory, chunk); + if(saveStats) + lastFileSaveStats = *saveStats; + written = saveStats ? "laz (mlaz failed)" : "none"; + } + std::lock_guard lock(lastMlazMutex); + if(mlazStats) + lastMlazSaveStats = *mlazStats; + lastChunkFormat = written; + return lidarList; +} + void stateWatcher() { using namespace std::chrono_literals; @@ -514,12 +581,10 @@ void stateWatcher() } else { - auto [fn, saveStats] = savePointcloudData(lidarBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - if(saveStats) - lastFileSaveStats = *saveStats; + auto mlazLidarList = savePoints(lidarBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); saveImuData(imuBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); saveStatusData(continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS, zeroPoints); - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); + auto lidarList = mlazLidarList ? *mlazLidarList : lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); if(gnssClientPtr) { @@ -611,12 +676,10 @@ void stateWatcher() } else { - auto [fn, saveStats] = savePointcloudData(lidarBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - if(saveStats) - lastFileSaveStats = *saveStats; + auto mlazLidarList = savePoints(lidarBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); saveImuData(imuBuffer, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); saveStatusData(continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS, zeroPoints); - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); + auto lidarList = mlazLidarList ? *mlazLidarList : lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); if(gnssClientPtr) @@ -706,13 +769,11 @@ void stateWatcher() } else { - auto [fn, saveStats] = savePointcloudData(lidarBuffer, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); - if(saveStats) - lastFileSaveStats = *saveStats; + auto mlazLidarList = savePoints(lidarBuffer, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); saveImuData(imuBuffer, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); saveStatusData(stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS, zeroPoints); - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); + auto lidarList = mlazLidarList ? *mlazLidarList : lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); if(gnssClientPtr) @@ -838,6 +899,12 @@ int main(int argc, char** argv) mandeye::lidarSDKToUse = mandeye::configJson["lidar_sdk"].get(); } std::cout << "Lidar SDK to use from config: " << mandeye::lidarSDKToUse << std::endl; + mandeye::pointFormat = mandeye::resolvePointFormat(mandeye::configJson, mandeye::lidarSDKToUse); + std::cout << "Point format: " << mandeye::toString(mandeye::pointFormat.format) << " (mLAZ " << MANDEYE_MLAZ_VERSION << ")" << std::endl; + if(!mandeye::pointFormat.warning.empty()) + { + std::cout << "WARNING: " << mandeye::pointFormat.warning << std::endl; + } std::thread thLivox([&]() { { diff --git a/code/save_data.cpp b/code/save_data.cpp index fbab8c5..77473c4 100644 --- a/code/save_data.cpp +++ b/code/save_data.cpp @@ -1,6 +1,7 @@ #include "save_data.h" #include "hardware_config/mandeye.h" #include "save_laz.h" +#include "save_mlaz.h" #include #include #include @@ -46,12 +47,41 @@ void saveLidarList(const std::unordered_map& lidars, cons std::cout << "Savig lidar list of size " << lidars.size() << " to " << lidarFilePath << std::endl; std::ofstream lidarStream(lidarFilePath); + lidarStream << lidarListText(lidars); + system("sync"); + return; +} + +std::string lidarListText(const std::unordered_map& lidars) +{ + std::ostringstream text; for(const auto& [id, sn] : lidars) { - lidarStream << id << " " << sn << "\n"; + text << id << " " << sn << "\n"; } - system("sync"); - return; + return text.str(); +} + +std::pair> +savePointcloudMlaz(LidarPointsBufferPtr buffer, const std::string& directory, int chunk, const std::string& lidarList) +{ + char lidarName[256]; + const auto start = std::chrono::steady_clock::now(); + snprintf(lidarName, 256, "lidar%04d.mlaz", chunk); + std::filesystem::path lidarFilePath = std::filesystem::path(directory) / std::filesystem::path(lidarName); + std::cout << "Savig lidar buffer of size " << buffer->size() << " to " << lidarFilePath << std::endl; + auto saveStatus = saveMlaz(lidarFilePath.string(), buffer, lidarList); // fsync + rename inside + const auto end = std::chrono::steady_clock::now(); + const std::chrono::duration elapsed_seconds = end - start; + if(saveStatus) + { + saveStatus->m_saveDurationSec2 = elapsed_seconds.count(); // no OnSavedLaz: one signal per chunk, the caller decides + } + else + { + std::cout << "Error saving mlaz file " << lidarFilePath << std::endl; + } + return {lidarFilePath.string(), saveStatus}; } void saveImuData(LidarIMUBufferPtr buffer, const std::string& directory, int chunk) diff --git a/code/save_data.h b/code/save_data.h index 468957e..4a3d220 100644 --- a/code/save_data.h +++ b/code/save_data.h @@ -9,7 +9,12 @@ namespace mandeye { std::pair> savePointcloudData(LidarPointsBufferPtr buffer, const std::string& directory, int chunk); +// lidarNNNN.mlaz (lossless mLAZ); lidarList = lidarListText() of the chunk, stored in the file +std::pair> +savePointcloudMlaz(LidarPointsBufferPtr buffer, const std::string& directory, int chunk, const std::string& lidarList); void saveLidarList(const std::unordered_map& lidars, const std::string& directory, int chunk); +// content of lidarNNNN.sn: " \n" per LiDAR +std::string lidarListText(const std::unordered_map& lidars); void saveImuData(LidarIMUBufferPtr buffer, const std::string& directory, int chunk); void saveGnssData(std::deque& buffer, const std::string& directory, int chunk); void saveGnssRawData(std::deque& buffer, const std::string& directory, int chunk); diff --git a/html/index.htm b/html/index.htm index a6c75e3..d030a99 100644 --- a/html/index.htm +++ b/html/index.htm @@ -57,6 +57,10 @@ $('.msgs_imu').text(counters.imu == null ? 'N/A' : counters.imu); $('.zero_xyz_filter').text(lidar.drop_zero_xyz === true ? 'On' : lidar.drop_zero_xyz === false ? 'Off' : 'N/A'); + var pf = obj.point_format || {}; + $('.point_format').text(pf.effective == null ? 'N/A' : + pf.effective.toUpperCase() + (pf.last_chunk ? ' (last chunk: ' + pf.last_chunk + ')' : '')); + $('.point_format_warning').text(pf.warning ? 'Point format: ' + pf.warning : ''); $('.state').text( obj.state); if (obj.gnss && obj.gnss.gga) @@ -201,6 +205,7 @@ + @@ -211,6 +216,7 @@ + @@ -218,6 +224,7 @@
    LidarZero XYZ filter IMU Disk State
    -1N/A -1 -1 -1
    Lidar Zero XYZ filterPoint format IMU Disk State
    -1 N/AN/A -1 -1 -1
    +

    From f3977e49e4e8d3862dbe2ba93654a479cb8a6b01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20Fry=C5=84?= <81593823+siju-mf@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:24:32 +0000 Subject: [PATCH 4/5] Guard point_format against the web status thread; test the mLAZ error path The web server thread starts before the config is read, so point_format is set and reported under lastMlazMutex. test_save_mlaz checks that a failed mLAZ save returns nullopt without throwing and leaves no file behind (LAZ fallback relies on it). README: full commands for the test. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++++-- code/main.cpp | 16 ++++++++++------ test/mlaz/test_save_mlaz.cpp | 31 +++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f59d3ef..0dc3238 100644 --- a/README.md +++ b/README.md @@ -285,11 +285,15 @@ Each `statusNNNN.json` reports `point_format` (`configured`, `effective`, `warning` and `last_chunk`, the format the chunk was saved in) and, when mLAZ is on, `lastMlazStatus`. The web status table shows the format. -`test/mlaz` checks the mLAZ writer against the LAZ writer without LiDAR SDKs: +`test/mlaz` checks the mLAZ writer against the LAZ writer without LiDAR SDKs +(needs `libzstd-dev zlib1g-dev nlohmann-json3-dev` and Python with laspy/lazrs): ```bash +git submodule update --init 3rd/LASzip 3rd/tracy 3rd/mlaz +make -C 3rd/mlaz mlaz # the mlaz tool, decodes .mlaz +pip install "laspy[lazrs]" cmake -S test/mlaz -B build-mlaz-test && cmake --build build-mlaz-test -j -python3 test/mlaz/check_save_mlaz.py --test build-mlaz-test/test_save_mlaz --mlaz PATH/TO/mlaz +python3 test/mlaz/check_save_mlaz.py --test build-mlaz-test/test_save_mlaz --mlaz 3rd/mlaz/mlaz ``` # Installation and usage of the package diff --git a/code/main.cpp b/code/main.cpp index f986952..a80ef7f 100644 --- a/code/main.cpp +++ b/code/main.cpp @@ -49,8 +49,8 @@ std::shared_ptr gnssClientPtr; std::shared_ptr fileSystemClientPtr; std::shared_ptr publisherPtr; mandeye::LazStats lastFileSaveStats; // updated by savePointcloudData return value -mandeye::PointFormatSetting pointFormat; // "point_format" from mandeye_config.json, resolved at start -std::mutex lastMlazMutex; // guards the two below, read by the web status thread +std::mutex lastMlazMutex; // guards the three below, read by the web status thread +mandeye::PointFormatSetting pointFormat; // "point_format" from mandeye_config.json, set at start before stateWatcher runs mandeye::LazStats lastMlazSaveStats; std::string lastChunkFormat; // what the last chunk was saved as: laz, mlaz, both, laz (mlaz failed), ... double usbWriteSpeed10Mb = 0.0; @@ -154,11 +154,11 @@ std::string produceReport(bool reportUSB = true, const ZeroPointStats* zeroPoint } j["lastLazStatus"] = lastFileSaveStats.produceStatus(); - j["point_format"]["configured"] = pointFormat.configured; - j["point_format"]["effective"] = toString(pointFormat.format); - j["point_format"]["warning"] = pointFormat.warning; { std::lock_guard lock(lastMlazMutex); + j["point_format"]["configured"] = pointFormat.configured; + j["point_format"]["effective"] = toString(pointFormat.format); + j["point_format"]["warning"] = pointFormat.warning; j["point_format"]["last_chunk"] = lastChunkFormat; if(pointFormat.format != PointFormat::Laz) { @@ -899,7 +899,11 @@ int main(int argc, char** argv) mandeye::lidarSDKToUse = mandeye::configJson["lidar_sdk"].get(); } std::cout << "Lidar SDK to use from config: " << mandeye::lidarSDKToUse << std::endl; - mandeye::pointFormat = mandeye::resolvePointFormat(mandeye::configJson, mandeye::lidarSDKToUse); + { + // the web server thread already reads it + std::lock_guard lock(mandeye::lastMlazMutex); + mandeye::pointFormat = mandeye::resolvePointFormat(mandeye::configJson, mandeye::lidarSDKToUse); + } std::cout << "Point format: " << mandeye::toString(mandeye::pointFormat.format) << " (mLAZ " << MANDEYE_MLAZ_VERSION << ")" << std::endl; if(!mandeye::pointFormat.warning.empty()) { diff --git a/test/mlaz/test_save_mlaz.cpp b/test/mlaz/test_save_mlaz.cpp index 881e0fb..22b9b36 100644 --- a/test/mlaz/test_save_mlaz.cpp +++ b/test/mlaz/test_save_mlaz.cpp @@ -6,7 +6,10 @@ #include #include +#include #include +#include +#include #include using mandeye::LidarPoint; @@ -75,6 +78,33 @@ void writeCase(const std::filesystem::path& dir, const std::string& name, size_t << (mlaz ? mlaz->m_decimationStep : 0) << std::endl; } +// A failed mLAZ save (here: the file exists, the writer never replaces one) must return nullopt +// without throwing, so the controller can fall back to LAZ; no file is touched or left behind. +void checkFailedSave(const std::filesystem::path& dir) +{ + const auto path = dir / "exists.mlaz"; + { + std::ofstream f(path, std::ios::binary | std::ios::trunc); + f << "keep"; + } + std::optional stats; + bool threw = false; + try + { + stats = mandeye::saveMlaz(path.string(), makeBuffer(1000), ""); + } + catch(...) + { + threw = true; + } + std::ifstream f(path, std::ios::binary); + const std::string content((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + expect(!threw && !stats, "failed save -> nullopt, no exception"); + expect(content == "keep", "failed save -> existing file untouched"); + expect(!std::filesystem::exists(path.string() + ".part"), "failed save -> no .part left"); + std::filesystem::remove(path); +} + void checkSwitch() { using mandeye::PointFormat; @@ -114,6 +144,7 @@ int main(int argc, char** argv) const std::filesystem::path dir = argv[1]; std::filesystem::create_directories(dir); checkSwitch(); + checkFailedSave(dir); writeCase(dir, "small", 123457); // several mLAZ frames, last one partial writeCase(dir, "empty", 0); writeCase(dir, "one", 1); From 274840ba3026bea19e039e28fee58aaf114e29f6 Mon Sep 17 00:00:00 2001 From: Dariusz Lubomski Date: Sat, 5 Dec 2026 07:36:35 +0100 Subject: [PATCH 5/5] Install the mLAZ build dependencies in CI --- .github/workflows/sanity-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sanity-build.yml b/.github/workflows/sanity-build.yml index dc9f07b..2573317 100644 --- a/.github/workflows/sanity-build.yml +++ b/.github/workflows/sanity-build.yml @@ -34,7 +34,7 @@ jobs: apt-get install -y -qq --no-install-recommends \ build-essential cmake git pkg-config ca-certificates \ libserial-dev libgpiod-dev libzmq3-dev libboost-all-dev \ - libpistache-dev rapidjson-dev nlohmann-json3-dev cppzmq-dev pps-tools + libpistache-dev rapidjson-dev nlohmann-json3-dev cppzmq-dev pps-tools zlib1g-dev libzstd-dev update-ca-certificates - name: Install Clang and clang-tidy