Skip to main content

uas_cot/
fmv.rs

1//! MISB ST 0601 (the KLV metadata in STANAG 4609 drone video) to CoT, using
2//! the [`misb`] crate.
3//!
4//! [`platform`] is the aircraft with a `<sensor>` element (ATAK draws the
5//! camera field of view from it) and, optionally, the video URL.
6//! [`spi`] is the sensor point of interest: where the center of the picture
7//! is on the ground, linked to the platform.
8//!
9//! ```
10//! use misb::st0601::{Builder, Packet, Tag};
11//! use uas_cot::fmv::{self, Options};
12//!
13//! let mut b = Builder::new(1_700_000_000_000_000);
14//! b.text(Tag::PlatformTailNumber, "N101").unwrap()
15//!     .float(Tag::SensorLatitude, 38.8895).unwrap()
16//!     .float(Tag::SensorLongitude, -77.0353).unwrap()
17//!     .float(Tag::SensorTrueAltitude, 450.0).unwrap()
18//!     .float(Tag::FrameCenterLatitude, 38.8950).unwrap()
19//!     .float(Tag::FrameCenterLongitude, -77.0300).unwrap();
20//! let bytes = b.finish();
21//! let (packet, _) = Packet::parse(&bytes).unwrap();
22//!
23//! let opts = Options::default();
24//! let air = fmv::platform(&packet, &opts).unwrap();
25//! let spi = fmv::spi(&packet, &opts).unwrap();
26//! assert_eq!(air.uid, "fmv-N101");
27//! assert_eq!(spi.uid, "fmv-N101.SPI1");
28//! assert_eq!(spi.links[0].uid, "fmv-N101");
29//! ```
30
31use crate::{Event, Link, Point, Sensor, Track};
32use misb::st0601::{Packet, Tag};
33use std::fmt::Write as _;
34
35/// How KLV packets become events.
36#[derive(Clone, Debug, PartialEq)]
37pub struct Options {
38    /// Affiliation letter for the platform type (default `'f'`: the video
39    /// usually comes from your own aircraft).
40    pub affiliation: char,
41    /// Seconds until the markers go stale (default 10).
42    pub stale_secs: u64,
43    /// Platform UID. Default: `"fmv-"` plus the tail number, call sign,
44    /// designation or mission ID from the packet, in that order, or
45    /// `"fmv-UAS"` when the packet has none of them (many encoders send
46    /// none: give each stream its own UID then).
47    pub uid: Option<String>,
48    /// Video stream URL to attach to the platform (`<__video url>`).
49    pub video_url: Option<String>,
50}
51
52impl Default for Options {
53    fn default() -> Self {
54        Options {
55            affiliation: 'f',
56            stale_secs: 10,
57            uid: None,
58            video_url: None,
59        }
60    }
61}
62
63fn name<'a>(p: &Packet<'a>) -> Option<&'a str> {
64    [
65        Tag::PlatformTailNumber,
66        Tag::PlatformCallSign,
67        Tag::PlatformDesignation,
68        Tag::MissionId,
69    ]
70    .into_iter()
71    .filter_map(|t| p.text(t))
72    .map(str::trim)
73    .find(|s| !s.is_empty())
74}
75
76/// The platform UID used by [`platform`] and [`spi`].
77pub fn platform_uid(p: &Packet<'_>, opts: &Options) -> String {
78    match &opts.uid {
79        Some(u) => u.clone(),
80        None => format!("fmv-{}", name(p).unwrap_or("UAS")),
81    }
82}
83
84/// The platform CoT type for `opts`.
85pub fn platform_type(opts: &Options) -> String {
86    format!("a-{}-A-M-F-Q", opts.affiliation)
87}
88
89fn time_us(p: &Packet<'_>) -> u64 {
90    p.timestamp().unwrap_or_else(crate::now_us)
91}
92
93/// The aircraft: sensor position (tags 13, 14; height above ellipsoid from
94/// tag 104 or 75, else the MSL altitude of tag 15), course and ground speed,
95/// and the camera's line of sight (`<sensor>`): azimuth = platform heading
96/// + sensor relative azimuth, field of view, slant range.
97pub fn platform(p: &Packet<'_>, opts: &Options) -> Option<Event> {
98    let uid = platform_uid(p, opts);
99    let pos = p.sensor_position()?;
100    let mut e = Event::new(uid, platform_type(opts), time_us(p), opts.stale_secs);
101    let (hae, altsrc) = match p.sensor_hae() {
102        Some(h) => (h, "GPS"),
103        None => (pos.height.unwrap_or(0.0), "MSL"),
104    };
105    e.point = Point::new(pos.lat, pos.lon, hae);
106    if !e.point.is_valid() {
107        return None;
108    }
109    e.precision_location = Some(("GPS".into(), altsrc.into()));
110    e.callsign = Some(name(p).map_or_else(|| e.uid.clone(), str::to_string));
111    let heading = p.platform_heading();
112    let course = p.float(Tag::PlatformCourseAngle).or(heading);
113    if let (Some(c), Some(s)) = (course, p.float(Tag::PlatformGroundSpeed)) {
114        e.track = Some(Track {
115            course: c,
116            speed: s,
117        });
118    }
119    let rel_az = p.float(Tag::SensorRelativeAzimuthAngle);
120    let sensor = Sensor {
121        azimuth: heading.zip(rel_az).map(|(h, a)| h + a),
122        elevation: p.float(Tag::SensorRelativeElevationAngle),
123        roll: p.float(Tag::SensorRelativeRollAngle),
124        fov: p.float(Tag::SensorHorizontalFieldOfView),
125        vfov: p.float(Tag::SensorVerticalFieldOfView),
126        range: p.float(Tag::SlantRange),
127        model: p.text(Tag::ImageSourceSensor).map(str::to_string),
128        kind: None,
129    };
130    if sensor.fov.is_some() || sensor.azimuth.is_some() {
131        e.sensor = Some(sensor);
132    }
133    e.video_url = opts.video_url.clone();
134    let mut r = String::from("MISB ST 0601.");
135    for (t, label) in [
136        (Tag::MissionId, "Mission"),
137        (Tag::PlatformDesignation, "Platform"),
138        (Tag::ImageSourceSensor, "Sensor"),
139    ] {
140        if let Some(v) = p.text(t).filter(|s| !s.trim().is_empty()) {
141            let _ = write!(r, " {label}: {}.", v.trim());
142        }
143    }
144    e.remarks = Some(r);
145    Some(e)
146}
147
148/// The sensor point of interest (`b-m-p-s-p-i`): the frame center (tags 23,
149/// 24; height from tag 78, else tag 25), linked to the platform.
150pub fn spi(p: &Packet<'_>, opts: &Options) -> Option<Event> {
151    let puid = platform_uid(p, opts);
152    let fc = p.frame_center()?;
153    let mut e = Event::new(
154        format!("{puid}.SPI1"),
155        "b-m-p-s-p-i",
156        time_us(p),
157        opts.stale_secs,
158    );
159    e.how = "m-i".into();
160    let hae = p
161        .float(Tag::FrameCenterHeightAboveEllipsoid)
162        .or(fc.height)
163        .unwrap_or(0.0);
164    e.point = Point::new(fc.lat, fc.lon, hae);
165    if !e.point.is_valid() {
166        return None;
167    }
168    if let Some(ce) = p.float(Tag::TargetErrorEstimateCe90) {
169        // CE90 to 1-sigma circular error
170        e.point.ce = ce / 2.146;
171    }
172    e.callsign = Some(format!("{} SPI", name(p).unwrap_or(&puid)));
173    e.links.push(Link {
174        uid: puid,
175        kind: platform_type(opts),
176        relation: "p-p".into(),
177    });
178    Some(e)
179}
180
181/// Platform and SPI events for one packet (platform first).
182pub fn events(p: &Packet<'_>, opts: &Options) -> Vec<Event> {
183    platform(p, opts).into_iter().chain(spi(p, opts)).collect()
184}