Skip to main content

edgefirst_decoder_abi/
lib.rs

1// SPDX-FileCopyrightText: Copyright 2026 Au-Zone Technologies
2// SPDX-License-Identifier: Apache-2.0
3
4//! Layout-only C ABI contract for the EdgeFirst detection vocabulary.
5//!
6//! Decoding model outputs into user-consumable structures — detection boxes,
7//! segmentation masks, tile placements — is what the decoder library *is*, so
8//! these types belong to it. They lived in `edgefirst-tensor` because of the
9//! r2 "plain-values-only boundary rule", whose premise (sibling libraries
10//! never link each other) spec Revision 3 overturned. A plain value that
11//! crosses needs a shared DECLARATION, not a shared LINK.
12//!
13//! Emitted into `edgefirst/decoder.h` by cbindgen's `[parse] include`,
14//! exactly as `edgefirst-tensor-abi`'s types are emitted into `tensor.h`.
15
16use std::ffi::c_int;
17
18/// A detection: a normalized box, a score, and a label index.
19///
20/// Coordinates are normalized to `[0, 1]` against the *model input*, not the
21/// source image — un-letterboxing is the consumer's job and needs the letterbox
22/// parameters, which this type deliberately does not carry.
23#[repr(C)]
24#[derive(Debug, Clone, Copy, PartialEq, Default)]
25pub struct EfDetectBox {
26    pub xmin: f32,
27    pub ymin: f32,
28    pub xmax: f32,
29    pub ymax: f32,
30    /// Model-specific confidence; higher is more confident.
31    pub score: f32,
32    /// Label index into the model's class list.
33    pub label: u32,
34}
35
36/// One segmentation result, as plain values.
37///
38/// Crosses library boundaries by the same rule as [`EfDetectBox`]: plain
39/// values, never a handle. `mask` **borrows** the producing list's buffer and
40/// is valid only until that list is freed — stated here because C gives a
41/// caller no way to discover it.
42///
43/// The bounds describe the **mask region**, which is snapped to the proto grid
44/// and therefore encloses rather than equals the companion detection's box.
45#[repr(C)]
46#[derive(Debug, Clone, Copy)]
47pub struct EfSegmentation {
48    pub xmin: f32,
49    pub ymin: f32,
50    pub xmax: f32,
51    pub ymax: f32,
52    /// Row-major mask bytes, `height * width`, borrowed from the list.
53    pub mask: *const u8,
54    pub width: u32,
55    pub height: u32,
56}
57
58/// How overlapping detections from neighbouring tiles are merged.
59#[repr(C)]
60#[derive(Debug, Clone, Copy)]
61pub struct EfMergeConfig {
62    /// An `EF_MATCH_METRIC_*` code: IoU, or Intersection-over-Smaller.
63    ///
64    /// IoS is the default for a reason: an object split across a tile seam has
65    /// *low* IoU with its own fragment but high IoS, so IoU would keep both
66    /// halves as separate detections.
67    pub metric: u32,
68    pub threshold: f32,
69    /// Non-zero to merge across classes.
70    pub class_agnostic: c_int,
71    pub max_det: usize,
72    pub score_threshold: f32,
73    /// An `EF_MERGE_MODE_*` code. `EF_MERGE_MODE_KEEP_BEST` (default): the
74    /// highest-scoring box of each matched group is kept and the boxes it
75    /// matched are dropped. `EF_MERGE_MODE_UNION`: the group becomes its
76    /// enclosing union carrying the max score.
77    ///
78    /// Keep-best is `0`, but note that a zero-initialised struct is still
79    /// not the library default: `metric` defaults to `EF_MATCH_METRIC_IOS`,
80    /// so an all-zero struct selects IoU. Fill with `ef_merge_config_default`.
81    /// The union measured about 0.05 AP50 worse on every frame of the Ocean
82    /// Cleanup ADIS 4K validation (TOP2-836), which is why it is opt-in.
83    ///
84    /// Occupies what was this struct's 4-byte tail pad, so adding it left
85    /// every other field's offset and the 32-byte size unchanged.
86    pub mode: u32,
87}
88
89/// One tile's placement within a frame grid.
90///
91/// Produced by `edgefirst_image::ImageProcessor::plan_tiles` and consumed by
92/// `edgefirst_decoder::tiling` to lift per-tile detections back to full-frame
93/// coordinates. It lives here because it is the contract *between* those two
94/// crates: it was previously defined in `decoder` and re-exported by `image`,
95/// so the producer imported its own output type from its consumer.
96#[derive(Debug, Clone, Copy, PartialEq)]
97pub struct TilePlacement {
98    /// Tile index within the frame grid, `0..count`.
99    pub index: usize,
100    /// Total tiles for this frame (the streaming fan-in fence).
101    pub count: usize,
102    /// Native crop origin `(ox, oy)` in full-frame pixels.
103    pub origin: (f32, f32),
104    /// Native crop size `(cw, ch)` in full-frame pixels. Equals the tile size
105    /// for the full-size tiles the EvenDist grid produces.
106    pub crop_size: (f32, f32),
107    /// Normalized letterbox content bounds `[lx0, ly0, lx1, ly1]` on the model
108    /// input, or `None` when the crop was stretched to fill it (the hot path).
109    pub letterbox: Option<[f32; 4]>,
110    /// Full-frame dimensions `(frame_w, frame_h)` in pixels.
111    pub frame_dims: (f32, f32),
112}
113
114/// C layout of `ef_tile_placement` in `detect.h`.
115///
116/// One declaration for image-capi (producer) and decoder-capi (consumer).
117/// cbindgen excludes this type so the header-only `detect.h` definition wins.
118#[repr(C)]
119#[derive(Debug, Clone, Copy)]
120pub struct EfTilePlacement {
121    pub index: usize,
122    pub count: usize,
123    pub origin_x: f32,
124    pub origin_y: f32,
125    pub crop_width: f32,
126    pub crop_height: f32,
127    pub has_letterbox: c_int,
128    pub letterbox: [f32; 4],
129    pub frame_width: f32,
130    pub frame_height: f32,
131}
132
133impl From<&TilePlacement> for EfTilePlacement {
134    fn from(p: &TilePlacement) -> Self {
135        let (has_letterbox, letterbox) = match p.letterbox {
136            Some(lb) => (1, lb),
137            None => (0, [0.0; 4]),
138        };
139        Self {
140            index: p.index,
141            count: p.count,
142            origin_x: p.origin.0,
143            origin_y: p.origin.1,
144            crop_width: p.crop_size.0,
145            crop_height: p.crop_size.1,
146            has_letterbox,
147            letterbox,
148            frame_width: p.frame_dims.0,
149            frame_height: p.frame_dims.1,
150        }
151    }
152}
153
154impl From<&EfTilePlacement> for TilePlacement {
155    fn from(p: &EfTilePlacement) -> Self {
156        Self {
157            index: p.index,
158            count: p.count,
159            origin: (p.origin_x, p.origin_y),
160            crop_size: (p.crop_width, p.crop_height),
161            letterbox: if p.has_letterbox != 0 {
162                Some(p.letterbox)
163            } else {
164                None
165            },
166            frame_dims: (p.frame_width, p.frame_height),
167        }
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    /// Load-bearing: `edgefirst-image` and `edgefirst-tracker` depend on this
176    /// crate to NAME decoder's types without linking decoder's implementation.
177    /// A single dependency here would drag code into both and defeat that.
178    #[test]
179    fn this_crate_has_no_dependencies_and_never_may() {
180        let manifest = include_str!("../Cargo.toml");
181        assert!(
182            !manifest.contains("[dependencies."),
183            "dependency sub-tables are dependencies too"
184        );
185        let deps = manifest
186            .split("[dependencies]")
187            .nth(1)
188            .expect("manifest has a [dependencies] table");
189        let body = deps.split("\n[").next().unwrap_or(deps);
190        let lines: Vec<&str> = body
191            .lines()
192            .map(str::trim)
193            .filter(|l| !l.is_empty() && !l.starts_with('#'))
194            .collect();
195        assert!(
196            lines.is_empty(),
197            "edgefirst-decoder-abi grew dependencies: {lines:?}"
198        );
199    }
200
201    #[test]
202    fn detect_box_is_six_packed_32_bit_fields() {
203        assert_eq!(std::mem::size_of::<EfDetectBox>(), 24);
204        assert_eq!(std::mem::align_of::<EfDetectBox>(), 4);
205    }
206
207    #[test]
208    fn segmentation_layout_is_pinned() {
209        assert_eq!(std::mem::size_of::<EfSegmentation>(), 32);
210        assert_eq!(std::mem::align_of::<EfSegmentation>(), 8);
211    }
212
213    #[test]
214    fn merge_config_layout_is_pinned() {
215        // `max_det: usize` forces 8-byte alignment and 4 bytes of pad after
216        // `class_agnostic`; `mode` fills what was the tail pad at 28, so the
217        // struct is 32 bytes with or without it. Matches `detect.h`.
218        assert_eq!(std::mem::size_of::<EfMergeConfig>(), 32);
219        assert_eq!(std::mem::align_of::<EfMergeConfig>(), 8);
220        assert_eq!(std::mem::offset_of!(EfMergeConfig, metric), 0);
221        assert_eq!(std::mem::offset_of!(EfMergeConfig, threshold), 4);
222        assert_eq!(std::mem::offset_of!(EfMergeConfig, class_agnostic), 8);
223        assert_eq!(std::mem::offset_of!(EfMergeConfig, max_det), 16);
224        assert_eq!(std::mem::offset_of!(EfMergeConfig, score_threshold), 24);
225        assert_eq!(std::mem::offset_of!(EfMergeConfig, mode), 28);
226    }
227
228    #[test]
229    fn tile_placement_layout_is_pinned() {
230        // 60 bytes of fields, align 8 -> 64. Matches `detect.h`.
231        assert_eq!(std::mem::size_of::<EfTilePlacement>(), 64);
232        assert_eq!(std::mem::align_of::<EfTilePlacement>(), 8);
233    }
234}