diff --git a/README.md b/README.md index a40a1b1..22a388d 100644 --- a/README.md +++ b/README.md @@ -225,9 +225,34 @@ You can set the SDK to use in two ways: } ``` +## Livox point tag in LAZ and mLAZ files + +Each Livox point carries a tag byte (Mid-360 protocol, point cloud data +1.2.1.3.4): bits 0-1 confidence of adjacent-object stickiness, bits 2-3 rain, +fog or dust, bits 4-5 other, bits 6-7 reserved. Every point record (LAS 1.2, +point format 1) stores it twice: + +| Field | Value | +|-------------------|--------------------------------------------------------| +| `point_source_ID` | the whole tag byte (0-255) | +| `classification` | `tag & 0x1F`, bits 0-4 only, as in older files | + +Files from older firmware have `point_source_ID` 0; their `classification` is +the same. The LAZ and mLAZ writers fill both fields the same way; other LiDARs +write tag 0. + +Each Livox `statusNNNN.json` reports `lidar.last_chunk_livox_tag`, a histogram +of the tag byte for the points of that chunk kept in the buffer (after the zero +filter, before decimation), in total and per head (`by_head` with `handle` and +`serial_number`). `histogram` maps a tag value to its point count and leaves out +values with no points; `bits_5_7_points` counts the points whose tag has bit 5, +6 or 7 set, which `classification` does not show. The value is `null` until the +first chunk of a scan is saved. + ## Point-cloud format: LAZ or lossless mLAZ -By default every chunk is saved as `lidarNNNN.laz`, exactly as before. The +By default every chunk is saved as `lidarNNNN.laz`, as before (Livox points +also carry the full tag in `point_source_ID`, see "Livox point tag" above). 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 diff --git a/code/lidars/BaseLidarClient.h b/code/lidars/BaseLidarClient.h index 62d85a0..041397b 100644 --- a/code/lidars/BaseLidarClient.h +++ b/code/lidars/BaseLidarClient.h @@ -12,7 +12,7 @@ struct LidarPoint float y{0}; //! Y coordinate in meters float z{0}; //! Z coordinate in meters float intensity{0}; //! Intensity of the point, usually 0-255 - uint8_t tag{0}; //! Lidar-specific point tag (e.g. Livox tag), saved as LAZ classification + uint8_t tag{0}; //! Lidar-specific point tag (e.g. Livox tag), saved as point_source_ID and (bits 0-4) classification uint64_t timestamp{0}; //! Timestamp in nanoseconds, 0 if not set uint8_t line_id{0}; //! Line ID, used to identify the laser that produced this point uint16_t laser_id{0}; //! Laser ID, used to identify the laser that produced this point diff --git a/code/lidars/livoxsdk2/LivoxClient.cpp b/code/lidars/livoxsdk2/LivoxClient.cpp index 11fd780..6bad01a 100644 --- a/code/lidars/livoxsdk2/LivoxClient.cpp +++ b/code/lidars/livoxsdk2/LivoxClient.cpp @@ -89,6 +89,10 @@ nlohmann::json LivoxClient::produceStatus() { data["counters"]["lidar"] = 0; } + { + std::lock_guard lock(m_lastChunkTagsMutex); + data["last_chunk_livox_tag"] = m_lastChunkTags ? m_lastChunkTags->produceStatus() : nlohmann::json(nullptr); + } std::lock_guard lcK1(m_bufferLidarMutex); std::lock_guard lcK2(m_bufferImuMutex); @@ -163,6 +167,9 @@ void LivoxClient::startLog() std::lock_guard lcK2(m_bufferImuMutex); m_bufferLivoxPtr = std::make_shared(); m_bufferIMUPtr = std::make_shared(); + m_tagsByHandle.clear(); + std::lock_guard lcK3(m_lastChunkTagsMutex); + m_lastChunkTags.reset(); } void LivoxClient::stopLog() @@ -171,17 +178,33 @@ void LivoxClient::stopLog() std::lock_guard lcK2(m_bufferImuMutex); m_bufferLivoxPtr = nullptr; m_bufferIMUPtr = nullptr; + m_tagsByHandle.clear(); // m_lastChunkTags stays: the status of the scan's last chunk is saved after stopLog() } 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); + LivoxTagStats tags; + { + std::lock_guard lck1(m_bufferLidarMutex); + std::lock_guard lck2(m_bufferImuMutex); + std::swap(m_bufferIMUPtr, returnPointerImu); + std::swap(m_bufferLivoxPtr, returnPointerLidar); + std::swap(m_tagsByHandle, tags.byHandle); + } + { + std::lock_guard lock(m_lidarInfoMutex); + for(const auto& [handle, serial] : m_handleToSerialNumber) + { + tags.byHandle[handle].serialNumber = serial; + } + } + { + std::lock_guard lock(m_lastChunkTagsMutex); + m_lastChunkTags = std::move(tags); + } + return {returnPointerLidar, returnPointerImu}; } void LivoxClient::testThread() { @@ -289,7 +312,7 @@ 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& tags = this_ptr->m_tagsByHandle[handle]; for(uint32_t i = 0; i < data->dot_num; i++) { LidarPoint point; @@ -304,6 +327,7 @@ void LivoxClient::PointCloudCallback(uint32_t handle, const uint8_t dev_type, Li if(point.timestamp > 0 && (point.x != 0 || point.y != 0 || point.z != 0)) { buffer->push_back(point); + tags.record(point.tag); } } } diff --git a/code/lidars/livoxsdk2/LivoxClient.h b/code/lidars/livoxsdk2/LivoxClient.h index 5309d5b..99ca874 100644 --- a/code/lidars/livoxsdk2/LivoxClient.h +++ b/code/lidars/livoxsdk2/LivoxClient.h @@ -1,6 +1,7 @@ #pragma once #include "lidars/BaseLidarClient.h" +#include "lidars/livoxsdk2/LivoxTagStats.h" #include "livox_lidar_def.h" #include "utils/TimeStampProvider.h" #include @@ -55,6 +56,12 @@ class LivoxClient : public BaseLidarClient LidarPointsBufferPtr m_bufferLivoxPtr{nullptr}; LidarIMUBufferPtr m_bufferIMUPtr{nullptr}; + //! Tag histogram of the points buffered for the current chunk (guarded by m_bufferLidarMutex). + std::map m_tagsByHandle; + //! Tag histogram of the last retrieved chunk, reported by produceStatus() (so in statusNNNN.json). + //! Kept after stopLog(), so the last chunk of a scan is reported too; cleared by startLog(). + std::mutex m_lastChunkTagsMutex; + std::optional m_lastChunkTags; std::mutex m_timestampMutex; uint64_t m_timestamp{0}; diff --git a/code/lidars/livoxsdk2/LivoxTagStats.h b/code/lidars/livoxsdk2/LivoxTagStats.h new file mode 100644 index 0000000..b688577 --- /dev/null +++ b/code/lidars/livoxsdk2/LivoxTagStats.h @@ -0,0 +1,71 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace mandeye +{ + +// Histogram of the Livox point tag byte (Mid-360 protocol 1.2.1.3.4: bits 0-1 adjacent-object +// confidence, 2-3 rain/fog/dust, 4-5 other, 6-7 reserved). The LAS classification keeps only bits 0-4, +// so bits_5_7_points counts the points whose tag the classification alone does not show. +struct LivoxTagCounts +{ + std::array counts{}; + + void record(uint8_t tag) + { + ++counts[tag]; + } + + nlohmann::json produceStatus() const + { + uint64_t points = 0; + uint64_t bits57 = 0; + auto histogram = nlohmann::json::object(); // "tag value" -> points, tags without points left out + for(size_t tag = 0; tag < counts.size(); tag++) + { + if(!counts[tag]) + continue; + points += counts[tag]; + if(tag & 0xE0) + bits57 += counts[tag]; + histogram[std::to_string(tag)] = counts[tag]; + } + return {{"points", points}, {"bits_5_7_points", bits57}, {"histogram", std::move(histogram)}}; + } +}; + +struct LivoxTagStats +{ + struct Head : LivoxTagCounts + { + std::string serialNumber; + }; + + std::map byHandle; + + nlohmann::json produceStatus() const + { + LivoxTagCounts total; + auto heads = nlohmann::json::array(); + for(const auto& [handle, head] : byHandle) + { + for(size_t tag = 0; tag < head.counts.size(); tag++) + total.counts[tag] += head.counts[tag]; + auto entry = head.produceStatus(); + 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(); + status["by_head"] = std::move(heads); + return status; + } +}; + +} // namespace mandeye diff --git a/code/save_laz.cpp b/code/save_laz.cpp index 9bf8571..2f43f2e 100644 --- a/code/save_laz.cpp +++ b/code/save_laz.cpp @@ -149,7 +149,8 @@ std::optional mandeye::saveLaz(const std::string& filename, L const auto& p = buffer->at(i); point->intensity = p.intensity; point->gps_time = p.timestamp * 1e-9; - point->classification = p.tag; + point->classification = p.tag; // LAS 1.2 keeps bits 0-4 only + point->point_source_ID = p.tag; // full tag byte (Livox: bits 5-7 too) point->user_data = p.laser_id; p_count++; coordinates[0] = p.x; diff --git a/code/save_mlaz.cpp b/code/save_mlaz.cpp index 32ed642..2a5787e 100644 --- a/code/save_mlaz.cpp +++ b/code/save_mlaz.cpp @@ -195,7 +195,7 @@ try 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 + put16(r + 18, p.tag); // point_source_ID: full tag byte, as saveLaz() putF64(r + 20, p.timestamp * 1e-9); // gps_time if(++inBatch == options.block) { diff --git a/test/mlaz/CMakeLists.txt b/test/mlaz/CMakeLists.txt index 565803c..112d438 100644 --- a/test/mlaz/CMakeLists.txt +++ b/test/mlaz/CMakeLists.txt @@ -2,7 +2,7 @@ # 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. +# to compare its LAZ files with check_save_mlaz.py --laz-base. cmake_minimum_required(VERSION 3.13) project(mandeye_mlaz_test C CXX) set(CMAKE_CXX_STANDARD 17) diff --git a/test/mlaz/check_save_mlaz.py b/test/mlaz/check_save_mlaz.py index a8b1ed1..98ef8b1 100644 --- a/test/mlaz/check_save_mlaz.py +++ b/test/mlaz/check_save_mlaz.py @@ -7,22 +7,47 @@ (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. + 3. the serial-number text stored in .mlaz comes back unchanged; + 4. the full LiDAR tag byte is kept: point_source_ID == tag and the whole classification byte == + tag & 0x1F, record by record (test buffers have tag = buffer index % 256), all 256 values present. +Optional --laz-base DIR: NAME.las and NAME.laz written by test_save_mlaz built with the save_laz.cpp of +the firmware before the full tag (point_source_ID 0) must differ from the ones written here only in the +point_source_ID bytes: header and VLRs byte-identical, records identical with bytes 18..19 masked. - check_save_mlaz.py --test BUILD/test_save_mlaz --mlaz PATH/mlaz [--out DIR] [--laz-ref DIR] + check_save_mlaz.py --test BUILD/test_save_mlaz --mlaz PATH/mlaz [--out DIR] [--laz-base DIR] """ import argparse +import math import pathlib import subprocess import sys import tempfile -CASES = ["small", "empty", "one", "decimated"] +import numpy as np + +# name -> points in the LidarPoint buffer (test_save_mlaz.cpp) +CASES = {"small": 123457, "empty": 0, "one": 1, "decimated": 4500001} SN = b"0 47MDL9A0020061\n" SOFTWARE = slice(58, 90) HEADER = 227 +RECORD = 28 +CLASSIFICATION = 15 +POINT_SOURCE_ID = slice(18, 20) + + +def decimation_step(n): + """saveLaz(): every point up to 4 mln, otherwise every ceil(n / 2 mln)-th.""" + return math.ceil(n / 2000000.0) if n > 4000000 else 1 + + +def records(raw): + return np.frombuffer(raw, dtype=np.uint8).reshape(-1, RECORD) + + +def without_source_id(recs): + r = recs.copy() + r[:, POINT_SOURCE_ID] = 0 + return r def main(): @@ -30,7 +55,7 @@ def main(): ap.add_argument("--test", required=True) ap.add_argument("--mlaz", required=True) ap.add_argument("--out") - ap.add_argument("--laz-ref") + ap.add_argument("--laz-base") a = ap.parse_args() import laspy # with the lazrs backend @@ -45,7 +70,7 @@ def check(ok, what): print(("ok " if ok else "FAIL ") + what) fails += not ok - for name in CASES: + for name, size in CASES.items(): 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) @@ -59,13 +84,39 @@ def check(ok, what): 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") + check(len(recs) == n * RECORD 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}") + + step = decimation_step(size) + tags = (np.arange(n, dtype=np.int64) * step % 256).astype(np.uint16) + r = records(recs) + source_id = r[:, POINT_SOURCE_ID].copy().view("= 256: + check(len(np.unique(source_id)) == 256, f"{name}: all 256 tag values in point_source_ID") + + if a.laz_base: + base = pathlib.Path(a.laz_base) + bl = (base / f"{name}.las").read_bytes() + off = int.from_bytes(las[96:100], "little") + ok = len(bl) == len(las) and bl[:off] == las[:off] + if ok: + br, nr = records(bl[off:]), records(las[off:]) + ok = not br[:, POINT_SOURCE_ID].any() and np.array_equal(without_source_id(br), without_source_id(nr)) + check(ok, f"{name}: .las vs base: header equal, records differ only in point_source_ID (0 in base)") + + blz_raw, lz_raw = (base / f"{name}.laz").read_bytes(), (out / f"{name}.laz").read_bytes() + off = int.from_bytes(lz_raw[96:100], "little") + blz = laspy.read(base / f"{name}.laz") + br, nr = records(blz.points.array.tobytes()), r + ok = (blz_raw[:off] == lz_raw[:off] and br.shape == nr.shape and not br[:, POINT_SOURCE_ID].any() + and np.array_equal(without_source_id(br), without_source_id(nr))) + check(ok, f"{name}: .laz vs base: header and VLRs equal, records (laspy) differ only in point_source_ID") print("ALL OK" if not fails else f"{fails} FAILED") return 1 if fails else 0 diff --git a/test/mlaz/test_save_mlaz.cpp b/test/mlaz/test_save_mlaz.cpp index 22b9b36..245e0bd 100644 --- a/test/mlaz/test_save_mlaz.cpp +++ b/test/mlaz/test_save_mlaz.cpp @@ -1,6 +1,7 @@ // 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 "lidars/livoxsdk2/LivoxTagStats.h" #include "save_laz.h" #include "save_mlaz.h" @@ -29,7 +30,8 @@ void expect(bool ok, const std::string& what) } } -// Deterministic buffer covering values the LAS record has to cut down: tag bits 5-7, laser_id > 255, +// Deterministic buffer covering values the LAS record has to cut down or keep: tag = i % 256 (all bits; +// classification keeps bits 0-4, point_source_ID the whole byte - check_save_mlaz.py relies on it), laser_id > 255, // fractional and > 255 intensity, negative/zero/far coordinates, nanosecond timestamps near 2026. LidarPointsBufferPtr makeBuffer(size_t n) { @@ -132,6 +134,51 @@ void checkSwitch() 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"); } + +// Livox tag histogram reported in statusNNNN.json (lidar.last_chunk_livox_tag). +void checkTagStats() +{ + mandeye::LivoxTagStats empty; + auto j = empty.produceStatus(); + expect(j["points"] == 0 && j["bits_5_7_points"] == 0 && j["histogram"].empty() && j["by_head"].empty(), "tag stats: no heads -> zero counts"); + + mandeye::LivoxTagStats stats; + auto& a = stats.byHandle[7]; + a.serialNumber = "47MDL9A0020061"; + for(int tag = 0; tag < 256; tag++) + for(int k = 0; k <= tag % 3; k++) // tag t counted t%3+1 times + a.record(uint8_t(tag)); + auto& b = stats.byHandle[9]; // head without serial number + b.record(0x20); + b.record(0x20); + b.record(0x01); + stats.byHandle[11]; // discovered head that sent no points + + uint64_t pointsA = 0, bitsA = 0; + for(int tag = 0; tag < 256; tag++) + { + pointsA += tag % 3 + 1; + bitsA += (tag & 0xE0) ? tag % 3 + 1 : 0; + } + j = stats.produceStatus(); + const auto& heads = j["by_head"]; + expect(heads.size() == 3, "tag stats: one entry per head"); + const auto& ja = heads[0]; + bool histogramOk = ja["histogram"].size() == 256; + for(int tag = 0; tag < 256 && histogramOk; tag++) + histogramOk = ja["histogram"].value(std::to_string(tag), uint64_t(0)) == uint64_t(tag % 3 + 1); + expect(ja["handle"] == 7 && ja["serial_number"] == "47MDL9A0020061", "tag stats: handle and serial number"); + expect(histogramOk, "tag stats: all 256 tag values counted"); + expect(ja["points"] == pointsA && ja["bits_5_7_points"] == bitsA, "tag stats: head points and bits 5-7 points"); + const auto& jb = heads[1]; + expect(jb["serial_number"].is_null() && jb["points"] == 3 && jb["bits_5_7_points"] == 2 && + jb["histogram"] == nlohmann::json({{"1", 1}, {"32", 2}}), + "tag stats: sparse histogram, null serial number"); + const auto& jc = heads[2]; + expect(jc["points"] == 0 && jc["histogram"].empty(), "tag stats: head without points"); + expect(j["points"] == pointsA + 3 && j["bits_5_7_points"] == bitsA + 2 && j["histogram"]["32"] == 3 + 2, + "tag stats: totals over heads"); // tag 32: 32%3+1 = 3 from head 7, 2 from head 9 +} } // namespace int main(int argc, char** argv) @@ -144,6 +191,7 @@ int main(int argc, char** argv) const std::filesystem::path dir = argv[1]; std::filesystem::create_directories(dir); checkSwitch(); + checkTagStats(); checkFailedSave(dir); writeCase(dir, "small", 123457); // several mLAZ frames, last one partial writeCase(dir, "empty", 0);