Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion code/lidars/BaseLidarClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 30 additions & 6 deletions code/lidars/livoxsdk2/LivoxClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ nlohmann::json LivoxClient::produceStatus()
{
data["counters"]["lidar"] = 0;
}
{
std::lock_guard<std::mutex> lock(m_lastChunkTagsMutex);
data["last_chunk_livox_tag"] = m_lastChunkTags ? m_lastChunkTags->produceStatus() : nlohmann::json(nullptr);
}

std::lock_guard<std::mutex> lcK1(m_bufferLidarMutex);
std::lock_guard<std::mutex> lcK2(m_bufferImuMutex);
Expand Down Expand Up @@ -163,6 +167,9 @@ void LivoxClient::startLog()
std::lock_guard<std::mutex> lcK2(m_bufferImuMutex);
m_bufferLivoxPtr = std::make_shared<LidarPointsBuffer>();
m_bufferIMUPtr = std::make_shared<LidarIMUBuffer>();
m_tagsByHandle.clear();
std::lock_guard<std::mutex> lcK3(m_lastChunkTagsMutex);
m_lastChunkTags.reset();
}

void LivoxClient::stopLog()
Expand All @@ -171,17 +178,33 @@ void LivoxClient::stopLog()
std::lock_guard<std::mutex> 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<LidarPointsBufferPtr, LidarIMUBufferPtr> LivoxClient::retrieveData()
{
std::lock_guard<std::mutex> lck1(m_bufferLidarMutex);
std::lock_guard<std::mutex> lck2(m_bufferImuMutex);
LidarPointsBufferPtr returnPointerLidar{std::make_shared<LidarPointsBuffer>()};
LidarIMUBufferPtr returnPointerImu{std::make_shared<LidarIMUBuffer>()};
std::swap(m_bufferIMUPtr, returnPointerImu);
std::swap(m_bufferLivoxPtr, returnPointerLidar);
return std::pair<LidarPointsBufferPtr, LidarIMUBufferPtr>(returnPointerLidar, returnPointerImu);
LivoxTagStats tags;
{
std::lock_guard<std::mutex> lck1(m_bufferLidarMutex);
std::lock_guard<std::mutex> lck2(m_bufferImuMutex);
std::swap(m_bufferIMUPtr, returnPointerImu);
std::swap(m_bufferLivoxPtr, returnPointerLidar);
std::swap(m_tagsByHandle, tags.byHandle);
}
{
std::lock_guard<std::mutex> lock(m_lidarInfoMutex);
for(const auto& [handle, serial] : m_handleToSerialNumber)
{
tags.byHandle[handle].serialNumber = serial;
}
}
{
std::lock_guard<std::mutex> lock(m_lastChunkTagsMutex);
m_lastChunkTags = std::move(tags);
}
return {returnPointerLidar, returnPointerImu};
}
void LivoxClient::testThread()
{
Expand Down Expand Up @@ -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;
Expand All @@ -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);
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions code/lidars/livoxsdk2/LivoxClient.h
Original file line number Diff line number Diff line change
@@ -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 <atomic>
Expand Down Expand Up @@ -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<uint32_t, LivoxTagStats::Head> 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<LivoxTagStats> m_lastChunkTags;

std::mutex m_timestampMutex;
uint64_t m_timestamp{0};
Expand Down
71 changes: 71 additions & 0 deletions code/lidars/livoxsdk2/LivoxTagStats.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#pragma once

#include <array>
#include <cstdint>
#include <map>
#include <nlohmann/json.hpp>
#include <string>
#include <utility>

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<uint64_t, 256> 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<uint32_t, Head> 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
3 changes: 2 additions & 1 deletion code/save_laz.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ std::optional<mandeye::LazStats> 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;
Expand Down
2 changes: 1 addition & 1 deletion code/save_mlaz.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<uint8_t>(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)
{
Expand Down
2 changes: 1 addition & 1 deletion test/mlaz/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
73 changes: 62 additions & 11 deletions test/mlaz/check_save_mlaz.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,55 @@
(LAS header bytes 58..89), which must be "Mandeye mLAZ <version>";
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():
ap = argparse.ArgumentParser()
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

Expand All @@ -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)
Expand All @@ -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("<u2").ravel()
check(n == len(range(0, size, step)) and np.array_equal(source_id, tags),
f"{name}: point_source_ID == tag for all {n} LAZ records (step {step})")
check(np.array_equal(r[:, CLASSIFICATION], (tags & 0x1F).astype(np.uint8)),
f"{name}: classification byte == tag & 0x1F (no flag bits set)")
if size >= 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
Expand Down
Loading
Loading