drongo-geo 0.1.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.
- drongo/__init__.py +18 -0
- drongo/_mp4.py +171 -0
- drongo/camera.py +113 -0
- drongo/dji_embedded.py +282 -0
- drongo/frames.py +84 -0
- drongo/geometry.py +263 -0
- drongo/provider.py +58 -0
- drongo/py.typed +0 -0
- drongo/rectify.py +32 -0
- drongo/telemetry.py +301 -0
- drongo/types.py +70 -0
- drongo_geo-0.1.0.dist-info/METADATA +375 -0
- drongo_geo-0.1.0.dist-info/RECORD +16 -0
- drongo_geo-0.1.0.dist-info/WHEEL +5 -0
- drongo_geo-0.1.0.dist-info/licenses/LICENSE +201 -0
- drongo_geo-0.1.0.dist-info/top_level.txt +1 -0
drongo/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""drongo — direct georeferencing for drone video (Phase 1)."""
|
|
2
|
+
from .camera import CameraModel, Intrinsics
|
|
3
|
+
from .frames import FlatGround, GroundModel, LocalFrame
|
|
4
|
+
from .geometry import Footprint, FrameGeometry, apply_h, relative_homography, rotation_world_from_cam
|
|
5
|
+
from .provider import PoseEstimate, PoseProvider, TelemetryPoseProvider
|
|
6
|
+
from .telemetry import DjiSrtReader, TelemetryReader, TelemetryTrack, open_telemetry, write_dji_srt
|
|
7
|
+
from .dji_embedded import DjiEmbeddedReader, DjiPacketDecoder, iter_dji_packets
|
|
8
|
+
from .types import PoseSample, TelemetrySourceKind, lerp_angle_deg, wrap_deg
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"CameraModel", "Intrinsics", "FlatGround", "GroundModel", "LocalFrame",
|
|
14
|
+
"Footprint", "FrameGeometry", "apply_h", "relative_homography", "rotation_world_from_cam",
|
|
15
|
+
"PoseEstimate", "PoseProvider", "TelemetryPoseProvider",
|
|
16
|
+
"DjiSrtReader", "DjiEmbeddedReader", "DjiPacketDecoder", "iter_dji_packets", "TelemetryReader", "TelemetryTrack", "open_telemetry", "write_dji_srt",
|
|
17
|
+
"PoseSample", "TelemetrySourceKind", "lerp_angle_deg", "wrap_deg",
|
|
18
|
+
]
|
drongo/_mp4.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Minimal ISO-BMFF / QuickTime reader: list tracks and read the samples of a
|
|
2
|
+
timed-metadata track. Pure Python, no external tools. Reads only box headers
|
|
3
|
+
and the sample tables, then the samples themselves; never the video data.
|
|
4
|
+
|
|
5
|
+
Treats the file as untrusted: box sizes are bounds-checked, nesting depth and
|
|
6
|
+
sample counts are capped.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import struct
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import BinaryIO, Iterator, Optional
|
|
14
|
+
|
|
15
|
+
_CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts", b"udta", b"dinf"}
|
|
16
|
+
MAX_SAMPLES = 2_000_000
|
|
17
|
+
MAX_SAMPLE_BYTES = 1 << 20
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Mp4Error(ValueError):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Track:
|
|
26
|
+
track_id: int = 0
|
|
27
|
+
handler_type: str = "" # 'vide', 'soun', 'meta', 'text', ...
|
|
28
|
+
handler_name: str = "" # e.g. 'DJI meta'
|
|
29
|
+
sample_format: str = "" # sample entry fourcc, e.g. 'djmd', 'avc1'
|
|
30
|
+
timescale: int = 0
|
|
31
|
+
sizes: list[int] = field(default_factory=list)
|
|
32
|
+
chunk_offsets: list[int] = field(default_factory=list)
|
|
33
|
+
stsc: list[tuple[int, int]] = field(default_factory=list) # (first_chunk, samples_per_chunk)
|
|
34
|
+
stts: list[tuple[int, int]] = field(default_factory=list) # (count, delta)
|
|
35
|
+
|
|
36
|
+
def sample_offsets(self) -> list[int]:
|
|
37
|
+
out: list[int] = []
|
|
38
|
+
n = len(self.sizes)
|
|
39
|
+
if not self.stsc or not self.chunk_offsets:
|
|
40
|
+
return out
|
|
41
|
+
runs = self.stsc + [(len(self.chunk_offsets) + 1, 0)]
|
|
42
|
+
s = 0
|
|
43
|
+
for (first, per), (nxt, _) in zip(runs[:-1], runs[1:]):
|
|
44
|
+
for chunk in range(first, nxt):
|
|
45
|
+
if chunk - 1 >= len(self.chunk_offsets):
|
|
46
|
+
break
|
|
47
|
+
off = self.chunk_offsets[chunk - 1]
|
|
48
|
+
for _ in range(per):
|
|
49
|
+
if s >= n:
|
|
50
|
+
return out
|
|
51
|
+
out.append(off)
|
|
52
|
+
off += self.sizes[s]
|
|
53
|
+
s += 1
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
def sample_times_ms(self) -> list[float]:
|
|
57
|
+
t, out = 0, []
|
|
58
|
+
for count, delta in self.stts:
|
|
59
|
+
for _ in range(count):
|
|
60
|
+
out.append(1000.0 * t / self.timescale if self.timescale else 0.0)
|
|
61
|
+
t += delta
|
|
62
|
+
return out[: len(self.sizes)]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _boxes(f: BinaryIO, start: int, end: int) -> Iterator[tuple[bytes, int, int]]:
|
|
66
|
+
"""Yield (type, payload_start, payload_end) for boxes in [start, end)."""
|
|
67
|
+
pos = start
|
|
68
|
+
while pos + 8 <= end:
|
|
69
|
+
f.seek(pos)
|
|
70
|
+
hdr = f.read(8)
|
|
71
|
+
if len(hdr) < 8:
|
|
72
|
+
return
|
|
73
|
+
size, typ = struct.unpack(">I4s", hdr)
|
|
74
|
+
head = 8
|
|
75
|
+
if size == 1:
|
|
76
|
+
ext = f.read(8)
|
|
77
|
+
if len(ext) < 8:
|
|
78
|
+
return
|
|
79
|
+
size = struct.unpack(">Q", ext)[0]
|
|
80
|
+
head = 16
|
|
81
|
+
elif size == 0:
|
|
82
|
+
size = end - pos
|
|
83
|
+
if size < head or pos + size > end:
|
|
84
|
+
raise Mp4Error(f"bad box size {size} for {typ!r} at {pos}")
|
|
85
|
+
yield typ, pos + head, pos + size
|
|
86
|
+
pos += size
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _read(f: BinaryIO, a: int, b: int) -> bytes:
|
|
90
|
+
f.seek(a)
|
|
91
|
+
return f.read(b - a)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _parse_stbl(f, a, b, tr: Track) -> None:
|
|
95
|
+
for typ, s, e in _boxes(f, a, b):
|
|
96
|
+
d = _read(f, s, e)
|
|
97
|
+
if typ == b"stsd" and len(d) >= 16:
|
|
98
|
+
tr.sample_format = d[12:16].decode("latin-1").strip("\0")
|
|
99
|
+
elif typ == b"stsz" and len(d) >= 12:
|
|
100
|
+
fixed, n = struct.unpack(">II", d[4:12])
|
|
101
|
+
if n > MAX_SAMPLES:
|
|
102
|
+
raise Mp4Error("too many samples")
|
|
103
|
+
tr.sizes = [fixed] * n if fixed else list(struct.unpack(f">{n}I", d[12:12 + 4 * n]))
|
|
104
|
+
elif typ == b"stco" and len(d) >= 8:
|
|
105
|
+
n = struct.unpack(">I", d[4:8])[0]
|
|
106
|
+
tr.chunk_offsets = list(struct.unpack(f">{n}I", d[8:8 + 4 * n]))
|
|
107
|
+
elif typ == b"co64" and len(d) >= 8:
|
|
108
|
+
n = struct.unpack(">I", d[4:8])[0]
|
|
109
|
+
tr.chunk_offsets = list(struct.unpack(f">{n}Q", d[8:8 + 8 * n]))
|
|
110
|
+
elif typ == b"stsc" and len(d) >= 8:
|
|
111
|
+
n = struct.unpack(">I", d[4:8])[0]
|
|
112
|
+
tr.stsc = [struct.unpack(">II", d[8 + 12 * i: 16 + 12 * i]) for i in range(n)]
|
|
113
|
+
elif typ == b"stts" and len(d) >= 8:
|
|
114
|
+
n = struct.unpack(">I", d[4:8])[0]
|
|
115
|
+
tr.stts = [struct.unpack(">II", d[8 + 8 * i: 16 + 8 * i]) for i in range(n)]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _walk_trak(f, a, b, tr: Track, depth=0) -> None:
|
|
119
|
+
if depth > 8:
|
|
120
|
+
return
|
|
121
|
+
for typ, s, e in _boxes(f, a, b):
|
|
122
|
+
if typ == b"tkhd":
|
|
123
|
+
d = _read(f, s, min(e, s + 24))
|
|
124
|
+
ver = d[0] if d else 0
|
|
125
|
+
off = 12 if ver == 0 else 20
|
|
126
|
+
if len(d) >= off + 4:
|
|
127
|
+
tr.track_id = struct.unpack(">I", d[off:off + 4])[0]
|
|
128
|
+
elif typ == b"mdhd":
|
|
129
|
+
d = _read(f, s, min(e, s + 32))
|
|
130
|
+
ver = d[0] if d else 0
|
|
131
|
+
off = 12 if ver == 0 else 20
|
|
132
|
+
if len(d) >= off + 4:
|
|
133
|
+
tr.timescale = struct.unpack(">I", d[off:off + 4])[0]
|
|
134
|
+
elif typ == b"hdlr" and not tr.handler_type: # mdia's hdlr; QuickTime adds a data hdlr later
|
|
135
|
+
d = _read(f, s, e)
|
|
136
|
+
if len(d) >= 24:
|
|
137
|
+
tr.handler_type = d[8:12].decode("latin-1")
|
|
138
|
+
name = d[24:]
|
|
139
|
+
if name[:1] and name[0] == len(name) - 1: # QuickTime pascal string
|
|
140
|
+
name = name[1:]
|
|
141
|
+
tr.handler_name = name.split(b"\0")[0].decode("utf-8", "replace").strip()
|
|
142
|
+
elif typ == b"stbl":
|
|
143
|
+
_parse_stbl(f, s, e, tr)
|
|
144
|
+
elif typ in _CONTAINERS:
|
|
145
|
+
_walk_trak(f, s, e, tr, depth + 1)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def read_tracks(path: Path) -> list[Track]:
|
|
149
|
+
tracks: list[Track] = []
|
|
150
|
+
with open(path, "rb") as f:
|
|
151
|
+
f.seek(0, 2)
|
|
152
|
+
size = f.tell()
|
|
153
|
+
for typ, s, e in _boxes(f, 0, size):
|
|
154
|
+
if typ == b"moov":
|
|
155
|
+
for t2, s2, e2 in _boxes(f, s, e):
|
|
156
|
+
if t2 == b"trak":
|
|
157
|
+
tr = Track()
|
|
158
|
+
_walk_trak(f, s2, e2, tr)
|
|
159
|
+
tracks.append(tr)
|
|
160
|
+
return tracks
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def read_samples(path: Path, track: Track) -> Iterator[tuple[float, bytes]]:
|
|
164
|
+
"""(time_ms, payload) for every sample of the track."""
|
|
165
|
+
offs, times = track.sample_offsets(), track.sample_times_ms()
|
|
166
|
+
with open(path, "rb") as f:
|
|
167
|
+
for i, (off, n) in enumerate(zip(offs, track.sizes)):
|
|
168
|
+
if n > MAX_SAMPLE_BYTES:
|
|
169
|
+
raise Mp4Error(f"sample {i} too large ({n} bytes)")
|
|
170
|
+
f.seek(off)
|
|
171
|
+
yield (times[i] if i < len(times) else float("nan")), f.read(n)
|
drongo/camera.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Camera model. Intrinsics are always derived from the actual frame size, so a
|
|
2
|
+
16:9 crop of a 4:3 sensor never needs a separately configured sensor height."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from .types import ArrayN2, Mat3, as_n2
|
|
11
|
+
|
|
12
|
+
# Nominal values from public specs. Calibrate before relying on them for
|
|
13
|
+
# accuracy work; distortion is not included.
|
|
14
|
+
_PRESETS: dict[str, tuple[float, float]] = {
|
|
15
|
+
# name: (sensor_w_mm, focal_mm)
|
|
16
|
+
"generic_small_sensor": (6.3, 4.5), # 1/2.3"-class sensor, 4.5 mm lens
|
|
17
|
+
"equiv_24mm": (36.0, 24.0), # any camera specified as 24 mm full-frame equivalent
|
|
18
|
+
"mini2": (6.17, 4.49),
|
|
19
|
+
"mini3pro": (9.6, 6.72),
|
|
20
|
+
"air2s": (13.2, 8.38),
|
|
21
|
+
"mavic3_wide": (17.3, 12.29),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class Intrinsics:
|
|
27
|
+
fx: float
|
|
28
|
+
fy: float
|
|
29
|
+
cx: float
|
|
30
|
+
cy: float
|
|
31
|
+
img_w_px: int
|
|
32
|
+
img_h_px: int
|
|
33
|
+
dist_coeffs: Optional[tuple[float, ...]] = None # k1, k2, p1, p2, k3
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def K(self) -> Mat3:
|
|
37
|
+
return np.array([[self.fx, 0, self.cx], [0, self.fy, self.cy], [0, 0, 1.0]])
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def K_inv(self) -> Mat3:
|
|
41
|
+
return np.array([[1 / self.fx, 0, -self.cx / self.fx],
|
|
42
|
+
[0, 1 / self.fy, -self.cy / self.fy], [0, 0, 1.0]])
|
|
43
|
+
|
|
44
|
+
def scaled(self, img_w_px: int, img_h_px: int) -> "Intrinsics":
|
|
45
|
+
sx, sy = img_w_px / self.img_w_px, img_h_px / self.img_h_px
|
|
46
|
+
return Intrinsics(self.fx * sx, self.fy * sy, self.cx * sx, self.cy * sy,
|
|
47
|
+
img_w_px, img_h_px, self.dist_coeffs)
|
|
48
|
+
|
|
49
|
+
# ---- distortion (Brown–Conrady, OpenCV coefficient order)
|
|
50
|
+
def _coeffs(self):
|
|
51
|
+
d = list(self.dist_coeffs or ()) + [0.0] * 5
|
|
52
|
+
return d[:5]
|
|
53
|
+
|
|
54
|
+
def _distort_norm(self, xy: np.ndarray) -> np.ndarray:
|
|
55
|
+
k1, k2, p1, p2, k3 = self._coeffs()
|
|
56
|
+
x, y = xy[:, 0], xy[:, 1]
|
|
57
|
+
r2 = x * x + y * y
|
|
58
|
+
radial = 1 + k1 * r2 + k2 * r2 ** 2 + k3 * r2 ** 3
|
|
59
|
+
xd = x * radial + 2 * p1 * x * y + p2 * (r2 + 2 * x * x)
|
|
60
|
+
yd = y * radial + p1 * (r2 + 2 * y * y) + 2 * p2 * x * y
|
|
61
|
+
return np.stack([xd, yd], axis=1)
|
|
62
|
+
|
|
63
|
+
def undistort_points(self, uv: ArrayN2) -> ArrayN2:
|
|
64
|
+
uv = as_n2(uv)
|
|
65
|
+
if not self.dist_coeffs or not any(self.dist_coeffs):
|
|
66
|
+
return uv.copy()
|
|
67
|
+
xd = np.stack([(uv[:, 0] - self.cx) / self.fx, (uv[:, 1] - self.cy) / self.fy], axis=1)
|
|
68
|
+
x = xd.copy()
|
|
69
|
+
for _ in range(20): # fixed-point iteration
|
|
70
|
+
x = x + (xd - self._distort_norm(x))
|
|
71
|
+
return np.stack([x[:, 0] * self.fx + self.cx, x[:, 1] * self.fy + self.cy], axis=1)
|
|
72
|
+
|
|
73
|
+
def distort_points(self, uv: ArrayN2) -> ArrayN2:
|
|
74
|
+
uv = as_n2(uv)
|
|
75
|
+
if not self.dist_coeffs or not any(self.dist_coeffs):
|
|
76
|
+
return uv.copy()
|
|
77
|
+
x = np.stack([(uv[:, 0] - self.cx) / self.fx, (uv[:, 1] - self.cy) / self.fy], axis=1)
|
|
78
|
+
xd = self._distort_norm(x)
|
|
79
|
+
return np.stack([xd[:, 0] * self.fx + self.cx, xd[:, 1] * self.fy + self.cy], axis=1)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True, slots=True)
|
|
83
|
+
class CameraModel:
|
|
84
|
+
sensor_w_mm: float
|
|
85
|
+
focal_mm: float
|
|
86
|
+
dist_coeffs: Optional[tuple[float, ...]] = None
|
|
87
|
+
name: str = "custom"
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def preset(cls, name: str) -> "CameraModel":
|
|
91
|
+
try:
|
|
92
|
+
w, f = _PRESETS[name]
|
|
93
|
+
except KeyError:
|
|
94
|
+
raise KeyError(f"unknown camera preset {name!r}; known: {sorted(_PRESETS)}") from None
|
|
95
|
+
return cls(w, f, None, name)
|
|
96
|
+
|
|
97
|
+
@staticmethod
|
|
98
|
+
def presets() -> list[str]:
|
|
99
|
+
return sorted(_PRESETS)
|
|
100
|
+
|
|
101
|
+
def intrinsics(self, img_w_px: int, img_h_px: int) -> Intrinsics:
|
|
102
|
+
"""Square pixels; principal point at image centre. The sensor width
|
|
103
|
+
maps to the full frame width, so the effective sensor height is
|
|
104
|
+
sensor_w * h / w for any aspect ratio."""
|
|
105
|
+
if img_w_px <= 0 or img_h_px <= 0:
|
|
106
|
+
raise ValueError("frame size must be positive")
|
|
107
|
+
f_px = self.focal_mm / self.sensor_w_mm * img_w_px
|
|
108
|
+
return Intrinsics(f_px, f_px, img_w_px / 2.0, img_h_px / 2.0,
|
|
109
|
+
int(img_w_px), int(img_h_px), self.dist_coeffs)
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def hfov_deg(self) -> float:
|
|
113
|
+
return float(np.degrees(2 * np.arctan(self.sensor_w_mm / (2 * self.focal_mm))))
|
drongo/dji_embedded.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""Reader for DJI telemetry embedded in MP4/MOV files ("DJI meta" timed-metadata
|
|
2
|
+
track, protobuf payload per video frame). Pure Python; no ffmpeg or exiftool.
|
|
3
|
+
|
|
4
|
+
Field layout (protobuf field numbers, '.'-separated path from the root):
|
|
5
|
+
|
|
6
|
+
3.3.4.1.2 latitude, radians (double)
|
|
7
|
+
3.3.4.1.3 longitude, radians (double)
|
|
8
|
+
3.3.4.2 altitude above sea level (varint mm, or float m)
|
|
9
|
+
3.3.5.1 altitude above takeoff (float; mm on some models, m on others)
|
|
10
|
+
3.3.3.1-3 aircraft pitch, roll, yaw (deci-degrees)
|
|
11
|
+
3.4.3.1-3 gimbal pitch, roll, yaw (deci-degrees, absolute)
|
|
12
|
+
|
|
13
|
+
Angles are stored as protobuf int (two's complement) on the aircraft checked
|
|
14
|
+
so far (Mavic 3 Enterprise), and as zigzag sint by some third-party writers.
|
|
15
|
+
The encoding is chosen per file: the one under which every gimbal sample is a
|
|
16
|
+
physically possible attitude. Samples that are impossible under the chosen
|
|
17
|
+
encoding are dropped and counted (TEL-11).
|
|
18
|
+
|
|
19
|
+
Verified against: DJI Mavic 3 Enterprise ("DJI M3E", 2024 firmware); files
|
|
20
|
+
written by simulators using the zigzag variant. Other models may use other
|
|
21
|
+
paths; they are reported as "no position fields" rather than guessed.
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import math
|
|
26
|
+
import struct
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Iterator, Optional
|
|
29
|
+
|
|
30
|
+
from ._mp4 import Mp4Error, read_samples, read_tracks
|
|
31
|
+
from .telemetry import TelemetryTrack
|
|
32
|
+
from .types import PoseSample, TelemetrySourceKind
|
|
33
|
+
|
|
34
|
+
_MAX_DEPTH = 8
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _varint(b: bytes, i: int) -> tuple[int, int]:
|
|
38
|
+
r = s = 0
|
|
39
|
+
while True:
|
|
40
|
+
if i >= len(b) or s > 63:
|
|
41
|
+
raise ValueError("truncated varint")
|
|
42
|
+
c = b[i]
|
|
43
|
+
i += 1
|
|
44
|
+
r |= (c & 0x7F) << s
|
|
45
|
+
s += 7
|
|
46
|
+
if c < 0x80:
|
|
47
|
+
return r, i
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def decode_fields(buf: bytes, prefix: str = "", depth: int = 0) -> Optional[dict[str, object]]:
|
|
51
|
+
"""Flatten a protobuf message into {path: value}. Length-delimited fields
|
|
52
|
+
are decoded as sub-messages when they parse cleanly, else kept as bytes.
|
|
53
|
+
Returns None if `buf` is not a valid message. Repeated fields keep the
|
|
54
|
+
first value."""
|
|
55
|
+
out: dict[str, object] = {}
|
|
56
|
+
i = 0
|
|
57
|
+
try:
|
|
58
|
+
while i < len(buf):
|
|
59
|
+
key, i = _varint(buf, i)
|
|
60
|
+
num, wire = key >> 3, key & 7
|
|
61
|
+
if num == 0:
|
|
62
|
+
return None
|
|
63
|
+
path = f"{prefix}.{num}" if prefix else str(num)
|
|
64
|
+
if wire == 0:
|
|
65
|
+
v, i = _varint(buf, i)
|
|
66
|
+
elif wire == 1:
|
|
67
|
+
if i + 8 > len(buf):
|
|
68
|
+
return None
|
|
69
|
+
v = struct.unpack_from("<d", buf, i)[0]
|
|
70
|
+
i += 8
|
|
71
|
+
elif wire == 5:
|
|
72
|
+
if i + 4 > len(buf):
|
|
73
|
+
return None
|
|
74
|
+
v = struct.unpack_from("<f", buf, i)[0]
|
|
75
|
+
i += 4
|
|
76
|
+
elif wire == 2:
|
|
77
|
+
n, i = _varint(buf, i)
|
|
78
|
+
if i + n > len(buf):
|
|
79
|
+
return None
|
|
80
|
+
sub = buf[i:i + n]
|
|
81
|
+
i += n
|
|
82
|
+
inner = decode_fields(sub, path, depth + 1) if (n and depth < _MAX_DEPTH) else None
|
|
83
|
+
if inner:
|
|
84
|
+
for k, val in inner.items():
|
|
85
|
+
out.setdefault(k, val)
|
|
86
|
+
continue
|
|
87
|
+
v = sub
|
|
88
|
+
else:
|
|
89
|
+
return None
|
|
90
|
+
out.setdefault(path, v)
|
|
91
|
+
except ValueError:
|
|
92
|
+
return None
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _as_int(v: int) -> int: # protobuf int32/int64: two's complement in 64 bits
|
|
97
|
+
return v - (1 << 64) if v >= (1 << 63) else v
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _as_sint(v: int) -> int: # protobuf sint32/sint64: zigzag
|
|
101
|
+
return (v >> 1) ^ -(v & 1)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _plausible(pitch: float, roll: float, yaw: float) -> bool:
|
|
105
|
+
return -120.0 <= pitch <= 45.0 and -95.0 <= roll <= 95.0 and -360.0 <= yaw <= 360.0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _alt_m(v) -> Optional[float]:
|
|
109
|
+
if v is None or isinstance(v, (bytes, bytearray)):
|
|
110
|
+
return None
|
|
111
|
+
v = float(v)
|
|
112
|
+
return v / 1000.0 if abs(v) > 5000.0 else v # mm on some models (no drone flies 5 km up)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _gimbal(d: dict, conv) -> Optional[tuple[float, float, float]]:
|
|
116
|
+
vals = [d.get(f"3.4.3.{k}", 0) for k in (1, 2, 3)]
|
|
117
|
+
if not all(isinstance(v, int) for v in vals):
|
|
118
|
+
return None
|
|
119
|
+
return tuple(conv(v) / 10.0 for v in vals) # type: ignore[return-value]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _has_position(d: dict) -> bool:
|
|
123
|
+
return "3.3.4.1.2" in d and "3.3.4.1.3" in d
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _encoding_scores(decoded: list[dict]) -> dict[str, int]:
|
|
127
|
+
"""How many packets give a physically possible gimbal attitude under each encoding."""
|
|
128
|
+
out = {}
|
|
129
|
+
for name, conv in (("int", _as_int), ("zigzag", _as_sint)):
|
|
130
|
+
out[name] = sum(1 for d in decoded if (g := _gimbal(d, conv)) and _plausible(*g))
|
|
131
|
+
return out
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def packet_to_sample(t_ms: float, d: dict, encoding: str, kind=TelemetrySourceKind.DJI_PROTOBUF) -> Optional[PoseSample]:
|
|
135
|
+
"""One decoded packet -> PoseSample, or None if it has no position or an
|
|
136
|
+
impossible attitude (the sanity gate)."""
|
|
137
|
+
if not _has_position(d):
|
|
138
|
+
return None
|
|
139
|
+
conv = _as_int if encoding == "int" else _as_sint
|
|
140
|
+
lat, lon = math.degrees(d["3.3.4.1.2"]), math.degrees(d["3.3.4.1.3"])
|
|
141
|
+
g = _gimbal(d, conv)
|
|
142
|
+
if not (-90 <= lat <= 90 and -180 <= lon <= 180) or (lat == 0 and lon == 0) or not g or not _plausible(*g):
|
|
143
|
+
return None
|
|
144
|
+
pitch, roll, yaw = g
|
|
145
|
+
body = d.get("3.3.3.3")
|
|
146
|
+
alt = _alt_m(d.get("3.3.5.1"))
|
|
147
|
+
return PoseSample(
|
|
148
|
+
t_ms=int(round(t_ms)), lat_deg=lat, lon_deg=lon,
|
|
149
|
+
alt_agl_m=alt if alt is not None else float("nan"),
|
|
150
|
+
gimbal_yaw_deg=yaw % 360.0, gimbal_pitch_deg=pitch, gimbal_roll_deg=roll,
|
|
151
|
+
alt_msl_m=_alt_m(d.get("3.3.4.2")),
|
|
152
|
+
body_yaw_deg=(conv(body) / 10.0) % 360.0 if isinstance(body, int) else None, source=kind)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class DjiEmbeddedReader:
|
|
156
|
+
"""TelemetryReader for DJI telemetry embedded in a recorded video file."""
|
|
157
|
+
|
|
158
|
+
kind = TelemetrySourceKind.DJI_PROTOBUF
|
|
159
|
+
HANDLER_NAMES = ("dji meta",)
|
|
160
|
+
SAMPLE_FORMATS = ("djmd",)
|
|
161
|
+
|
|
162
|
+
def __init__(self) -> None:
|
|
163
|
+
self.last_stats: dict = {}
|
|
164
|
+
|
|
165
|
+
def _track(self, video: Path):
|
|
166
|
+
for t in read_tracks(video):
|
|
167
|
+
if t.handler_name.lower() in self.HANDLER_NAMES or t.sample_format in self.SAMPLE_FORMATS:
|
|
168
|
+
return t
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
def can_read(self, video, sidecar) -> bool:
|
|
172
|
+
if video is None or not Path(video).is_file():
|
|
173
|
+
return False
|
|
174
|
+
try:
|
|
175
|
+
return self._track(Path(video)) is not None
|
|
176
|
+
except (Mp4Error, OSError, struct.error):
|
|
177
|
+
return False
|
|
178
|
+
|
|
179
|
+
def explain(self, video, sidecar) -> str:
|
|
180
|
+
if video is None or not Path(video).is_file():
|
|
181
|
+
return "no video file"
|
|
182
|
+
try:
|
|
183
|
+
names = [t.handler_name or t.sample_format for t in read_tracks(Path(video))]
|
|
184
|
+
except (Mp4Error, OSError, struct.error) as e:
|
|
185
|
+
return f"not a readable MP4/MOV container ({e})"
|
|
186
|
+
return f"no DJI metadata track (tracks: {', '.join(names) or 'none'})"
|
|
187
|
+
|
|
188
|
+
def read(self, video, sidecar) -> TelemetryTrack:
|
|
189
|
+
decoded = [(t, decode_fields(p) or {}) for t, p in iter_dji_packets(video)]
|
|
190
|
+
return self.from_decoded(decoded)
|
|
191
|
+
|
|
192
|
+
def from_decoded(self, decoded: list[tuple[float, dict]]) -> TelemetryTrack:
|
|
193
|
+
"""Build a track from (time_ms, decoded fields) pairs. The encoding is
|
|
194
|
+
chosen over the whole file; also used by tests."""
|
|
195
|
+
raw = [(t, d) for t, d in decoded if _has_position(d)]
|
|
196
|
+
scores = _encoding_scores([d for _, d in raw])
|
|
197
|
+
enc = max(scores, key=scores.get) if raw else "int"
|
|
198
|
+
out = [s for t, d in raw if (s := packet_to_sample(t, d, enc, self.kind)) is not None]
|
|
199
|
+
self.last_stats = {"packets": len(decoded), "with_position": len(raw), "angle_encoding": enc,
|
|
200
|
+
"plausible": scores, "rejected_implausible": len(raw) - len(out)}
|
|
201
|
+
return TelemetryTrack(out)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def iter_dji_packets(video) -> Iterator[tuple[float, bytes]]:
|
|
205
|
+
"""(time_ms, raw packet) for each DJI telemetry packet in a recorded file,
|
|
206
|
+
in order. Feeding these to DjiPacketDecoder replays a recording as a live
|
|
207
|
+
stream."""
|
|
208
|
+
video = Path(video)
|
|
209
|
+
reader = DjiEmbeddedReader()
|
|
210
|
+
track = reader._track(video)
|
|
211
|
+
if track is None:
|
|
212
|
+
raise ValueError(reader.explain(video, None))
|
|
213
|
+
yield from read_samples(video, track)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class DjiPacketDecoder:
|
|
217
|
+
"""Streaming decoder: one DJI telemetry packet in, a PoseSample out.
|
|
218
|
+
|
|
219
|
+
The angle encoding cannot be known from one packet when angles are small
|
|
220
|
+
and positive (both encodings then give plausible values), so it is chosen
|
|
221
|
+
from the first packets: as soon as only one encoding gives a possible
|
|
222
|
+
attitude, or after `decide_after` packets by majority. Packets received
|
|
223
|
+
before the decision are buffered and released with the decision, so the
|
|
224
|
+
first `feed` calls may return an empty list and a later one several samples.
|
|
225
|
+
Pass `encoding="int"` or `"zigzag"` to skip detection.
|
|
226
|
+
|
|
227
|
+
dec = DjiPacketDecoder()
|
|
228
|
+
for t_ms, packet in source: # live feed, or iter_dji_packets(path)
|
|
229
|
+
for sample in dec.feed(packet, t_ms):
|
|
230
|
+
track.append(sample)
|
|
231
|
+
|
|
232
|
+
Times must be on the same clock as the video frames you query.
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
def __init__(self, encoding: str = "auto", decide_after: int = 10) -> None:
|
|
236
|
+
if encoding not in ("auto", "int", "zigzag"):
|
|
237
|
+
raise ValueError("encoding must be 'auto', 'int' or 'zigzag'")
|
|
238
|
+
self.encoding: Optional[str] = None if encoding == "auto" else encoding
|
|
239
|
+
self.decide_after = decide_after
|
|
240
|
+
self._pending: list[tuple[float, dict]] = []
|
|
241
|
+
self.stats = {"packets": 0, "undecodable": 0, "no_position": 0, "rejected_implausible": 0, "emitted": 0}
|
|
242
|
+
|
|
243
|
+
def feed(self, packet: bytes, t_ms: float) -> list[PoseSample]:
|
|
244
|
+
self.stats["packets"] += 1
|
|
245
|
+
d = decode_fields(packet)
|
|
246
|
+
if d is None:
|
|
247
|
+
self.stats["undecodable"] += 1
|
|
248
|
+
return []
|
|
249
|
+
if not _has_position(d):
|
|
250
|
+
self.stats["no_position"] += 1
|
|
251
|
+
return []
|
|
252
|
+
if self.encoding is None:
|
|
253
|
+
self._pending.append((t_ms, d))
|
|
254
|
+
scores = _encoding_scores([x for _, x in self._pending])
|
|
255
|
+
n = len(self._pending)
|
|
256
|
+
unique = [k for k, v in scores.items() if v == n] if min(scores.values()) < n else []
|
|
257
|
+
if len(unique) == 1 or n >= self.decide_after:
|
|
258
|
+
self.encoding = unique[0] if len(unique) == 1 else max(scores, key=scores.get)
|
|
259
|
+
pending, self._pending = self._pending, []
|
|
260
|
+
return self._emit(pending)
|
|
261
|
+
return []
|
|
262
|
+
return self._emit([(t_ms, d)])
|
|
263
|
+
|
|
264
|
+
def flush(self) -> list[PoseSample]:
|
|
265
|
+
"""Decide with whatever is buffered (end of a short stream)."""
|
|
266
|
+
if not self._pending:
|
|
267
|
+
return []
|
|
268
|
+
scores = _encoding_scores([x for _, x in self._pending])
|
|
269
|
+
self.encoding = self.encoding or max(scores, key=scores.get)
|
|
270
|
+
pending, self._pending = self._pending, []
|
|
271
|
+
return self._emit(pending)
|
|
272
|
+
|
|
273
|
+
def _emit(self, items) -> list[PoseSample]:
|
|
274
|
+
out = []
|
|
275
|
+
for t, d in items:
|
|
276
|
+
s = packet_to_sample(t, d, self.encoding or "int")
|
|
277
|
+
if s is None:
|
|
278
|
+
self.stats["rejected_implausible"] += 1
|
|
279
|
+
else:
|
|
280
|
+
out.append(s)
|
|
281
|
+
self.stats["emitted"] += len(out)
|
|
282
|
+
return out
|
drongo/frames.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Local metric frame (ENU tangent plane) and ground models."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from .types import ArrayN2, as_n2
|
|
10
|
+
|
|
11
|
+
_WGS84_A = 6378137.0
|
|
12
|
+
_WGS84_E2 = 6.69437999014e-3
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _radii(lat_rad):
|
|
16
|
+
s2 = np.sin(lat_rad) ** 2
|
|
17
|
+
m = _WGS84_A * (1 - _WGS84_E2) / (1 - _WGS84_E2 * s2) ** 1.5 # meridian
|
|
18
|
+
n = _WGS84_A / np.sqrt(1 - _WGS84_E2 * s2) # prime vertical
|
|
19
|
+
return m, n
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class LocalFrame:
|
|
24
|
+
"""Local metric plane (E, N) anchored at a reference point.
|
|
25
|
+
|
|
26
|
+
Mid-latitude projection on the WGS84 ellipsoid: N = dlat * M(lat_mid),
|
|
27
|
+
E = dlon * N(lat_mid) * cos(lat_mid). Distances agree with the geodesic
|
|
28
|
+
to < 1 mm within ~10 km of the reference (test_camera_frames.py). Earth
|
|
29
|
+
curvature (ground drops ~d^2/2R, 0.3 m at 2 km) is ignored, consistent
|
|
30
|
+
with the flat-ground model.
|
|
31
|
+
"""
|
|
32
|
+
ref_lat_deg: float
|
|
33
|
+
ref_lon_deg: float
|
|
34
|
+
ref_alt_m: float = 0.0
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def m_per_deg(self) -> tuple[float, float]:
|
|
38
|
+
"""(metres per degree latitude, metres per degree longitude) at the reference."""
|
|
39
|
+
phi = np.radians(self.ref_lat_deg)
|
|
40
|
+
m, n = _radii(phi)
|
|
41
|
+
return float(np.radians(1) * m), float(np.radians(1) * n * np.cos(phi))
|
|
42
|
+
|
|
43
|
+
def to_enu(self, lat_lon: ArrayN2) -> ArrayN2:
|
|
44
|
+
ll = np.radians(as_n2(lat_lon))
|
|
45
|
+
phi0, lam0 = np.radians(self.ref_lat_deg), np.radians(self.ref_lon_deg)
|
|
46
|
+
phim = (ll[:, 0] + phi0) / 2
|
|
47
|
+
m, n = _radii(phim)
|
|
48
|
+
return np.stack([(ll[:, 1] - lam0) * n * np.cos(phim), (ll[:, 0] - phi0) * m], axis=1)
|
|
49
|
+
|
|
50
|
+
def to_wgs84(self, en: ArrayN2) -> ArrayN2:
|
|
51
|
+
en = as_n2(en)
|
|
52
|
+
phi0, lam0 = np.radians(self.ref_lat_deg), np.radians(self.ref_lon_deg)
|
|
53
|
+
phi = phi0 + en[:, 1] / _radii(phi0)[0]
|
|
54
|
+
for _ in range(4): # converges to < 1e-12 rad
|
|
55
|
+
phim = (phi + phi0) / 2
|
|
56
|
+
m, n = _radii(phim)
|
|
57
|
+
phi = phi0 + en[:, 1] / m
|
|
58
|
+
phim = (phi + phi0) / 2
|
|
59
|
+
_, n = _radii(phim)
|
|
60
|
+
lam = lam0 + en[:, 0] / (n * np.cos(phim))
|
|
61
|
+
return np.degrees(np.stack([phi, lam], axis=1))
|
|
62
|
+
|
|
63
|
+
def distance_m(self, a_lat_lon: ArrayN2, b_lat_lon: ArrayN2) -> np.ndarray:
|
|
64
|
+
return np.linalg.norm(self.to_enu(a_lat_lon) - self.to_enu(b_lat_lon), axis=1)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class GroundModel(Protocol):
|
|
68
|
+
def height_m(self, en: ArrayN2) -> np.ndarray: ...
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def is_planar(self) -> bool: ...
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True)
|
|
75
|
+
class FlatGround:
|
|
76
|
+
"""Ground plane at a fixed height relative to the takeoff point (z = 0)."""
|
|
77
|
+
level_m: float = 0.0
|
|
78
|
+
|
|
79
|
+
def height_m(self, en: ArrayN2) -> np.ndarray:
|
|
80
|
+
return np.full(as_n2(en).shape[0], self.level_m)
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def is_planar(self) -> bool:
|
|
84
|
+
return True
|