unitree_webrtc_connect 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ # Monkey-patch aioice.Connection to use a fixed username and password accross all instances.
2
+
3
+ import aioice
4
+
5
+
6
+ class Connection(aioice.Connection):
7
+ local_username = aioice.utils.random_string(4)
8
+ local_password = aioice.utils.random_string(22)
9
+
10
+ def __init__(self, *args, **kwargs):
11
+ super().__init__(*args, **kwargs)
12
+ self.local_username = Connection.local_username
13
+ self.local_password = Connection.local_password
14
+
15
+
16
+ aioice.Connection = Connection # type: ignore
17
+
18
+
19
+ # Monkey-patch aiortc.rtcdtlstransport.X509_DIGEST_ALGORITHMS to remove extra SHA algorithms
20
+ # Extra SHA algorithms introduced in aiortc 1.10.0 causes Unity Go2 to use the new SCTP format, despite aiortc using the old SCTP syntax.
21
+ # This new format is not supported by aiortc version as of today (2025-06-02)
22
+
23
+
24
+ import aiortc
25
+ from packaging.version import Version
26
+
27
+
28
+ if Version(aiortc.__version__) == Version("1.10.0"):
29
+ X509_DIGEST_ALGORITHMS = {
30
+ "sha-256": "SHA256",
31
+ }
32
+ aiortc.rtcdtlstransport.X509_DIGEST_ALGORITHMS = X509_DIGEST_ALGORITHMS
33
+
34
+ elif Version(aiortc.__version__) >= Version("1.11.0"):
35
+ # Syntax changed in aiortc 1.11.0, so we need to use the hashes module
36
+ from cryptography.hazmat.primitives import hashes
37
+
38
+ X509_DIGEST_ALGORITHMS = {
39
+ "sha-256": hashes.SHA256(), # type: ignore
40
+ }
41
+ aiortc.rtcdtlstransport.X509_DIGEST_ALGORITHMS = X509_DIGEST_ALGORITHMS
@@ -0,0 +1,203 @@
1
+ from enum import Enum
2
+
3
+ DATA_CHANNEL_TYPE = {
4
+ "VALIDATION": "validation",
5
+ "SUBSCRIBE": "subscribe",
6
+ "UNSUBSCRIBE": "unsubscribe",
7
+ "MSG": "msg",
8
+ "REQUEST": "req",
9
+ "RESPONSE": "res",
10
+ "VID": "vid",
11
+ "AUD": "aud",
12
+ "ERR": "err",
13
+ "HEARTBEAT": "heartbeat",
14
+ "RTC_INNER_REQ": "rtc_inner_req",
15
+ "RTC_REPORT": "rtc_report",
16
+ "ADD_ERROR": "add_error",
17
+ "RM_ERROR": "rm_error",
18
+ "ERRORS": "errors",
19
+ }
20
+
21
+ class WebRTCConnectionMethod(Enum):
22
+ LocalAP = 1
23
+ LocalSTA = 2
24
+ Remote = 3
25
+
26
+ app_error_messages = {
27
+ "app_error_code_100_1": "DDS message timeout",
28
+ "app_error_code_100_10": "Battery communication error",
29
+ "app_error_code_100_2": "Distribution switch abnormal",
30
+ "app_error_code_100_20": "Abnormal mote control communication",
31
+ "app_error_code_100_40": "MCU communication error",
32
+ "app_error_code_100_80": "Motor communication error",
33
+ "app_error_code_200_1": "Rear left fan jammed",
34
+ "app_error_code_200_2": "Rear right fan jammed",
35
+ "app_error_code_200_4": "Front fan jammed",
36
+ "app_error_code_300_1": "Overcurrent",
37
+ "app_error_code_300_10": "Winding overheating",
38
+ "app_error_code_300_100": "Motor communication interruption",
39
+ "app_error_code_300_2": "Overvoltage",
40
+ "app_error_code_300_20": "Encoder abnormal",
41
+ "app_error_code_300_4": "Driver overheating",
42
+ "app_error_code_300_8": "Generatrix undervoltage",
43
+ "app_error_code_400_1": "Motor rotate speed abnormal",
44
+ "app_error_code_400_10": "Abnormal dirt index",
45
+ "app_error_code_400_2": "PointCloud data abnormal",
46
+ "app_error_code_400_4": "Serial port data abnormal",
47
+ "app_error_code_500_1": "UWB serial port open abnormal",
48
+ "app_error_code_500_2": "Robot dog information retrieval abnormal",
49
+ "app_error_code_600_4": "Overheating software protection",
50
+ "app_error_code_600_8": "Low battery software protection",
51
+ "app_error_source_100": "Communication firmware malfunction",
52
+ "app_error_source_200": "Communication firmware malfunction",
53
+ "app_error_source_300": "Motor malfunction",
54
+ "app_error_source_400": "Radar malfunction",
55
+ "app_error_source_500": "UWB malfunction",
56
+ "app_error_source_600": "Motion Control",
57
+ "app_error_wheel_300_100": "Motor Communication Interruption",
58
+ "app_error_wheel_300_40": "Calibration Data Abnormality",
59
+ "app_error_wheel_300_80": "Abnormal Reset"
60
+ }
61
+
62
+ RTC_TOPIC = {
63
+ "LOW_STATE": "rt/lf/lowstate",
64
+ "MULTIPLE_STATE": "rt/multiplestate",
65
+ "FRONT_PHOTO_REQ": "rt/api/videohub/request",
66
+ "ULIDAR_SWITCH": "rt/utlidar/switch",
67
+ "ULIDAR": "rt/utlidar/voxel_map",
68
+ "ULIDAR_ARRAY": "rt/utlidar/voxel_map_compressed",
69
+ "ULIDAR_STATE": "rt/utlidar/lidar_state",
70
+ "ROBOTODOM": "rt/utlidar/robot_pose",
71
+ "UWB_REQ": "rt/api/uwbswitch/request",
72
+ "UWB_STATE": "rt/uwbstate",
73
+ "LOW_CMD": "rt/lowcmd",
74
+ "WIRELESS_CONTROLLER": "rt/wirelesscontroller",
75
+ "SPORT_MOD": "rt/api/sport/request",
76
+ "SPORT_MOD_STATE": "rt/sportmodestate",
77
+ "LF_SPORT_MOD_STATE": "rt/lf/sportmodestate",
78
+ "BASH_REQ": "rt/api/bashrunner/request",
79
+ "SELF_TEST": "rt/selftest",
80
+ "GRID_MAP": "rt/mapping/grid_map",
81
+ "SERVICE_STATE": "rt/servicestate",
82
+ "GPT_FEEDBACK": "rt/gptflowfeedback",
83
+ "VUI": "rt/api/vui/request",
84
+ "OBSTACLES_AVOID": "rt/api/obstacles_avoid/request",
85
+ "SLAM_QT_COMMAND": "rt/qt_command",
86
+ "SLAM_ADD_NODE": "rt/qt_add_node",
87
+ "SLAM_ADD_EDGE": "rt/qt_add_edge",
88
+ "SLAM_QT_NOTICE": "rt/qt_notice",
89
+ "SLAM_PC_TO_IMAGE_LOCAL": "rt/pctoimage_local",
90
+ "SLAM_ODOMETRY": "rt/lio_sam_ros2/mapping/odometry",
91
+ "ARM_COMMAND": "rt/arm_Command",
92
+ "ARM_FEEDBACK": "rt/arm_Feedback",
93
+ "AUDIO_HUB_REQ": "rt/api/audiohub/request",
94
+ "AUDIO_HUB_PLAY_STATE": "rt/audiohub/player/state",
95
+ "GAS_SENSOR": "rt/gas_sensor",
96
+ "GAS_SENSOR_REQ": "rt/api/gas_sensor/request",
97
+ "LIDAR_MAPPING_CMD": "rt/uslam/client_command",
98
+ "LIDAR_MAPPING_CLOUD_POINT": "rt/uslam/frontend/cloud_world_ds",
99
+ "LIDAR_MAPPING_ODOM": "rt/uslam/frontend/odom",
100
+ "LIDAR_MAPPING_PCD_FILE": "rt/uslam/cloud_map",
101
+ "LIDAR_MAPPING_SERVER_LOG": "rt/uslam/server_log",
102
+ "LIDAR_LOCALIZATION_ODOM": "rt/uslam/localization/odom",
103
+ "LIDAR_NAVIGATION_GLOBAL_PATH": "rt/uslam/navigation/global_path",
104
+ "LIDAR_LOCALIZATION_CLOUD_POINT": "rt/uslam/localization/cloud_world",
105
+ "PROGRAMMING_ACTUATOR_CMD": "rt/programming_actuator/command",
106
+ "ASSISTANT_RECORDER": "rt/api/assistant_recorder/request",
107
+ "MOTION_SWITCHER": "rt/api/motion_switcher/request"
108
+ }
109
+
110
+ SPORT_CMD = {
111
+ "Damp": 1001,
112
+ "BalanceStand": 1002,
113
+ "StopMove": 1003,
114
+ "StandUp": 1004,
115
+ "StandDown": 1005,
116
+ "RecoveryStand": 1006,
117
+ "Euler": 1007,
118
+ "Move": 1008,
119
+ "Sit": 1009,
120
+ "RiseSit": 1010,
121
+ "SwitchGait": 1011,
122
+ "Trigger": 1012,
123
+ "BodyHeight": 1013,
124
+ "FootRaiseHeight": 1014,
125
+ "SpeedLevel": 1015,
126
+ "Hello": 1016,
127
+ "Stretch": 1017,
128
+ "TrajectoryFollow": 1018,
129
+ "ContinuousGait": 1019,
130
+ "Content": 1020,
131
+ "Wallow": 1021,
132
+ "Dance1": 1022,
133
+ "Dance2": 1023,
134
+ "GetBodyHeight": 1024,
135
+ "GetFootRaiseHeight": 1025,
136
+ "GetSpeedLevel": 1026,
137
+ "SwitchJoystick": 1027,
138
+ "Pose": 1028,
139
+ "Scrape": 1029,
140
+ "FrontFlip": 1030,
141
+ "LeftFlip": 1042,
142
+ "RightFlip": 1043,
143
+ "BackFlip": 1044,
144
+ "FrontJump": 1031,
145
+ "FrontPounce": 1032,
146
+ "WiggleHips": 1033,
147
+ "GetState": 1034,
148
+ "EconomicGait": 1035,
149
+ "LeadFollow": 1045,
150
+ "FingerHeart": 1036,
151
+ "Bound": 1304,
152
+ "MoonWalk": 1305,
153
+ "OnesidedStep": 1303,
154
+ "CrossStep": 1302,
155
+ "Handstand": 1301,
156
+ "StandOut": 1039,
157
+ "FreeWalk": 1045,
158
+ "Standup": 1050,
159
+ "CrossWalk": 1051
160
+ }
161
+
162
+ class VUI_COLOR:
163
+ WHITE: str = 'white'
164
+ RED: str = 'red'
165
+ YELLOW: str = 'yellow'
166
+ BLUE: str = 'blue'
167
+ GREEN: str = 'green'
168
+ CYAN: str = 'cyan'
169
+ PURPLE: str = 'purple'
170
+
171
+ # Audio API IDs
172
+ AUDIO_API = {
173
+ # Audio Player Commands
174
+ "GET_AUDIO_LIST": 1001,
175
+ "SELECT_START_PLAY": 1002,
176
+ "PAUSE": 1003,
177
+ "UNSUSPEND": 1004,
178
+ "SELECT_PREV_START_PLAY": 1005,
179
+ "SELECT_NEXT_START_PLAY": 1006,
180
+ "SET_PLAY_MODE": 1007,
181
+ "SELECT_RENAME": 1008,
182
+ "SELECT_DELETE": 1009,
183
+ "GET_PLAY_MODE": 1010,
184
+
185
+ # Audio Upload
186
+ "UPLOAD_AUDIO_FILE": 2001,
187
+
188
+ # Internal Corpus
189
+ "PLAY_START_OBSTACLE_AVOIDANCE": 3001,
190
+ "PLAY_EXIT_OBSTACLE_AVOIDANCE": 3002,
191
+ "PLAY_START_COMPANION_MODE": 3003,
192
+ "PLAY_EXIT_COMPANION_MODE": 3004,
193
+
194
+ # Megaphone
195
+ "ENTER_MEGAPHONE": 4001,
196
+ "EXIT_MEGAPHONE": 4002,
197
+ "UPLOAD_MEGAPHONE": 4003,
198
+
199
+ # Internal Long Corpus
200
+ "INTERNAL_LONG_CORPUS_SELECT_TO_PLAY": 5001,
201
+ "INTERNAL_LONG_CORPUS_PLAYBACK_COMPLETED": 5002,
202
+ "INTERNAL_LONG_CORPUS_STOP_PLAYING": 5003
203
+ }
@@ -0,0 +1,131 @@
1
+ from Crypto.Cipher import AES
2
+ from Crypto.PublicKey import RSA
3
+ from Crypto.Cipher import PKCS1_v1_5
4
+ import base64
5
+ import uuid
6
+ import binascii
7
+
8
+ ###############
9
+ ### AES handling
10
+ ###############
11
+
12
+ # Function to generate a UUID and return it as a 32-character hexadecimal string
13
+ def _generate_uuid() -> str:
14
+ uuid_32 = uuid.uuid4().bytes
15
+ uuid_32_hex_string = binascii.hexlify(uuid_32).decode('utf-8')
16
+ return uuid_32_hex_string
17
+
18
+ def pad(data: str) -> bytes:
19
+ """Pad data to be a multiple of 16 bytes (AES block size)."""
20
+ block_size = AES.block_size
21
+ padding = block_size - len(data) % block_size
22
+ padded_data = data + chr(padding) * padding
23
+ return padded_data.encode('utf-8')
24
+
25
+ def unpad(data: bytes) -> str:
26
+ """Remove padding from data."""
27
+ padding = data[-1]
28
+ return data[:-padding].decode('utf-8')
29
+
30
+ def aes_encrypt(data: str, key: str) -> str:
31
+ """Encrypt the given data using AES (ECB mode with PKCS5 padding)."""
32
+ # Ensure key is 32 bytes for AES-256
33
+ key_bytes = key.encode('utf-8')
34
+
35
+ # Pad the data to ensure it is a multiple of block size
36
+ padded_data = pad(data)
37
+
38
+ # Create AES cipher in ECB mode
39
+ cipher = AES.new(key_bytes, AES.MODE_ECB)
40
+
41
+ # Encrypt data
42
+ encrypted_data = cipher.encrypt(padded_data)
43
+
44
+ # Encode encrypted data to Base64
45
+ encoded_encrypted_data = base64.b64encode(encrypted_data).decode('utf-8')
46
+
47
+ return encoded_encrypted_data
48
+
49
+ def aes_decrypt(encrypted_data: str, key: str) -> str:
50
+ """Decrypt the given data using AES (ECB mode with PKCS5 padding)."""
51
+ # Ensure key is 32 bytes for AES-256
52
+ key_bytes = key.encode('utf-8')
53
+
54
+ # Decode Base64 encrypted data
55
+ encrypted_data_bytes = base64.b64decode(encrypted_data)
56
+
57
+ # Create AES cipher in ECB mode
58
+ cipher = AES.new(key_bytes, AES.MODE_ECB)
59
+
60
+ # Decrypt data
61
+ decrypted_padded_data = cipher.decrypt(encrypted_data_bytes)
62
+
63
+ # Unpad the decrypted data
64
+ decrypted_data = unpad(decrypted_padded_data)
65
+
66
+ return decrypted_data
67
+
68
+ # Function to generate an AES key
69
+ def generate_aes_key() -> str:
70
+ return _generate_uuid()
71
+
72
+ ###############
73
+ ### RSA handling
74
+ ###############
75
+
76
+ def rsa_load_public_key(pem_data: str) -> RSA.RsaKey:
77
+ """Load an RSA public key from a PEM-formatted string."""
78
+ key_bytes = base64.b64decode(pem_data)
79
+ return RSA.import_key(key_bytes)
80
+
81
+ def rsa_encrypt(data: str, public_key: RSA.RsaKey) -> str:
82
+ """Encrypt data using RSA and a given public key."""
83
+ cipher = PKCS1_v1_5.new(public_key)
84
+
85
+ # Maximum chunk size for encryption with RSA/ECB/PKCS1Padding is key size - 11 bytes
86
+ max_chunk_size = public_key.size_in_bytes() - 11
87
+ data_bytes = data.encode('utf-8')
88
+
89
+ encrypted_bytes = bytearray()
90
+ for i in range(0, len(data_bytes), max_chunk_size):
91
+ chunk = data_bytes[i:i + max_chunk_size]
92
+ encrypted_chunk = cipher.encrypt(chunk)
93
+ encrypted_bytes.extend(encrypted_chunk)
94
+
95
+ # Base64 encode the final encrypted data
96
+ encoded_encrypted_data = base64.b64encode(encrypted_bytes).decode('utf-8')
97
+ return encoded_encrypted_data
98
+
99
+ # Example usage
100
+ if __name__ == "__main__":
101
+ # Public key
102
+ public_key_pem = """
103
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnOc1sgpzL4GTVp9/oQ0H
104
+ D7eeAO2GJUABfjX3TitgXiXN1Ktn2WLsLrtAiIuj3OrrRogx8fCT16oxnXx/Xrap
105
+ BRHD/ufHZ08A2IRVw6U6vKDv8TpQH22sAEtUji4/P2AaZmeOxFsYW5FshQr37KBG
106
+ +cBb7rJWLWEJpIXmCpnt37GGCtsACqRegkl7qQ8Q0OiJmtrYLPi00xSstZb+Wv1v
107
+ 8B0eTY3POAUXjgl357L5dc6vS99rYFkYeUCTWHaH4d51Z/KgCRYUadboDc2cgNg/
108
+ z2dbO9S3HADegbIsN3fTbjDCruKfvc5ejxlFZ0Xbu6SScQbmkP8t3TPvy/DXGJAh
109
+ NwIDAQAB
110
+ """
111
+
112
+ # Example value of UUID or data you wish to encrypt
113
+ value_of = "26a663562a6f4dfbbbbf2b50c1a278cb"
114
+
115
+ # Load public key
116
+ public_key = rsa_load_public_key(public_key_pem)
117
+
118
+ # Encrypt the message
119
+ encrypted_value = rsa_encrypt(value_of, public_key)
120
+ print(f"Encrypted Value: {encrypted_value}")
121
+
122
+ # AES testing
123
+ aes_key = "26a663562a6f4dfbbbbf2b50c1a278cb" # Example 32-character UUID
124
+
125
+ # Encrypt a message with AES
126
+ encrypted_message = aes_encrypt("Hello, world!", aes_key)
127
+ print(f"Encrypted AES Message: {encrypted_message}")
128
+
129
+ # Decrypt the AES message
130
+ decrypted_message = aes_decrypt(encrypted_message, aes_key)
131
+ print(f"Decrypted AES Message: {decrypted_message}")
@@ -0,0 +1,161 @@
1
+ # Redistribution and use in source and binary forms, with or without
2
+ # modification, are permitted provided that the following conditions are met:
3
+ #
4
+ # 1. Redistributions of source code must retain the above copyright notice, this
5
+ # list of conditions and the following disclaimer.
6
+ #
7
+ # 2. Redistributions in binary form must reproduce the above copyright notice,
8
+ # this list of conditions and the following disclaimer in the documentation
9
+ # and/or other materials provided with the distribution.
10
+ #
11
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
12
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
14
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
15
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
16
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
17
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
18
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
19
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
20
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
21
+
22
+ import math
23
+ import ctypes
24
+ import numpy as np
25
+ import os
26
+
27
+ from wasmtime import Config, Engine, Store, Module, Instance, Func, FuncType
28
+ from wasmtime import ValType
29
+
30
+
31
+ class LidarDecoder:
32
+ def __init__(self) -> None:
33
+
34
+ config = Config()
35
+ config.wasm_multi_value = True
36
+ config.debug_info = True
37
+ self.store = Store(Engine(config))
38
+
39
+ wasm_path = os.path.join(os.path.dirname(__file__), "libvoxel.wasm")
40
+ self.module = Module.from_file(self.store.engine, wasm_path)
41
+
42
+ self.a_callback_type = FuncType([ValType.i32()], [ValType.i32()])
43
+ self.b_callback_type = FuncType([ValType.i32(), ValType.i32(), ValType.i32()], [])
44
+
45
+ a = Func(self.store, self.a_callback_type, self.adjust_memory_size)
46
+ b = Func(self.store, self.b_callback_type, self.copy_memory_region)
47
+
48
+ self.instance = Instance(self.store, self.module, [a, b])
49
+
50
+ self.generate = self.instance.exports(self.store)["e"]
51
+ self.malloc = self.instance.exports(self.store)["f"]
52
+ self.free = self.instance.exports(self.store)["g"]
53
+ self.wasm_memory = self.instance.exports(self.store)["c"]
54
+
55
+ self.buffer = self.wasm_memory.data_ptr(self.store)
56
+ self.memory_size = self.wasm_memory.data_len(self.store)
57
+
58
+ self.buffer_ptr = int.from_bytes(self.buffer, "little")
59
+
60
+ self.HEAP8 = (ctypes.c_int8 * self.memory_size).from_address(self.buffer_ptr)
61
+ self.HEAP16 = (ctypes.c_int16 * (self.memory_size // 2)).from_address(self.buffer_ptr)
62
+ self.HEAP32 = (ctypes.c_int32 * (self.memory_size // 4)).from_address(self.buffer_ptr)
63
+ self.HEAPU8 = (ctypes.c_uint8 * self.memory_size).from_address(self.buffer_ptr)
64
+ self.HEAPU16 = (ctypes.c_uint16 * (self.memory_size // 2)).from_address(self.buffer_ptr)
65
+ self.HEAPU32 = (ctypes.c_uint32 * (self.memory_size // 4)).from_address(self.buffer_ptr)
66
+ self.HEAPF32 = (ctypes.c_float * (self.memory_size // 4)).from_address(self.buffer_ptr)
67
+ self.HEAPF64 = (ctypes.c_double * (self.memory_size // 8)).from_address(self.buffer_ptr)
68
+
69
+ self.input = self.malloc(self.store, 61440)
70
+ self.decompressBuffer = self.malloc(self.store, 80000)
71
+ self.positions = self.malloc(self.store, 2880000)
72
+ self.uvs = self.malloc(self.store, 1920000)
73
+ self.indices = self.malloc(self.store, 5760000)
74
+ self.decompressedSize = self.malloc(self.store, 4)
75
+ self.faceCount = self.malloc(self.store, 4)
76
+ self.pointCount = self.malloc(self.store, 4)
77
+ self.decompressBufferSize = 80000
78
+
79
+ def adjust_memory_size(self, t):
80
+ return len(self.HEAPU8)
81
+
82
+ def copy_within(self, target, start, end):
83
+ # Copy the sublist for the specified range [start:end]
84
+ sublist = self.HEAPU8[start:end]
85
+
86
+ # Replace elements in the list starting from index 'target'
87
+ for i in range(len(sublist)):
88
+ if target + i < len(self.HEAPU8):
89
+ self.HEAPU8[target + i] = sublist[i]
90
+
91
+ def copy_memory_region(self, t, n, a):
92
+ self.copy_within(t, n, n + a)
93
+
94
+ def get_value(self, t, n="i8"):
95
+ if n.endswith("*"):
96
+ n = "*"
97
+ if n == "i1" or n == "i8":
98
+ return self.HEAP8[t]
99
+ elif n == "i16":
100
+ return self.HEAP16[t >> 1]
101
+ elif n == "i32" or n == "i64":
102
+ return self.HEAP32[t >> 2]
103
+ elif n == "float":
104
+ return self.HEAPF32[t >> 2]
105
+ elif n == "double":
106
+ return self.HEAPF64[t >> 3]
107
+ elif n == "*":
108
+ return self.HEAPU32[t >> 2]
109
+ else:
110
+ raise ValueError(f"invalid type for getValue: {n}")
111
+
112
+ def add_value_arr(self, start, value):
113
+ if start + len(value) <= len(self.HEAPU8):
114
+ for i, byte in enumerate(value):
115
+ self.HEAPU8[start + i] = byte
116
+ else:
117
+ raise ValueError("Not enough space to insert bytes at the specified index.")
118
+
119
+ def decode(self, compressed_data, data):
120
+ self.add_value_arr(self.input, compressed_data)
121
+
122
+ some_v = math.floor(data["origin"][2] / data["resolution"])
123
+
124
+ self.generate(
125
+ self.store,
126
+ self.input,
127
+ len(compressed_data),
128
+ self.decompressBufferSize,
129
+ self.decompressBuffer,
130
+ self.decompressedSize,
131
+ self.positions,
132
+ self.uvs,
133
+ self.indices,
134
+ self.faceCount,
135
+ self.pointCount,
136
+ some_v
137
+ )
138
+
139
+ self.get_value(self.decompressedSize, "i32")
140
+ c = self.get_value(self.pointCount, "i32")
141
+ u = self.get_value(self.faceCount, "i32")
142
+
143
+ positions_slice = self.HEAPU8[self.positions:self.positions + u * 12]
144
+ positions_copy = bytearray(positions_slice)
145
+ p = np.frombuffer(positions_copy, dtype=np.uint8)
146
+
147
+ uvs_slice = self.HEAPU8[self.uvs:self.uvs + u * 8]
148
+ uvs_copy = bytearray(uvs_slice)
149
+ r = np.frombuffer(uvs_copy, dtype=np.uint8)
150
+
151
+ indices_slice = self.HEAPU8[self.indices:self.indices + u * 24]
152
+ indices_copy = bytearray(indices_slice)
153
+ o = np.frombuffer(indices_copy, dtype=np.uint32)
154
+
155
+ return {
156
+ "point_count": c,
157
+ "face_count": u,
158
+ "positions": p,
159
+ "uvs": r,
160
+ "indices": o
161
+ }
@@ -0,0 +1,61 @@
1
+ # Redistribution and use in source and binary forms, with or without
2
+ # modification, are permitted provided that the following conditions are met:
3
+ #
4
+ # 1. Redistributions of source code must retain the above copyright notice, this
5
+ # list of conditions and the following disclaimer.
6
+ #
7
+ # 2. Redistributions in binary form must reproduce the above copyright notice,
8
+ # this list of conditions and the following disclaimer in the documentation
9
+ # and/or other materials provided with the distribution.
10
+ #
11
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
12
+ # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
13
+ # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
14
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
15
+ # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
16
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
17
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
18
+ # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
19
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
20
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
21
+
22
+ import numpy as np
23
+ import lz4.block
24
+
25
+ def decompress(compressed_data, decomp_size):
26
+ decompressed = lz4.block.decompress(
27
+ compressed_data,
28
+ uncompressed_size=decomp_size
29
+ )
30
+ return decompressed
31
+
32
+ def bits_to_points(buf, origin, resolution=0.05):
33
+ buf = np.frombuffer(bytearray(buf), dtype=np.uint8)
34
+ nonzero_indices = np.nonzero(buf)[0]
35
+ points = []
36
+
37
+ for n in nonzero_indices:
38
+ byte_value = buf[n]
39
+ z = n // 0x800
40
+ n_slice = n % 0x800
41
+ y = n_slice // 0x10
42
+ x_base = (n_slice % 0x10) * 8
43
+
44
+ for bit_pos in range(8):
45
+ if byte_value & (1 << (7 - bit_pos)):
46
+ x = x_base + bit_pos
47
+ points.append((x,y,z))
48
+
49
+ return np.array(points) * resolution + origin
50
+
51
+ class LidarDecoder:
52
+ def decode(self, compressed_data, data):
53
+ def points():
54
+ decompressed = decompress(compressed_data, data["src_size"])
55
+ points = bits_to_points(decompressed, data["origin"], data["resolution"])
56
+ return points
57
+
58
+ return {
59
+ "points": points(),
60
+ # "raw": compressed_data,
61
+ }
@@ -0,0 +1,38 @@
1
+ from .lidar_decoder_libvoxel import LidarDecoder as LibVoxelDecoder
2
+ from .lidar_decoder_native import LidarDecoder as NativeDecoder
3
+
4
+
5
+ class UnifiedLidarDecoder:
6
+ def __init__(self, decoder_type="libvoxel"):
7
+ """
8
+ Initialize the UnifiedLidarDecoder with the specified decoder type.
9
+
10
+ :param decoder_type: The type of decoder to use ("libvoxel" or "native").
11
+ Defaults to "libvoxel".
12
+ """
13
+ if decoder_type == "libvoxel":
14
+ self.decoder = LibVoxelDecoder()
15
+ self.decoder_name = "LibVoxelDecoder"
16
+ elif decoder_type == "native":
17
+ self.decoder = NativeDecoder()
18
+ self.decoder_name = "NativeDecoder"
19
+ else:
20
+ raise ValueError("Invalid decoder type. Choose 'libvoxel' or 'native'.")
21
+
22
+ def decode(self, compressed_data, metadata):
23
+ """
24
+ Decode the compressed data using the selected decoder.
25
+
26
+ :param compressed_data: The compressed data to decode.
27
+ :param metadata: Metadata required for decoding (e.g., origin, resolution).
28
+ :return: Decoded result from the selected decoder.
29
+ """
30
+ return self.decoder.decode(compressed_data, metadata)
31
+
32
+ def get_decoder_name(self):
33
+ """
34
+ Get the name of the currently selected decoder.
35
+
36
+ :return: Name of the decoder (e.g., "LibVoxelDecoder" or "NativeDecoder").
37
+ """
38
+ return self.decoder_name