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 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 7c7e305..5ce829d 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) @@ -251,6 +255,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/README.md b/README.md index 9a57dd2..a40a1b1 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 @@ -225,6 +225,55 @@ You can set the SDK to use in two ways: } ``` +## 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 +(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 3rd/mlaz/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/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/main.cpp b/code/main.cpp index 424813a..68bb173 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 +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; double usbWriteSpeed1Mb = 0.0; @@ -149,6 +154,17 @@ std::string produceReport(bool reportUSB = true) } j["lastLazStatus"] = lastFileSaveStats.produceStatus(); + { + 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) + { + j["lastMlazStatus"] = lastMlazSaveStats.produceStatus(); + } + } std::ostringstream s; s << std::setw(4) << j; @@ -260,6 +276,57 @@ void saveStatusData(const std::string& directory, int chunk) 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; @@ -510,12 +577,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); - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); + auto lidarList = mlazLidarList ? *mlazLidarList : lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); if(gnssClientPtr) { @@ -607,12 +672,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); - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); + auto lidarList = mlazLidarList ? *mlazLidarList : lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, continousScanDirectory, chunksInExperimentCS + chunksInExperimentSS); if(gnssClientPtr) @@ -702,13 +765,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); - auto lidarList = lidarClientPtr->getSerialNumberToLidarIdMapping(); + auto lidarList = mlazLidarList ? *mlazLidarList : lidarClientPtr->getSerialNumberToLidarIdMapping(); saveLidarList(lidarList, stopScanDirectory, chunksInExperimentCS + chunksInExperimentSS); if(gnssClientPtr) @@ -834,6 +895,16 @@ 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; + { + // 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()) + { + 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/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/html/index.htm b/html/index.htm index eceb2c2..094dc13 100644 --- a/html/index.htm +++ b/html/index.htm @@ -53,6 +53,10 @@ $('.msgs_lidar').text( obj.lidar.counters.lidar); $('.msgs_imu').text( obj.lidar.counters.imu); + 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.hasOwnProperty('gnss')) @@ -196,6 +200,7 @@ + @@ -205,6 +210,7 @@ + @@ -212,6 +218,7 @@
LidarPoint format IMU Disk State
-1N/A -1 -1 -1
+

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..22b9b36 --- /dev/null +++ b/test/mlaz/test_save_mlaz.cpp @@ -0,0 +1,154 @@ +// 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 +#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; +} + +// 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; + 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(); + checkFailedSave(dir); + 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; +}