Skip to main content

cumulus3d_cli/
compose.rs

1/*
2 * compose.rs
3 *
4 * Copyright (c) 2026 ParkSangWoo
5 *
6 * Author(s):
7 *
8 *      ParkSangWoo <dev.parksangwoo@gmail.com>
9 *
10 *
11 * This file is part of cumulus3d.
12 *
13 * Licensed under the Apache License, Version 2.0 (the "License");
14 * you may not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
16 *
17 *      http://www.apache.org/licenses/LICENSE-2.0
18 *
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
24 *
25 * SPDX-License-Identifier: Apache-2.0
26 */
27
28//! Declarative incremental composition for live frame sources.
29//!
30//! [`crate::declare::Recon`] runs a finite, pre-discovered folder to completion. This module is the live counterpart:
31//! a retained node ([`ReconNode`]) owns a [`Session`] and its [`Pipeline`], and the caller only *declares* the current
32//! input state ([`FrameState`]). The node reconciles each declaration against what it has already accepted and does
33//! the minimal incremental work:
34//!
35//! | declared state | node action |
36//! |---|---|
37//! | new synchronized set (next sequence) | ingest one position |
38//! | same key and revision again | nothing ([`Outcome::Duplicate`]) |
39//! | set with cameras missing, or [`FrameState::Pending`] | wait, ingest nothing ([`Outcome::Waiting`]) |
40//! | sequence jump (dropped frames) | ingest, report the gap ([`Outcome::Appended`]`{ skipped }`) |
41//! | late arrival of an older sequence | per [`ReconcilePolicy`] |
42//! | higher revision of an accepted sequence | per [`ReconcilePolicy`] |
43//! | [`FrameState::End`] / [`ReconNode::close`] | close open zones, drain refinement, final events |
44//!
45//! Frames are identified by [`FrameKey`] (`source_id`, `sequence`, `revision`), not by path. Each accepted sequence
46//! becomes one position, in sequence order. Payloads can be files under the image folder or in-memory images
47//! ([`FramePayload`]); in-memory images are written atomically to a spool folder inside the image folder, because the
48//! reconstruction core reads images by name.
49//!
50//! Events are the ordinary pipeline events (hooks registered on the builder, or [`ReconNode::subscribe`]).
51//! Reconciliation decisions that drop or reorder input are also reported as [`Event::Warning`].
52//!
53//! # Example
54//!
55//! ```no_run
56//! use cumulus3d_cli::compose::{reconstruct, CompositionHost, FrameKey, FrameState, LiveFrameSet, ReconNode, ReconcilePolicy};
57//! use cumulus3d_cli::declare::Dense;
58//!
59//! fn main() -> Result<(), cumulus3d_cli::compose::ComposeError> {
60//!     let host = CompositionHost::new();
61//!     let recon = ReconNode::declare()
62//!         .images("live/images")
63//!         .cameras(["camF", "camR", "camL"])
64//!         .zones(12, 2)
65//!         .dense(Dense::profile("fast").fusion_min_views(3))
66//!         .reconcile(ReconcilePolicy::ReplayWindow { positions: 4 })
67//!         .on_zone_preview(|range, cloud| println!("preview {}: {} points", range.zone, cloud.len()))
68//!         .build(&host)?;
69//!
70//!     let set = |seq: u64| {
71//!         LiveFrameSet::new(FrameKey::new("drone-1", seq, 0))
72//!             .file("camF", format!("camF/camF_{:04}.jpg", seq * 3))
73//!             .file("camR", format!("camR/camR_{:04}.jpg", seq * 3))
74//!             .file("camL", format!("camL/camL_{:04}.jpg", seq * 3))
75//!     };
76//!     recon.compose(FrameState::ready(set(0)))?;
77//!     recon.compose(FrameState::ready(set(1)))?;
78//!     recon.compose(FrameState::ready(set(1)))?; // no-op: same identity and revision
79//!     // The same node, found by id (positional-memoization style):
80//!     reconstruct(&host, "default", FrameState::ready(set(2)))?;
81//!     let closed = recon.close()?;
82//!     println!("{} events, {:?}", closed.summary.events, closed.stats);
83//!     Ok(())
84//! }
85//! ```
86//!
87//! For a producer thread (decoder, network receiver) use [`ReconNode::spawn`]: the node then runs on its own thread
88//! behind a bounded queue with an explicit [`Backpressure`] policy, and the producer only calls
89//! [`ComposeHandle::send`] / [`ComposeHandle::try_send`] (both usable from async code; `try_send` never blocks).
90
91use crate::blocks::LiveStream;
92use crate::declare::{AlignFrame, Dense, Features, Plan};
93use crate::densewrap::{make_ba_backend, make_match_backend, make_sift_backend, make_sparse_backend, parse_profile};
94use crate::events::{Command, Event, EventKind, Frame, ZoneRange};
95use crate::intrinsics::{IntrinsicsPrior, DEFAULT_DIST_SIGMA, DEFAULT_FOCAL_SIGMA};
96use crate::live::DisplayFeed;
97use crate::pipeline::{Pipeline, QueuePolicy, Summary};
98use crate::post::LiveOptions;
99use crate::session::{FrameSet, Input, Session, SessionConfig};
100use crate::sinks::{self, DefaultSinks, SinkOptions, SinkSet};
101use cumulus3d_core::io::ply::PointCloud;
102use cumulus3d_core::io::GpsRecord;
103use std::collections::{BTreeMap, HashMap, VecDeque};
104use std::fmt;
105use std::path::{Path, PathBuf};
106use std::sync::mpsc::Receiver;
107use std::sync::{Arc, Condvar, Mutex, MutexGuard};
108use std::thread::JoinHandle;
109use std::time::SystemTime;
110
111// ============================================================================================
112// Input model
113// ============================================================================================
114
115/// Stable identity of one synchronized frame set.
116#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
117pub struct FrameKey {
118    /// Source (stream) identity. A node accepts one source.
119    pub source_id: String,
120    /// Synchronized position sequence number (increasing along the stream).
121    pub sequence: u64,
122    /// Correction/replacement version of this sequence (0 = original).
123    pub revision: u32,
124}
125
126impl FrameKey {
127    /// Key from its three parts.
128    pub fn new(source_id: impl Into<String>, sequence: u64, revision: u32) -> Self {
129        Self { source_id: source_id.into(), sequence, revision }
130    }
131}
132
133impl fmt::Display for FrameKey {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        write!(f, "{}#{}r{}", self.source_id, self.sequence, self.revision)
136    }
137}
138
139/// Encoded image container for [`FramePayload::Encoded`].
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub enum EncodedFormat {
142    /// JPEG bytes.
143    Jpeg,
144    /// PNG bytes.
145    Png,
146}
147
148impl EncodedFormat {
149    fn extension(self) -> &'static str {
150        match self {
151            EncodedFormat::Jpeg => "jpg",
152            EncodedFormat::Png => "png",
153        }
154    }
155}
156
157/// Where the pixels of one camera frame come from.
158#[derive(Clone)]
159pub enum FramePayload {
160    /// Existing file, relative to the node's image folder. The producer must finish writing it before declaring it.
161    File {
162        /// Path relative to the image folder (also the image name in models and GPS records).
163        relative_name: String,
164    },
165    /// Decoded RGB8 pixels (row-major, `width * height * 3` bytes). Spooled as PNG.
166    Rgb8 {
167        /// Width in pixels.
168        width: u32,
169        /// Height in pixels.
170        height: u32,
171        /// Pixels.
172        pixels: Arc<[u8]>,
173    },
174    /// Encoded image bytes. Spooled as-is.
175    Encoded {
176        /// Image bytes.
177        bytes: Arc<[u8]>,
178        /// Container format.
179        format: EncodedFormat,
180    },
181}
182
183impl fmt::Debug for FramePayload {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        match self {
186            FramePayload::File { relative_name } => f.debug_struct("File").field("relative_name", relative_name).finish(),
187            FramePayload::Rgb8 { width, height, .. } => f.debug_struct("Rgb8").field("width", width).field("height", height).finish(),
188            FramePayload::Encoded { bytes, format } => {
189                f.debug_struct("Encoded").field("bytes", &bytes.len()).field("format", format).finish()
190            }
191        }
192    }
193}
194
195/// One camera frame of a synchronized set.
196#[derive(Clone, Debug)]
197pub struct LiveImage {
198    /// Camera name (one of the node's cameras).
199    pub camera: String,
200    /// Pixels.
201    pub payload: FramePayload,
202}
203
204/// One synchronized frame set (one camera frame per camera) with its identity.
205#[derive(Clone, Debug)]
206pub struct LiveFrameSet {
207    /// Identity.
208    pub key: FrameKey,
209    /// Capture time.
210    pub timestamp: SystemTime,
211    /// Camera frames, any order.
212    pub images: Vec<LiveImage>,
213    /// GPS fixes for this set. A record named after a camera (e.g. `"camF"`) is renamed to that camera's stored
214    /// image name; a record already named after the stored image is kept.
215    pub gps: Vec<GpsRecord>,
216}
217
218impl LiveFrameSet {
219    /// Empty set with this key, stamped now.
220    pub fn new(key: FrameKey) -> Self {
221        Self { key, timestamp: SystemTime::now(), images: Vec::new(), gps: Vec::new() }
222    }
223    /// Adds a frame.
224    pub fn image(mut self, camera: impl Into<String>, payload: FramePayload) -> Self {
225        self.images.push(LiveImage { camera: camera.into(), payload });
226        self
227    }
228    /// Adds a file frame (path relative to the image folder).
229    pub fn file(self, camera: impl Into<String>, relative_name: impl Into<String>) -> Self {
230        self.image(camera, FramePayload::File { relative_name: relative_name.into() })
231    }
232    /// Adds an RGB8 frame.
233    pub fn rgb8(self, camera: impl Into<String>, width: u32, height: u32, pixels: impl Into<Arc<[u8]>>) -> Self {
234        self.image(camera, FramePayload::Rgb8 { width, height, pixels: pixels.into() })
235    }
236    /// Adds an encoded frame.
237    pub fn encoded(self, camera: impl Into<String>, bytes: impl Into<Arc<[u8]>>, format: EncodedFormat) -> Self {
238        self.image(camera, FramePayload::Encoded { bytes: bytes.into(), format })
239    }
240    /// Adds a GPS fix for one camera (`name` = camera name, see [`LiveFrameSet::gps`]).
241    pub fn gps_fix(mut self, camera: impl Into<String>, lat: f64, lon: f64, alt: f64) -> Self {
242        self.gps.push(GpsRecord { name: camera.into(), lat, lon, alt });
243        self
244    }
245    /// Sets the capture time.
246    pub fn at(mut self, t: SystemTime) -> Self {
247        self.timestamp = t;
248        self
249    }
250}
251
252/// Declared input state.
253#[derive(Clone, Debug)]
254pub enum FrameState {
255    /// A synchronized set is available. If cameras are missing it is treated like [`FrameState::Pending`].
256    Ready(LiveFrameSet),
257    /// A set is being assembled; nothing is ingested until it is declared ready.
258    Pending {
259        /// Identity of the set being assembled.
260        key: FrameKey,
261        /// Capture time.
262        timestamp: SystemTime,
263        /// Cameras not yet received.
264        missing_cameras: Vec<String>,
265    },
266    /// The stream ended: same as [`ReconNode::close`], the summary is kept for a later `close`.
267    End,
268}
269
270impl FrameState {
271    /// [`FrameState::Ready`].
272    pub fn ready(set: LiveFrameSet) -> Self {
273        FrameState::Ready(set)
274    }
275    /// [`FrameState::Pending`] stamped now.
276    pub fn pending<S: Into<String>>(key: FrameKey, missing_cameras: impl IntoIterator<Item = S>) -> Self {
277        FrameState::Pending { key, timestamp: SystemTime::now(), missing_cameras: missing_cameras.into_iter().map(Into::into).collect() }
278    }
279}
280
281// ============================================================================================
282// Policies and results
283// ============================================================================================
284
285/// What to do with input that is not a plain append (late arrivals and corrected revisions).
286#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
287pub enum ReconcilePolicy {
288    /// Append new sequences only. Late arrivals and corrections are ignored (with a warning). Gaps are accepted.
289    #[default]
290    AppendOnly,
291    /// Like `AppendOnly`, but a late arrival or a correction within the last `positions` positions rewinds the session
292    /// to that position (`Command::ResetFrom`) and replays the corrected/inserted set and every later set.
293    /// Older ones are ignored. Costs memory for `positions + 1` rewind points.
294    ReplayWindow {
295        /// Replay window in positions.
296        positions: usize,
297    },
298    /// A correction keeps the registered geometry and rebuilds the outputs (preview and refined clouds) of every
299    /// arrived zone containing the position, with the corrected pixels (`Command::InvalidateZone`). The corrected
300    /// frame is stored under the original image name; features, matches and poses are not recomputed and GPS fixes of
301    /// the correction are not applied (use `ReplayWindow` for those). Late arrivals are ignored.
302    InvalidateAffectedZones,
303    /// Accept only the exact next sequence; everything else (gap, late, correction, foreign source) is an error.
304    Strict,
305}
306
307/// Queue policy between a producer and a spawned node ([`ReconNode::spawn`]).
308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
309pub enum Backpressure {
310    /// Never drop; the queue grows without bound.
311    Unbounded,
312    /// `send` blocks while `max_pending` states are queued (`try_send` returns [`SendError::Full`]).
313    Block {
314        /// Queue capacity.
315        max_pending: usize,
316    },
317    /// Keep the newest states: when `max_pending` are queued, the oldest queued ready set is dropped (it then shows up
318    /// as a sequence gap). Capture never waits for reconstruction.
319    KeepLatest {
320        /// Queue capacity.
321        max_pending: usize,
322    },
323}
324
325impl Default for Backpressure {
326    fn default() -> Self {
327        Backpressure::Block { max_pending: 8 }
328    }
329}
330
331/// Why a declared state was not applied.
332#[derive(Clone, Debug, PartialEq, Eq)]
333pub enum IgnoreReason {
334    /// Revision lower than the accepted one.
335    StaleRevision {
336        /// Accepted revision.
337        accepted: u32,
338    },
339    /// Higher revision of an accepted sequence, but the policy does not apply corrections.
340    CorrectionNotApplied,
341    /// Older sequence than the newest accepted one, never seen before, and the policy does not insert.
342    Late,
343    /// Correction or late arrival older than the replay window (or no rewind point left).
344    OutsideReplayWindow {
345        /// Position it would have to rewind to.
346        position: usize,
347    },
348    /// Different `source_id` than the node's source.
349    ForeignSource {
350        /// The node's source.
351        expected: String,
352    },
353    /// The node is closed.
354    Closed,
355}
356
357impl fmt::Display for IgnoreReason {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        match self {
360            IgnoreReason::StaleRevision { accepted } => write!(f, "stale revision (accepted revision {accepted})"),
361            IgnoreReason::CorrectionNotApplied => write!(f, "correction not applied by this policy"),
362            IgnoreReason::Late => write!(f, "late arrival not inserted by this policy"),
363            IgnoreReason::OutsideReplayWindow { position } => write!(f, "outside replay window (position {position})"),
364            IgnoreReason::ForeignSource { expected } => write!(f, "foreign source (node source is {expected})"),
365            IgnoreReason::Closed => write!(f, "node closed"),
366        }
367    }
368}
369
370/// Result of one declaration.
371#[derive(Clone, Debug, PartialEq, Eq)]
372pub enum Outcome {
373    /// Ingested as a new position. `skipped` = sequences missing between the previous accepted one and this one.
374    Appended {
375        /// New position.
376        position: usize,
377        /// Missing sequences before this one.
378        skipped: u64,
379    },
380    /// Same key and revision as an accepted set; nothing done.
381    Duplicate {
382        /// Its position.
383        position: usize,
384    },
385    /// Set incomplete; waiting for these cameras.
386    Waiting {
387        /// Missing cameras.
388        missing: Vec<String>,
389    },
390    /// Rewound to `from` and replayed `positions` sets (correction or late arrival under `ReplayWindow`).
391    Replayed {
392        /// Rewind position.
393        from: usize,
394        /// Sets pushed again (including the new one).
395        positions: usize,
396    },
397    /// Correction applied by rebuilding these zones (`InvalidateAffectedZones`).
398    Invalidated {
399        /// Corrected position.
400        position: usize,
401        /// Rebuilt zones (empty if no zone containing the position had arrived yet).
402        zones: Vec<usize>,
403    },
404    /// Not applied.
405    Ignored(IgnoreReason),
406    /// The stream ended and the node closed.
407    Ended,
408}
409
410/// Errors.
411#[derive(Clone, Debug, PartialEq, Eq)]
412pub enum ComposeError {
413    /// Builder configuration problems (all of them).
414    Config(Vec<String>),
415    /// Malformed frame set (unknown or duplicate camera, missing file, bad pixel buffer).
416    InvalidFrameSet(String),
417    /// Rejected by [`ReconcilePolicy::Strict`] (or a gap/late/correction under it).
418    Rejected(String),
419    /// File I/O while spooling.
420    Io(String),
421    /// The reconstruction session stopped on a fatal error.
422    Session(String),
423    /// No node with this id on the host.
424    UnknownNode(String),
425    /// A node with this id already exists on the host.
426    DuplicateNode(String),
427    /// The node was already closed and its summary taken.
428    Closed,
429}
430
431impl fmt::Display for ComposeError {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        match self {
434            ComposeError::Config(v) => write!(f, "invalid node configuration: {}", v.join("; ")),
435            ComposeError::InvalidFrameSet(m) => write!(f, "invalid frame set: {m}"),
436            ComposeError::Rejected(m) => write!(f, "rejected: {m}"),
437            ComposeError::Io(m) => write!(f, "i/o: {m}"),
438            ComposeError::Session(m) => write!(f, "session failed: {m}"),
439            ComposeError::UnknownNode(id) => write!(f, "no node {id:?} on this host"),
440            ComposeError::DuplicateNode(id) => write!(f, "node {id:?} already exists on this host"),
441            ComposeError::Closed => write!(f, "node already closed"),
442        }
443    }
444}
445
446impl std::error::Error for ComposeError {}
447
448/// Reconciliation counters.
449#[derive(Clone, Debug, Default, PartialEq, Eq)]
450pub struct ComposeStats {
451    /// Declarations received (all states).
452    pub declared: u64,
453    /// Sets ingested as new positions.
454    pub appended: u64,
455    /// Duplicate declarations (no-ops).
456    pub duplicates: u64,
457    /// Pending/incomplete declarations.
458    pub waiting: u64,
459    /// Sequences missing between accepted ones (dropped frames).
460    pub skipped_sequences: u64,
461    /// Rewind-and-replay operations.
462    pub replays: u64,
463    /// Sets pushed again by replays.
464    pub replayed_positions: u64,
465    /// Corrections applied by zone invalidation.
466    pub invalidations: u64,
467    /// Declarations ignored.
468    pub ignored: u64,
469}
470
471/// What [`ReconNode::close`] returns.
472pub struct Closed {
473    /// Final session state.
474    pub session: Session,
475    /// Pipeline summary (event counts, hook calls).
476    pub summary: Summary,
477    /// Reconciliation counters.
478    pub stats: ComposeStats,
479}
480
481impl fmt::Debug for Closed {
482    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483        f.debug_struct("Closed")
484            .field("positions", &self.session.positions())
485            .field("summary", &self.summary)
486            .field("stats", &self.stats)
487            .finish()
488    }
489}
490
491// ============================================================================================
492// Host
493// ============================================================================================
494
495/// Owner of retained nodes, addressed by id. Cheap to clone (shared).
496#[derive(Clone, Default)]
497pub struct CompositionHost {
498    nodes: Arc<Mutex<BTreeMap<String, ReconNode>>>,
499}
500
501impl fmt::Debug for CompositionHost {
502    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
503        f.debug_struct("CompositionHost").field("nodes", &self.ids()).finish()
504    }
505}
506
507impl CompositionHost {
508    /// Empty host.
509    pub fn new() -> Self {
510        Self::default()
511    }
512    /// Node by id.
513    pub fn node(&self, id: &str) -> Option<ReconNode> {
514        lock(&self.nodes).get(id).cloned()
515    }
516    /// Ids of the open nodes.
517    pub fn ids(&self) -> Vec<String> {
518        lock(&self.nodes).keys().cloned().collect()
519    }
520    /// Declares a state on node `id` ([`ReconNode::compose`]).
521    pub fn compose(&self, id: &str, state: FrameState) -> Result<Outcome, ComposeError> {
522        self.node(id).ok_or_else(|| ComposeError::UnknownNode(id.to_string()))?.compose(state)
523    }
524    /// Closes node `id` and removes it from the host.
525    pub fn close(&self, id: &str) -> Result<Closed, ComposeError> {
526        let node = lock(&self.nodes).remove(id).ok_or_else(|| ComposeError::UnknownNode(id.to_string()))?;
527        node.close_inner()
528    }
529    /// Closes every node (id order) and removes them.
530    pub fn close_all(&self) -> Vec<(String, Result<Closed, ComposeError>)> {
531        let nodes = std::mem::take(&mut *lock(&self.nodes));
532        nodes.into_iter().map(|(id, n)| (id, n.close_inner())).collect()
533    }
534    fn register(&self, node: &ReconNode) -> Result<(), ComposeError> {
535        let mut m = lock(&self.nodes);
536        if m.contains_key(&node.id) {
537            return Err(ComposeError::DuplicateNode(node.id.clone()));
538        }
539        m.insert(node.id.clone(), node.clone());
540        Ok(())
541    }
542}
543
544/// Declares `state` on the host's node `id`: the declarative entry point
545/// (`reconstruct(&host, "main", FrameState::ready(set))` on every new input).
546pub fn reconstruct(host: &CompositionHost, id: &str, state: FrameState) -> Result<Outcome, ComposeError> {
547    host.compose(id, state)
548}
549
550// ============================================================================================
551// Builder
552// ============================================================================================
553
554type Attach = Box<dyn FnOnce(Pipeline<Session>) -> Pipeline<Session> + Send>;
555
556/// Records a node configuration; [`NodeBuilder::build`] checks it and creates the node on a host.
557///
558/// The reconstruction settings are a [`Plan`] (same fields and TOML as [`crate::declare`]); the input folder is the
559/// image root, positions/stride are not used (input is declared live), and GPS comes with each set.
560pub struct NodeBuilder {
561    id: String,
562    plan: Plan,
563    policy: ReconcilePolicy,
564    backpressure: Backpressure,
565    source: Option<String>,
566    spool: PathBuf,
567    output: Option<(PathBuf, SinkOptions)>,
568    attach: Vec<Attach>,
569    frames: bool,
570    deltas: Option<LiveOptions>,
571    /// Geodetic origin written to the live diff stream manifest (`origin_gps`).
572    stream_origin: Option<[f64; 3]>,
573    /// Only run.log, the timeline and the live diff stream are written to the output folder.
574    stream_only: bool,
575    /// Soft intrinsics prior (set by the builder methods; the plan's `sparse.intrinsics_prior` file is the fallback).
576    prior: Option<IntrinsicsPrior>,
577    /// Error from reading a prior file in [`NodeBuilder::intrinsics_prior_json`], reported by `build`.
578    prior_error: Option<String>,
579}
580
581impl fmt::Debug for NodeBuilder {
582    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583        f.debug_struct("NodeBuilder").field("id", &self.id).field("policy", &self.policy).field("hooks", &self.attach.len()).finish()
584    }
585}
586
587impl ReconNode {
588    /// Starts a node declaration with the default plan (`aerial-formation` cameras, zones 12/2), dense off, no output files.
589    pub fn declare() -> NodeBuilder {
590        let mut plan = Plan::default();
591        plan.dense.enabled = false;
592        plan.gps = None;
593        NodeBuilder {
594            id: "default".to_string(),
595            plan,
596            policy: ReconcilePolicy::default(),
597            backpressure: Backpressure::default(),
598            source: None,
599            spool: PathBuf::from(".live"),
600            output: None,
601            attach: Vec::new(),
602            frames: false,
603            deltas: None,
604            stream_origin: None,
605            stream_only: false,
606            prior: None,
607            prior_error: None,
608        }
609    }
610}
611
612impl NodeBuilder {
613    /// Node id on the host (default `"default"`).
614    pub fn id(mut self, id: impl Into<String>) -> Self {
615        self.id = id.into();
616        self
617    }
618    /// Replaces the reconstruction settings with a plan (e.g. read from TOML). Input positions/stride and
619    /// the GPS file are ignored; sinks are ignored (use [`NodeBuilder::output`]).
620    pub fn plan(mut self, plan: Plan) -> Self {
621        self.plan = plan;
622        self
623    }
624    /// Image folder: file payloads are relative to it, in-memory payloads are spooled inside it.
625    pub fn images(mut self, dir: impl Into<PathBuf>) -> Self {
626        self.plan.input.images = dir.into();
627        self
628    }
629    /// Cameras of one synchronized set, in position order.
630    pub fn cameras<S: Into<String>>(mut self, cams: impl IntoIterator<Item = S>) -> Self {
631        self.plan.input.cameras = cams.into_iter().map(Into::into).collect();
632        self
633    }
634    /// Zone size and overlap in positions.
635    pub fn zones(mut self, span: usize, overlap: usize) -> Self {
636        self.plan.zones.span = span;
637        self.plan.zones.overlap = overlap;
638        self
639    }
640    /// Coordinate alignment (ENU needs GPS fixes in the sets).
641    pub fn align(mut self, frame: AlignFrame) -> Self {
642        self.plan.align.frame = frame;
643        self
644    }
645    /// Fixes the ENU origin at the first GPS fix.
646    pub fn fixed_enu_origin(mut self, on: bool) -> Self {
647        self.plan.align.fixed_origin = on;
648        self
649    }
650    /// Feature extraction settings.
651    pub fn features(mut self, f: Features) -> Self {
652        self.plan.features = f;
653        self
654    }
655    /// Descriptor matching backend (`cpu` | `cuda`).
656    pub fn match_backend(mut self, name: &str) -> Self {
657        self.plan.matching.backend = name.to_string();
658        self
659    }
660    /// CUDA for features, matching, the sparse stages, densification, undistortion and bundle adjustment.
661    pub fn gpu(mut self) -> Self {
662        self.plan.features.backend = "cuda".into();
663        self.plan.matching.backend = "cuda".into();
664        self.plan.sparse.backend = "cuda".into();
665        self.plan.dense.backend = "cuda".into();
666        self.plan.sparse.ba_backend = "cuda".into();
667        self.plan.dense.undistort_backend = "cuda".into();
668        self
669    }
670    /// Stable display (see [`SessionConfig::stable_display`]): intrinsics are settled then frozen, later zones are anchored to the
671    /// shown ones with shared 3D points, and shown zones are re-densified in place (`ZoneRefined` of an earlier zone again), so
672    /// the displayed cloud only gets refined and never jumps. Settle parameters come from the plan (`sparse.settle_tol`,
673    /// `sparse.settle_max_zone`). Combine with [`NodeBuilder::fixed_enu_origin`]`(true)` for a display in a fixed ENU frame.
674    pub fn stable_display(mut self, on: bool) -> Self {
675        self.plan.sparse.stable_display = on;
676        self
677    }
678    /// Computes the in-memory display updates in the library: after every dense zone result a point-keyed
679    /// [`Event::DisplayDelta`] is delivered to subscribers and hooks (`EventKind::DisplayDelta`). Thinning (`stride`), overlap
680    /// voxel ownership and zone composition follow [`crate::post::LiveDisplay`]; `relocate` is decided by the node (on only
681    /// when previews exist). Needs dense clouds with point keys (`.dense(..)`, which the session always keys). The composition runs on
682    /// the composing thread right after the causing event; the ENU origin reported in the delta frame is the first GPS fix
683    /// declared.
684    pub fn display_deltas(mut self, opts: LiveOptions) -> Self {
685        self.deltas = Some(opts);
686        self
687    }
688    /// Triangulate only newly registered images.
689    pub fn incremental_triangulation(mut self, on: bool) -> Self {
690        self.plan.sparse.incremental_triangulation = on;
691        self
692    }
693    /// Stable display settling: intrinsics change tolerance and the last zone that may still settle
694    /// (see [`SessionConfig::settle_tol`], [`SessionConfig::settle_max_zone`]).
695    pub fn settle(mut self, tol: f64, max_zone: usize) -> Self {
696        self.plan.sparse.settle_tol = tol;
697        self.plan.sparse.settle_max_zone = max_zone;
698        self
699    }
700    /// Live display thinning of the live diff stream: keep 1 of `stride` points by key hash (1 = keep all; default 6).
701    pub fn live_stride(mut self, stride: usize) -> Self {
702        self.plan.sinks.live_stride = stride;
703        self
704    }
705    /// Geodetic origin `[lat, lon, alt]` written to the live diff stream manifest. Give the first GPS fix the node will see
706    /// (with [`NodeBuilder::fixed_enu_origin`] it is the origin of every zone); without it the manifest frame is `display`.
707    pub fn stream_origin(mut self, lat: f64, lon: f64, alt: f64) -> Self {
708        self.stream_origin = Some([lat, lon, alt]);
709        self
710    }
711    /// With [`NodeBuilder::stable_display`] and [`NodeBuilder::output`]: write only run.log, the timeline and the live diff
712    /// stream, not the zone PLYs, the display PLYs, the per-zone models or the post-processing snapshots (default off).
713    pub fn stream_only(mut self, on: bool) -> Self {
714        self.stream_only = on;
715        self
716    }
717    /// Densification settings (enables it).
718    pub fn dense(mut self, d: Dense) -> Self {
719        self.plan.dense = Dense { enabled: true, ..d };
720        self
721    }
722    /// No densification (default).
723    pub fn no_dense(mut self) -> Self {
724        self.plan.dense.enabled = false;
725        self
726    }
727    /// RANSAC seed.
728    pub fn seed(mut self, seed: u64) -> Self {
729        self.plan.seed = Some(seed);
730        self
731    }
732    /// Reconciliation policy (default [`ReconcilePolicy::AppendOnly`]).
733    pub fn reconcile(mut self, p: ReconcilePolicy) -> Self {
734        self.policy = p;
735        self
736    }
737    /// Producer queue policy for [`ReconNode::spawn`] (default `Block { max_pending: 8 }`).
738    pub fn backpressure(mut self, b: Backpressure) -> Self {
739        self.backpressure = b;
740        self
741    }
742    /// Accept only this source id (default: the first declared source).
743    pub fn source(mut self, id: impl Into<String>) -> Self {
744        self.source = Some(id.into());
745        self
746    }
747    /// Spool folder for in-memory payloads, relative to the image folder (default `.live`).
748    pub fn spool(mut self, rel: impl Into<PathBuf>) -> Self {
749        self.spool = rel.into();
750        self
751    }
752    /// Writes the standard output files (timeline, run.log, zone PLYs, snapshots) to `dir`. With
753    /// [`NodeBuilder::stable_display`] also the live diff stream (`live/stream/`).
754    pub fn output(mut self, dir: impl Into<PathBuf>, opts: SinkOptions) -> Self {
755        self.output = Some((dir.into(), opts));
756        self
757    }
758    fn hook(mut self, f: impl FnOnce(Pipeline<Session>) -> Pipeline<Session> + Send + 'static) -> Self {
759        self.attach.push(Box::new(f));
760        self
761    }
762    /// Hook for one event kind ([`Pipeline::on`]). `FrameDecoded` turns frame decoding on.
763    pub fn on<F>(mut self, kind: EventKind, f: F) -> Self
764    where
765        F: FnMut(&Event) + Send + 'static,
766    {
767        self.frames |= kind == EventKind::FrameDecoded;
768        self.hook(move |p| p.on(kind, f))
769    }
770    /// Hook for every event ([`Pipeline::on_any`]).
771    pub fn on_event<F>(self, f: F) -> Self
772    where
773        F: FnMut(&Event) + Send + 'static,
774    {
775        self.hook(move |p| p.on_any(f))
776    }
777    /// Decoded input frames ([`Pipeline::on_frame`]); turns frame decoding on.
778    pub fn on_frame<F>(mut self, f: F) -> Self
779    where
780        F: FnMut(&Arc<Frame>) + Send + 'static,
781    {
782        self.frames = true;
783        self.hook(move |p| p.on_frame(f))
784    }
785    /// Zone preview clouds ([`Pipeline::on_zone_preview`]).
786    pub fn on_zone_preview<F>(self, f: F) -> Self
787    where
788        F: FnMut(ZoneRange, &Arc<PointCloud>) + Send + 'static,
789    {
790        self.hook(move |p| p.on_zone_preview(f))
791    }
792    /// Zone refined clouds ([`Pipeline::on_zone_refined`]).
793    pub fn on_zone_refined<F>(self, f: F) -> Self
794    where
795        F: FnMut(ZoneRange, &Arc<PointCloud>) + Send + 'static,
796    {
797        self.hook(move |p| p.on_zone_refined(f))
798    }
799    /// Warnings and errors ([`Pipeline::on_message`]); includes reconciliation warnings.
800    pub fn on_message<F>(self, f: F) -> Self
801    where
802        F: FnMut(EventKind, &str) + Send + 'static,
803    {
804        self.hook(move |p| p.on_message(f))
805    }
806    /// Per-kind hook queue policy ([`Pipeline::policy`]), e.g. `LatestPerKey` for `ZonePreview`.
807    pub fn event_policy(self, kind: EventKind, p: QueuePolicy) -> Self {
808        self.hook(move |pl| pl.policy(kind, p))
809    }
810    /// Runs hooks synchronously on the composing thread ([`Pipeline::sync`]).
811    pub fn sync_hooks(self, on: bool) -> Self {
812        self.hook(move |pl| pl.sync(on))
813    }
814
815    /// Soft intrinsics prior (the CLI's `--intrinsics-prior`): every camera starts from the given parameters (except the
816    /// principal point) and the bundle adjustment is pulled towards them with the prior's σ values. Cameras are keyed by
817    /// camera name (one of [`NodeBuilder::cameras`]) or by id; a camera without an entry is left alone. Checked by `build`.
818    ///
819    /// ```no_run
820    /// use cumulus3d_cli::compose::ReconNode;
821    /// use cumulus3d_cli::intrinsics::IntrinsicsPrior;
822    /// let prior = IntrinsicsPrior::new()
823    ///     .sigmas(0.005, 0.01) // focal: relative, distortion: absolute
824    ///     .opencv("camF", [1607.4, 1611.2, 1024.0, 576.0, 0.082, -0.084, 0.0013, 0.0014]);
825    /// let _builder = ReconNode::declare().images("live/images").cameras(["camF"]).intrinsics_prior(prior);
826    /// ```
827    pub fn intrinsics_prior(mut self, prior: IntrinsicsPrior) -> Self {
828        self.prior = Some(prior);
829        self.prior_error = None;
830        self
831    }
832
833    /// Reads the prior from a JSON file (same format as the CLI's `--intrinsics-prior`; default σ values 0.005 / 0.01).
834    /// A read or parse error is reported by `build`. For other σ values use [`IntrinsicsPrior::load`] and
835    /// [`NodeBuilder::intrinsics_prior`].
836    pub fn intrinsics_prior_json(mut self, path: impl AsRef<Path>) -> Self {
837        match IntrinsicsPrior::load(path, DEFAULT_FOCAL_SIGMA, DEFAULT_DIST_SIGMA) {
838            Ok(p) => {
839                self.prior = Some(p);
840                self.prior_error = None;
841            }
842            Err(e) => self.prior_error = Some(e),
843        }
844        self
845    }
846
847    /// Checks the configuration, creates the session and pipeline, and registers the node on `host`.
848    /// Creates the image folder's spool folder; nothing else is written until frames are declared.
849    pub fn build(self, host: &CompositionHost) -> Result<ReconNode, ComposeError> {
850        let NodeBuilder {
851            id,
852            plan,
853            policy,
854            backpressure,
855            source,
856            spool,
857            output,
858            attach,
859            frames,
860            deltas,
861            stream_origin,
862            stream_only,
863            prior,
864            prior_error,
865        } = self;
866        let mut pr = Vec::new();
867        let cams = &plan.input.cameras;
868        if cams.is_empty() {
869            pr.push("cameras: empty".to_string());
870        }
871        let mut seen = std::collections::BTreeSet::new();
872        for c in cams {
873            if c.is_empty() || c.contains(['/', '\\']) {
874                pr.push(format!("cameras: invalid name {c:?}"));
875            } else if !seen.insert(c.as_str()) {
876                pr.push(format!("cameras: duplicate {c}"));
877            }
878        }
879        let z = plan.zones;
880        if z.span == 0 {
881            pr.push("zones.span: must be at least 1".into());
882        } else if z.overlap >= z.span {
883            pr.push(format!("zones.overlap: must be smaller than the span ({}), got {}", z.span, z.overlap));
884        }
885        if !plan.input.images.is_dir() {
886            pr.push(format!("images: folder not found: {}", plan.input.images.display()));
887        }
888        if spool.is_absolute() || spool.components().any(|c| matches!(c, std::path::Component::ParentDir)) {
889            pr.push(format!("spool: must be a relative path inside the image folder, got {}", spool.display()));
890        }
891        if plan.sinks.live_stride == 0 {
892            pr.push("live_stride: must be at least 1 (1 = keep all)".into());
893        }
894        if plan.sparse.settle_tol.is_nan() || plan.sparse.settle_tol < 0.0 {
895            pr.push(format!("settle tolerance: must be >= 0, got {}", plan.sparse.settle_tol));
896        }
897        if let ReconcilePolicy::ReplayWindow { positions: 0 } = policy {
898            pr.push("reconcile: replay window must be at least 1 position".into());
899        }
900        match backpressure {
901            Backpressure::Block { max_pending: 0 } | Backpressure::KeepLatest { max_pending: 0 } => {
902                pr.push("backpressure: max_pending must be at least 1".into())
903            }
904            _ => {}
905        }
906        // Intrinsics prior: the builder's, else the plan's file (`sparse.intrinsics_prior`).
907        if let Some(e) = prior_error {
908            pr.push(format!("intrinsics_prior: {e}"));
909        }
910        let prior = match prior {
911            Some(p) => Some(p),
912            None => plan.sparse.intrinsics_prior.as_ref().and_then(|f| {
913                IntrinsicsPrior::load(f, plan.sparse.intrinsics_prior_sigma, plan.sparse.intrinsics_prior_dist_sigma)
914                    .map_err(|e| pr.push(format!("sparse.intrinsics_prior: {e}")))
915                    .ok()
916            }),
917        };
918        if let Some(p) = &prior {
919            match p.validate() {
920                Err(e) => pr.push(format!("intrinsics_prior: {e}")),
921                Ok(()) => {
922                    for n in p.named.keys().filter(|n| !cams.contains(n)) {
923                        pr.push(format!("intrinsics_prior: camera {n:?} is not one of the node's cameras"));
924                    }
925                }
926            }
927        }
928        let sift = make_sift_backend(&plan.features.backend).map_err(|e| pr.push(format!("features.backend: {e}"))).ok();
929        let matcher = make_match_backend(&plan.matching.backend).map_err(|e| pr.push(format!("matching.backend: {e}"))).ok();
930        let ba_backend = make_ba_backend(&plan.sparse.ba_backend).map_err(|e| pr.push(format!("sparse.ba_backend: {e}"))).ok();
931        let sparse = make_sparse_backend(&plan.sparse.backend).map_err(|e| pr.push(format!("sparse.backend: {e}"))).ok();
932        if plan.dense.enabled {
933            if let Err(e) = parse_profile(&plan.dense.profile) {
934                pr.push(format!("dense.profile: {e}"));
935            }
936        }
937        let dense = if plan.dense.enabled { plan.dense.config().map_err(|e| pr.push(format!("dense: {e}"))).ok() } else { None };
938        if !pr.is_empty() {
939            return Err(ComposeError::Config(pr));
940        }
941        if host.node(&id).is_some() {
942            return Err(ComposeError::DuplicateNode(id));
943        }
944
945        let mut sc = SessionConfig::new(plan.input.images.clone());
946        sc.span = z.span;
947        sc.overlap = z.overlap;
948        sc.total_positions = None;
949        sc.incremental_triangulation = plan.sparse.incremental_triangulation;
950        sc.fixed_enu_origin = plan.align.fixed_origin;
951        sc.seed = plan.seed;
952        sc.extraction.sift.max_num_features = plan.features.max_num_features;
953        sc.extraction.reader.max_image_size = plan.features.max_image_size;
954        sc.sift = sift.expect("checked");
955        sc.matcher = Arc::from(matcher.expect("checked"));
956        sc.ba_backend = ba_backend.expect("checked");
957        sc.sparse = sparse.expect("checked");
958        sc.dense = dense;
959        sc.history = match policy {
960            ReconcilePolicy::ReplayWindow { positions } => positions + 1,
961            _ => 0,
962        };
963        sc.decode_frames = frames;
964        sc.stable_display = plan.sparse.stable_display;
965        sc.settle_tol = plan.sparse.settle_tol;
966        sc.settle_max_zone = plan.sparse.settle_max_zone;
967        sc.intrinsics_prior = prior.map(Arc::new);
968        if deltas.as_ref().is_some_and(|o| o.stride == 0) {
969            return Err(ComposeError::Config(vec!["display_deltas: stride must be at least 1".into()]));
970        }
971
972        let origin = Arc::new(Mutex::new(None));
973        let mut pl = Pipeline::new(Session::new(sc));
974        if let Some(opts) = deltas {
975            let mut feed = DisplayFeed::new(opts).with_origin(Arc::clone(&origin));
976            pl = pl.derive(move |e| feed.handle(e).into_iter().collect());
977        }
978        if let Some((dir, opts)) = &output {
979            let io = |e: std::io::Error| ComposeError::Io(format!("{}: {e}", dir.display()));
980            pl = if plan.sparse.stable_display {
981                // Same files as `sinks::attach`, plus the live diff stream (stable display only, as in `Recon::run`).
982                let set = SinkSet {
983                    models: opts.save_models && !stream_only,
984                    zone_ply: !stream_only,
985                    live_files: !stream_only,
986                    live_stride: plan.sinks.live_stride,
987                    live_stream: Some(LiveStream { enu: stream_origin.is_some(), origin_gps: stream_origin }),
988                    ..SinkSet::all()
989                };
990                pl.on_any(DefaultSinks::with_set(dir, opts.echo, set).map_err(io)?.into_hook())
991            } else {
992                sinks::attach(pl, dir, opts).map_err(io)?
993            };
994        }
995        for a in attach {
996            pl = a(pl);
997        }
998        let core = Core {
999            cameras: plan.input.cameras.clone(),
1000            image_root: plan.input.images.clone(),
1001            spool,
1002            policy,
1003            source,
1004            accepted: BTreeMap::new(),
1005            order: Vec::new(),
1006            recent: VecDeque::new(),
1007            waiting: BTreeMap::new(),
1008            stats: ComposeStats::default(),
1009            pipeline: Some(pl),
1010            ended: None,
1011            origin,
1012        };
1013        let node = ReconNode { id, backpressure, core: Arc::new(Mutex::new(core)) };
1014        host.register(&node)?;
1015        Ok(node)
1016    }
1017}
1018
1019// ============================================================================================
1020// Node
1021// ============================================================================================
1022
1023/// A retained reconstruction node: session, pipeline, accepted-frame journal and lifecycle.
1024/// Cheap to clone (shared); all clones address the same node.
1025#[derive(Clone)]
1026pub struct ReconNode {
1027    id: String,
1028    backpressure: Backpressure,
1029    core: Arc<Mutex<Core>>,
1030}
1031
1032impl fmt::Debug for ReconNode {
1033    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1034        f.debug_struct("ReconNode").field("id", &self.id).finish()
1035    }
1036}
1037
1038#[derive(Clone, Copy, Debug)]
1039struct Accepted {
1040    revision: u32,
1041    position: usize,
1042}
1043
1044struct Core {
1045    cameras: Vec<String>,
1046    image_root: PathBuf,
1047    spool: PathBuf,
1048    policy: ReconcilePolicy,
1049    source: Option<String>,
1050    /// sequence -> accepted revision and position.
1051    accepted: BTreeMap<u64, Accepted>,
1052    /// sequence at each position (increasing).
1053    order: Vec<u64>,
1054    /// Resolved sets of the last positions (replay buffer), aligned to the end of `order`.
1055    recent: VecDeque<FrameSet>,
1056    /// Sets being assembled: sequence -> missing cameras.
1057    waiting: BTreeMap<u64, Vec<String>>,
1058    stats: ComposeStats,
1059    pipeline: Option<Pipeline<Session>>,
1060    /// Summary of a node closed by `FrameState::End`, until `close` takes it.
1061    ended: Option<Closed>,
1062    /// First GPS fix declared `[lat, lon, alt]` (ENU origin reported by display deltas).
1063    origin: Arc<Mutex<Option<[f64; 3]>>>,
1064}
1065
1066impl ReconNode {
1067    /// Node id on its host.
1068    pub fn id(&self) -> &str {
1069        &self.id
1070    }
1071
1072    /// Declares the current input state and reconciles it (see the module table).
1073    pub fn compose(&self, state: FrameState) -> Result<Outcome, ComposeError> {
1074        lock(&self.core).compose(state)
1075    }
1076
1077    /// Declares several states in order, stopping at the first error.
1078    pub fn compose_all(&self, states: impl IntoIterator<Item = FrameState>) -> Result<Vec<Outcome>, ComposeError> {
1079        states.into_iter().map(|s| self.compose(s)).collect()
1080    }
1081
1082    /// Collects finished background (refinement) events without new input.
1083    pub fn poll(&self) -> usize {
1084        lock(&self.core).pipeline.as_mut().map_or(0, |p| p.poll())
1085    }
1086
1087    /// Channel receiving every event of this node (see [`Pipeline::subscribe`]). `None` after close.
1088    pub fn subscribe(&self) -> Option<Receiver<Event>> {
1089        lock(&self.core).pipeline.as_ref().map(|p| p.subscribe())
1090    }
1091
1092    /// Reconciliation counters so far.
1093    pub fn stats(&self) -> ComposeStats {
1094        lock(&self.core).stats.clone()
1095    }
1096
1097    /// Positions ingested so far.
1098    pub fn positions(&self) -> usize {
1099        lock(&self.core).order.len()
1100    }
1101
1102    /// Accepted (sequence, revision) per position.
1103    pub fn journal(&self) -> Vec<(u64, u32)> {
1104        let c = lock(&self.core);
1105        c.order.iter().map(|s| (*s, c.accepted[s].revision)).collect()
1106    }
1107
1108    /// Sets currently waiting for cameras: (sequence, missing cameras).
1109    pub fn waiting(&self) -> Vec<(u64, Vec<String>)> {
1110        lock(&self.core).waiting.iter().map(|(k, v)| (*k, v.clone())).collect()
1111    }
1112
1113    /// Read access to the session (e.g. arrived zones, models).
1114    pub fn with_session<T>(&self, f: impl FnOnce(&Session) -> T) -> Option<T> {
1115        lock(&self.core).pipeline.as_ref().map(|p| f(p.reducer()))
1116    }
1117
1118    /// Closes the node: closes open zones, waits for background refinement and emits the final events.
1119    /// The node stays listed on its host; [`CompositionHost::close`] also removes it.
1120    pub fn close(&self) -> Result<Closed, ComposeError> {
1121        self.close_inner()
1122    }
1123
1124    fn close_inner(&self) -> Result<Closed, ComposeError> {
1125        let mut c = lock(&self.core);
1126        if let Some(done) = c.ended.take() {
1127            return Ok(done);
1128        }
1129        c.finish().ok_or(ComposeError::Closed)
1130    }
1131
1132    /// Moves the node onto its own thread behind a queue with the builder's [`Backpressure`] policy.
1133    /// The node stays registered on its host; composing on it directly while spawned is serialized with the worker.
1134    pub fn spawn(&self) -> ComposeHandle {
1135        let queue = Arc::new(Queue { st: Mutex::new(QueueState::default()), cv: Condvar::new() });
1136        let (q, node) = (Arc::clone(&queue), self.clone());
1137        let worker = std::thread::Builder::new()
1138            .name(format!("compose-{}", self.id))
1139            .spawn(move || {
1140                let mut outcomes = Vec::new();
1141                loop {
1142                    let next = {
1143                        let mut st = lock(&q.st);
1144                        loop {
1145                            if let Some(s) = st.items.pop_front() {
1146                                q.cv.notify_all();
1147                                break Some(s);
1148                            }
1149                            if st.closed {
1150                                break None;
1151                            }
1152                            st = q.cv.wait(st).unwrap_or_else(|p| p.into_inner());
1153                        }
1154                    };
1155                    let Some(state) = next else { break };
1156                    let end = matches!(state, FrameState::End);
1157                    let r = node.compose(state);
1158                    lock(&q.st).processed += 1;
1159                    let fatal = matches!(r, Err(ComposeError::Session(_)));
1160                    outcomes.push(r);
1161                    if end || fatal {
1162                        break;
1163                    }
1164                }
1165                let mut st = lock(&q.st);
1166                st.closed = true;
1167                st.items.clear();
1168                q.cv.notify_all();
1169                outcomes
1170            })
1171            .expect("compose worker thread");
1172        ComposeHandle { node: self.clone(), queue, policy: self.backpressure, worker: Some(worker) }
1173    }
1174}
1175
1176impl Core {
1177    fn pl(&mut self) -> &mut Pipeline<Session> {
1178        self.pipeline.as_mut().expect("open pipeline")
1179    }
1180
1181    fn warn(&mut self, message: String) {
1182        if let Some(p) = self.pipeline.as_mut() {
1183            p.reducer().emit_external(|meta| Event::Warning { meta, message });
1184            p.poll();
1185        }
1186    }
1187
1188    fn ignore(&mut self, key: &FrameKey, reason: IgnoreReason) -> Result<Outcome, ComposeError> {
1189        if self.policy == ReconcilePolicy::Strict && reason != IgnoreReason::Closed {
1190            return Err(ComposeError::Rejected(format!("{key}: {reason}")));
1191        }
1192        self.stats.ignored += 1;
1193        self.warn(format!("compose: {key} ignored: {reason}"));
1194        Ok(Outcome::Ignored(reason))
1195    }
1196
1197    fn compose(&mut self, state: FrameState) -> Result<Outcome, ComposeError> {
1198        self.stats.declared += 1;
1199        if self.pipeline.is_none() {
1200            return match state {
1201                FrameState::End => Ok(Outcome::Ended),
1202                _ => Ok(Outcome::Ignored(IgnoreReason::Closed)),
1203            };
1204        }
1205        match state {
1206            FrameState::End => {
1207                let done = self.finish().ok_or(ComposeError::Closed)?;
1208                self.ended = Some(done);
1209                Ok(Outcome::Ended)
1210            }
1211            FrameState::Pending { key, missing_cameras, .. } => {
1212                if let Some(r) = self.check_source(&key) {
1213                    return r;
1214                }
1215                self.stats.waiting += 1;
1216                if !self.accepted.contains_key(&key.sequence) {
1217                    self.waiting.insert(key.sequence, missing_cameras.clone());
1218                }
1219                Ok(Outcome::Waiting { missing: missing_cameras })
1220            }
1221            FrameState::Ready(set) => self.ready(set),
1222        }
1223    }
1224
1225    fn check_source(&mut self, key: &FrameKey) -> Option<Result<Outcome, ComposeError>> {
1226        match &self.source {
1227            None => {
1228                self.source = Some(key.source_id.clone());
1229                None
1230            }
1231            Some(s) if *s == key.source_id => None,
1232            Some(s) => {
1233                let expected = s.clone();
1234                Some(self.ignore(key, IgnoreReason::ForeignSource { expected }))
1235            }
1236        }
1237    }
1238
1239    fn ready(&mut self, set: LiveFrameSet) -> Result<Outcome, ComposeError> {
1240        let key = set.key.clone();
1241        // Shape checks first: a malformed set is an error under every policy.
1242        let mut by_cam: HashMap<&str, &LiveImage> = HashMap::new();
1243        for im in &set.images {
1244            if !self.cameras.contains(&im.camera) {
1245                return Err(ComposeError::InvalidFrameSet(format!("{key}: unknown camera {}", im.camera)));
1246            }
1247            if by_cam.insert(im.camera.as_str(), im).is_some() {
1248                return Err(ComposeError::InvalidFrameSet(format!("{key}: camera {} given twice", im.camera)));
1249            }
1250        }
1251        if let Some(r) = self.check_source(&key) {
1252            return r;
1253        }
1254        let missing: Vec<String> = self.cameras.iter().filter(|c| !by_cam.contains_key(c.as_str())).cloned().collect();
1255        if !missing.is_empty() && !self.accepted.contains_key(&key.sequence) {
1256            self.stats.waiting += 1;
1257            self.waiting.insert(key.sequence, missing.clone());
1258            return Ok(Outcome::Waiting { missing });
1259        }
1260
1261        if let Some(acc) = self.accepted.get(&key.sequence).copied() {
1262            if key.revision == acc.revision {
1263                self.stats.duplicates += 1;
1264                return Ok(Outcome::Duplicate { position: acc.position });
1265            }
1266            if key.revision < acc.revision {
1267                return self.ignore(&key, IgnoreReason::StaleRevision { accepted: acc.revision });
1268            }
1269            if !missing.is_empty() {
1270                return Err(ComposeError::InvalidFrameSet(format!("{key}: correction misses cameras {}", missing.join(", "))));
1271            }
1272            return self.correct(set, acc);
1273        }
1274
1275        let newest = self.order.last().copied();
1276        match newest {
1277            Some(n) if key.sequence < n => self.late(set),
1278            _ => {
1279                let skipped = newest.map_or(0, |n| key.sequence - n - 1);
1280                if skipped > 0 && self.policy == ReconcilePolicy::Strict {
1281                    return Err(ComposeError::Rejected(format!("{key}: {skipped} sequence(s) missing before it")));
1282                }
1283                let fs = self.resolve(&set, None)?;
1284                self.waiting.remove(&key.sequence);
1285                let position = self.order.len();
1286                self.push(fs)?;
1287                self.order.push(key.sequence);
1288                self.accepted.insert(key.sequence, Accepted { revision: key.revision, position });
1289                self.stats.appended += 1;
1290                if skipped > 0 {
1291                    self.stats.skipped_sequences += skipped;
1292                    self.warn(format!("compose: {key} appended at position {position} after {skipped} missing sequence(s)"));
1293                }
1294                Ok(Outcome::Appended { position, skipped })
1295            }
1296        }
1297    }
1298
1299    /// Late arrival of an unseen older sequence.
1300    fn late(&mut self, set: LiveFrameSet) -> Result<Outcome, ComposeError> {
1301        let key = set.key.clone();
1302        let ReconcilePolicy::ReplayWindow { positions: w } = self.policy else {
1303            return self.ignore(&key, IgnoreReason::Late);
1304        };
1305        let p = self.order.partition_point(|&s| s < key.sequence);
1306        if !self.in_window(p, w) {
1307            return self.ignore(&key, IgnoreReason::OutsideReplayWindow { position: p });
1308        }
1309        let fs = self.resolve(&set, None)?;
1310        let tail_sets: Vec<FrameSet> = self.recent.iter().skip(self.recent.len() - (self.order.len() - p)).cloned().collect();
1311        let mut tail = vec![fs];
1312        tail.extend(tail_sets);
1313        let mut seqs = vec![key.sequence];
1314        seqs.extend(self.order[p..].iter().copied());
1315        self.waiting.remove(&key.sequence);
1316        let n = self.replay(p, tail, &seqs, (key.sequence, key.revision))?;
1317        self.warn(format!("compose: late {key} inserted at position {p}, replayed {n} position(s)"));
1318        Ok(Outcome::Replayed { from: p, positions: n })
1319    }
1320
1321    /// Higher revision of an accepted sequence.
1322    fn correct(&mut self, set: LiveFrameSet, acc: Accepted) -> Result<Outcome, ComposeError> {
1323        let key = set.key.clone();
1324        let p = acc.position;
1325        match self.policy {
1326            ReconcilePolicy::AppendOnly | ReconcilePolicy::Strict => self.ignore(&key, IgnoreReason::CorrectionNotApplied),
1327            ReconcilePolicy::ReplayWindow { positions: w } => {
1328                if !self.in_window(p, w) {
1329                    return self.ignore(&key, IgnoreReason::OutsideReplayWindow { position: p });
1330                }
1331                let fs = self.resolve(&set, None)?;
1332                let start = self.recent.len() - (self.order.len() - p);
1333                let mut tail: Vec<FrameSet> = self.recent.iter().skip(start).cloned().collect();
1334                tail[0] = fs;
1335                let seqs: Vec<u64> = self.order[p..].to_vec();
1336                let n = self.replay(p, tail, &seqs, (key.sequence, key.revision))?;
1337                self.warn(format!("compose: correction {key} applied from position {p}, replayed {n} position(s)"));
1338                Ok(Outcome::Replayed { from: p, positions: n })
1339            }
1340            ReconcilePolicy::InvalidateAffectedZones => {
1341                // Store the corrected pixels under the original names so rebuilt outputs read them.
1342                let names: Vec<String> = self.pl().reducer().frames()[p].iter().map(|f| f.name.clone()).collect();
1343                self.resolve(&set, Some(&names))?;
1344                let zones: Vec<usize> =
1345                    self.pl().reducer().arrived_zones().into_iter().filter(|z| z.lo <= p && p < z.hi).map(|z| z.zone).collect();
1346                for &z in &zones {
1347                    self.pl().command(Command::InvalidateZone(z));
1348                }
1349                self.fail_check()?;
1350                self.accepted.insert(key.sequence, Accepted { revision: key.revision, position: p });
1351                self.stats.invalidations += 1;
1352                Ok(Outcome::Invalidated { position: p, zones })
1353            }
1354        }
1355    }
1356
1357    /// Whether position `p` can be rewound to with window `w`.
1358    fn in_window(&self, p: usize, w: usize) -> bool {
1359        let npos = self.order.len();
1360        npos - p <= w && npos - p <= self.recent.len()
1361    }
1362
1363    /// Rewinds to `p` and pushes `tail` (sequences `seqs`), updating the journal and the replay buffer.
1364    /// `changed` = the (sequence, revision) that differs from the journal (corrected or inserted set).
1365    fn replay(&mut self, p: usize, tail: Vec<FrameSet>, seqs: &[u64], changed: (u64, u32)) -> Result<usize, ComposeError> {
1366        let npos = self.order.len();
1367        self.pl().command(Command::ResetFrom(p));
1368        if self.pl().reducer().positions() != p {
1369            return Err(ComposeError::Session(format!("rewind to position {p} was refused by the session")));
1370        }
1371        let revs: HashMap<u64, u32> = self.order[p..].iter().map(|s| (*s, self.accepted[s].revision)).collect();
1372        for s in &self.order[p..] {
1373            self.accepted.remove(s);
1374        }
1375        self.order.truncate(p);
1376        let keep = self.recent.len() - (npos - p);
1377        self.recent.truncate(keep);
1378        let n = tail.len();
1379        for (fs, &seq) in tail.into_iter().zip(seqs) {
1380            let revision = if seq == changed.0 { changed.1 } else { revs[&seq] };
1381            let position = self.order.len();
1382            self.push(fs)?;
1383            self.order.push(seq);
1384            self.accepted.insert(seq, Accepted { revision, position });
1385        }
1386        self.stats.replays += 1;
1387        self.stats.replayed_positions += n as u64;
1388        Ok(n)
1389    }
1390
1391    /// Pushes one resolved set and keeps it in the replay buffer.
1392    fn push(&mut self, fs: FrameSet) -> Result<(), ComposeError> {
1393        let cap = match self.policy {
1394            ReconcilePolicy::ReplayWindow { positions } => positions,
1395            _ => 0,
1396        };
1397        if cap > 0 {
1398            self.recent.push_back(fs.clone());
1399            while self.recent.len() > cap {
1400                self.recent.pop_front();
1401            }
1402        }
1403        if let Some(g) = fs.gps.first() {
1404            lock(&self.origin).get_or_insert([g.lat, g.lon, g.alt]);
1405        }
1406        self.pl().push(Input::Frames(fs));
1407        self.fail_check()
1408    }
1409
1410    fn fail_check(&mut self) -> Result<(), ComposeError> {
1411        match self.pl().reducer().failed() {
1412            Some(e) => Err(ComposeError::Session(e.to_string())),
1413            None => Ok(()),
1414        }
1415    }
1416
1417    /// Materializes payloads (spooling in-memory ones) and builds the session's frame set in camera order.
1418    /// `names` forces the stored names (corrections under `InvalidateAffectedZones`).
1419    fn resolve(&self, set: &LiveFrameSet, names: Option<&[String]>) -> Result<FrameSet, ComposeError> {
1420        let key = &set.key;
1421        let mut fs = FrameSet::default();
1422        for (i, cam) in self.cameras.iter().enumerate() {
1423            let im = set.images.iter().find(|x| &x.camera == cam).expect("complete set");
1424            let forced = names.map(|n| n[i].clone());
1425            let name = match &im.payload {
1426                FramePayload::File { relative_name } => {
1427                    let src = self.image_root.join(relative_name);
1428                    if !src.is_file() {
1429                        return Err(ComposeError::InvalidFrameSet(format!("{key}: file not found: {}", src.display())));
1430                    }
1431                    match forced {
1432                        Some(n) if n != *relative_name => {
1433                            let bytes = std::fs::read(&src).map_err(|e| ComposeError::Io(format!("{}: {e}", src.display())))?;
1434                            self.store_encoded(&n, &bytes, ext_of(relative_name))?;
1435                            n
1436                        }
1437                        _ => relative_name.clone(),
1438                    }
1439                }
1440                FramePayload::Rgb8 { width, height, pixels } => {
1441                    if pixels.len() != *width as usize * *height as usize * 3 || *width == 0 || *height == 0 {
1442                        return Err(ComposeError::InvalidFrameSet(format!(
1443                            "{key}: camera {cam}: {} bytes for {width}x{height} RGB8",
1444                            pixels.len()
1445                        )));
1446                    }
1447                    let n = forced.unwrap_or_else(|| self.spool_name(key, cam, "png"));
1448                    let img = image::RgbImage::from_raw(*width, *height, pixels.to_vec()).expect("size checked");
1449                    self.store_image(&n, &image::DynamicImage::ImageRgb8(img))?;
1450                    n
1451                }
1452                FramePayload::Encoded { bytes, format } => {
1453                    let n = forced.unwrap_or_else(|| self.spool_name(key, cam, format.extension()));
1454                    self.store_encoded(&n, bytes, Some(format.extension()))?;
1455                    n
1456                }
1457            };
1458            fs.images.push(crate::session::FrameImage { camera: cam.clone(), name });
1459        }
1460        for g in &set.gps {
1461            let mut g = g.clone();
1462            if let Some(i) = self.cameras.iter().position(|c| *c == g.name) {
1463                g.name = fs.images[i].name.clone();
1464            }
1465            fs.gps.push(g);
1466        }
1467        Ok(fs)
1468    }
1469
1470    fn spool_name(&self, key: &FrameKey, cam: &str, ext: &str) -> String {
1471        let src: String = key.source_id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
1472        let p = self.spool.join(cam).join(format!("{src}_{:010}.{ext}", key.sequence));
1473        p.to_string_lossy().replace('\\', "/")
1474    }
1475
1476    /// Writes encoded bytes to `name`; re-encodes when the target extension differs from the bytes' format.
1477    fn store_encoded(&self, name: &str, bytes: &[u8], ext: Option<&str>) -> Result<(), ComposeError> {
1478        if ext.is_some() && ext == ext_of(name) {
1479            return self.atomic_write(name, |path| std::fs::write(path, bytes).map_err(|e| e.to_string()));
1480        }
1481        let img = image::load_from_memory(bytes).map_err(|e| ComposeError::InvalidFrameSet(format!("{name}: {e}")))?;
1482        self.store_image(name, &img)
1483    }
1484
1485    fn store_image(&self, name: &str, img: &image::DynamicImage) -> Result<(), ComposeError> {
1486        let fmt = image::ImageFormat::from_path(name).map_err(|e| ComposeError::Io(format!("{name}: {e}")))?;
1487        self.atomic_write(name, |path| img.save_with_format(path, fmt).map_err(|e| e.to_string()))
1488    }
1489
1490    /// Writes through a temporary file in the same folder and renames, so readers never see a partial image.
1491    fn atomic_write(&self, name: &str, write: impl FnOnce(&Path) -> Result<(), String>) -> Result<(), ComposeError> {
1492        let dst = self.image_root.join(name);
1493        let dir = dst.parent().unwrap_or(&self.image_root);
1494        std::fs::create_dir_all(dir).map_err(|e| ComposeError::Io(format!("{}: {e}", dir.display())))?;
1495        let file = dst.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
1496        let ext = ext_of(name).unwrap_or("tmp");
1497        let tmp = dir.join(format!(".{file}.partial.{ext}"));
1498        write(&tmp).map_err(|e| ComposeError::Io(format!("{}: {e}", tmp.display())))?;
1499        std::fs::rename(&tmp, &dst).map_err(|e| ComposeError::Io(format!("{}: {e}", dst.display())))
1500    }
1501
1502    fn finish(&mut self) -> Option<Closed> {
1503        let pl = self.pipeline.take()?;
1504        let (session, summary) = pl.finish();
1505        Some(Closed { session, summary, stats: self.stats.clone() })
1506    }
1507}
1508
1509fn ext_of(name: &str) -> Option<&str> {
1510    Path::new(name).extension().and_then(|e| e.to_str())
1511}
1512
1513fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
1514    m.lock().unwrap_or_else(|p| p.into_inner())
1515}
1516
1517// ============================================================================================
1518// Spawned node
1519// ============================================================================================
1520
1521#[derive(Default)]
1522struct QueueState {
1523    items: VecDeque<FrameState>,
1524    closed: bool,
1525    submitted: u64,
1526    dropped: u64,
1527    processed: u64,
1528    max_depth: usize,
1529}
1530
1531struct Queue {
1532    st: Mutex<QueueState>,
1533    cv: Condvar,
1534}
1535
1536/// Why a state could not be queued.
1537#[derive(Debug)]
1538pub enum SendError {
1539    /// `try_send` under `Block`: the queue is full. The state is handed back.
1540    Full(FrameState),
1541    /// The worker stopped (closed, or the session failed). The state is handed back.
1542    Closed(FrameState),
1543}
1544
1545impl fmt::Display for SendError {
1546    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1547        match self {
1548            SendError::Full(_) => write!(f, "compose queue full"),
1549            SendError::Closed(_) => write!(f, "compose worker stopped"),
1550        }
1551    }
1552}
1553
1554impl std::error::Error for SendError {}
1555
1556/// Queue counters of a spawned node.
1557#[derive(Clone, Debug, Default, PartialEq, Eq)]
1558pub struct QueueStats {
1559    /// States accepted into the queue.
1560    pub submitted: u64,
1561    /// Ready sets dropped by `KeepLatest`.
1562    pub dropped: u64,
1563    /// States composed by the worker.
1564    pub processed: u64,
1565    /// Current queue depth.
1566    pub depth: usize,
1567    /// Largest queue depth seen.
1568    pub max_depth: usize,
1569}
1570
1571/// Producer side of a spawned node ([`ReconNode::spawn`]).
1572pub struct ComposeHandle {
1573    node: ReconNode,
1574    queue: Arc<Queue>,
1575    policy: Backpressure,
1576    worker: Option<JoinHandle<Vec<Result<Outcome, ComposeError>>>>,
1577}
1578
1579impl fmt::Debug for ComposeHandle {
1580    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1581        f.debug_struct("ComposeHandle").field("node", &self.node.id).field("policy", &self.policy).field("stats", &self.stats()).finish()
1582    }
1583}
1584
1585impl ComposeHandle {
1586    /// The node.
1587    pub fn node(&self) -> &ReconNode {
1588        &self.node
1589    }
1590
1591    /// Queues a state. Under `Block` waits for room; never waits otherwise.
1592    pub fn send(&self, state: FrameState) -> Result<(), SendError> {
1593        self.enqueue(state, true)
1594    }
1595
1596    /// Queues a state without waiting (`Block` returns [`SendError::Full`] when full).
1597    pub fn try_send(&self, state: FrameState) -> Result<(), SendError> {
1598        self.enqueue(state, false)
1599    }
1600
1601    /// Queues every state of a source (iterator, channel receiver, ...) with [`ComposeHandle::send`].
1602    pub fn send_all(&self, states: impl IntoIterator<Item = FrameState>) -> Result<(), SendError> {
1603        states.into_iter().try_for_each(|s| self.send(s))
1604    }
1605
1606    fn enqueue(&self, state: FrameState, wait: bool) -> Result<(), SendError> {
1607        let q = &self.queue;
1608        let mut st = lock(&q.st);
1609        if st.closed {
1610            return Err(SendError::Closed(state));
1611        }
1612        // End is never dropped or refused for room.
1613        let end = matches!(state, FrameState::End);
1614        match self.policy {
1615            Backpressure::Unbounded => {}
1616            Backpressure::Block { max_pending } => {
1617                while !end && st.items.len() >= max_pending && !st.closed {
1618                    if !wait {
1619                        return Err(SendError::Full(state));
1620                    }
1621                    st = q.cv.wait(st).unwrap_or_else(|p| p.into_inner());
1622                }
1623                if st.closed {
1624                    return Err(SendError::Closed(state));
1625                }
1626            }
1627            Backpressure::KeepLatest { max_pending } => {
1628                while !end && st.items.len() >= max_pending {
1629                    match st.items.iter().position(|s| matches!(s, FrameState::Ready(_))) {
1630                        Some(i) => {
1631                            st.items.remove(i);
1632                            st.dropped += 1;
1633                        }
1634                        None => {
1635                            st.items.pop_front();
1636                        }
1637                    }
1638                }
1639            }
1640        }
1641        st.items.push_back(state);
1642        st.submitted += 1;
1643        st.max_depth = st.max_depth.max(st.items.len());
1644        q.cv.notify_all();
1645        Ok(())
1646    }
1647
1648    /// Queue counters.
1649    pub fn stats(&self) -> QueueStats {
1650        let st = lock(&self.queue.st);
1651        QueueStats { submitted: st.submitted, dropped: st.dropped, processed: st.processed, depth: st.items.len(), max_depth: st.max_depth }
1652    }
1653
1654    /// Sends `End`, waits for the worker to compose everything queued, and closes the node.
1655    /// Returns the per-state outcomes (in queue order) and the close result.
1656    pub fn close(mut self) -> (Vec<Result<Outcome, ComposeError>>, Result<Closed, ComposeError>) {
1657        let _ = self.enqueue(FrameState::End, false);
1658        let outcomes = self.worker.take().map(|w| w.join().unwrap_or_default()).unwrap_or_default();
1659        (outcomes, self.node.close_inner())
1660    }
1661}
1662
1663impl Drop for ComposeHandle {
1664    fn drop(&mut self) {
1665        if let Some(w) = self.worker.take() {
1666            {
1667                let mut st = lock(&self.queue.st);
1668                st.closed = true;
1669                self.queue.cv.notify_all();
1670            }
1671            let _ = w.join();
1672        }
1673    }
1674}
1675
1676#[cfg(test)]
1677mod tests {
1678    use super::*;
1679
1680    #[test]
1681    fn spool_names_are_sanitized_and_stable() {
1682        let c = Core {
1683            cameras: vec!["camF".into()],
1684            image_root: PathBuf::from("/tmp/x"),
1685            spool: PathBuf::from(".live"),
1686            policy: ReconcilePolicy::AppendOnly,
1687            source: None,
1688            accepted: BTreeMap::new(),
1689            order: Vec::new(),
1690            recent: VecDeque::new(),
1691            waiting: BTreeMap::new(),
1692            stats: ComposeStats::default(),
1693            pipeline: None,
1694            ended: None,
1695            origin: Arc::new(Mutex::new(None)),
1696        };
1697        let k = FrameKey::new("rtsp://drone 1", 42, 3);
1698        assert_eq!(c.spool_name(&k, "camF", "png"), ".live/camF/rtsp___drone_1_0000000042.png");
1699    }
1700
1701    #[test]
1702    fn key_display() {
1703        assert_eq!(FrameKey::new("d", 7, 1).to_string(), "d#7r1");
1704    }
1705}