Skip to main content

oximedia_align/
lib.rs

1//! Video alignment and registration tools for multi-camera synchronization in `OxiMedia`.
2//!
3//! This crate provides comprehensive tools for aligning and registering video from multiple cameras:
4//!
5//! # Temporal Alignment
6//!
7//! The [`temporal`] module provides time-based synchronization:
8//!
9//! - **Audio Cross-Correlation** - Sync cameras using audio tracks
10//! - **Timecode Synchronization** - LTC/VITC-based alignment
11//! - **Visual Markers** - Clapper detection and flash-based sync
12//! - **Sub-frame Accuracy** - Precise timing down to microseconds
13//!
14//! # Spatial Registration
15//!
16//! The [`spatial`] module provides geometric alignment:
17//!
18//! - **Homography Estimation** - Planar perspective transformation
19//! - **Perspective Correction** - Remove keystone distortion
20//! - **Feature Matching** - Correspond points between views
21//! - **RANSAC** - Robust outlier rejection
22//!
23//! # Feature Detection
24//!
25//! The [`features`] module provides patent-free feature detection and matching:
26//!
27//! - **FAST Corners** - High-speed corner detection
28//! - **BRIEF Descriptors** - Binary robust independent elementary features
29//! - **ORB Features** - Oriented FAST and Rotated BRIEF
30//! - **Brute-Force Matching** - Hamming distance matching
31//!
32//! # Lens Distortion
33//!
34//! The [`distortion`] module corrects lens aberrations:
35//!
36//! - **Brown-Conrady Model** - Radial and tangential distortion
37//! - **Fisheye Model** - Wide-angle lens correction
38//! - **Calibration** - Camera intrinsic parameter estimation
39//! - **Undistortion** - Real-time image correction
40//!
41//! # Color Matching
42//!
43//! The [`color`] module matches color across cameras:
44//!
45//! - **Color Transfer** - Match color distributions
46//! - **Histogram Matching** - Equalize color histograms
47//! - **White Balance** - Illuminant estimation
48//! - **Color Calibration** - ColorChecker-based calibration
49//!
50//! # Sync Markers
51//!
52//! The [`markers`] module detects synchronization markers:
53//!
54//! - **Clapper Detection** - Automatic slate detection
55//! - **Flash Detection** - Bright flash sync
56//! - **LED Markers** - Coded light patterns
57//! - **Audio Spike** - Sharp transient detection
58//!
59//! # Rolling Shutter
60//!
61//! The [`rolling_shutter`] module corrects rolling shutter artifacts:
62//!
63//! - **Motion Estimation** - Per-scanline motion vectors
64//! - **Correction** - Remove wobble and skew
65//! - **Global Shutter Simulation** - Temporal interpolation
66//!
67//! # Example: Audio-Based Sync
68//!
69//! ```
70//! use oximedia_align::temporal::{AudioSync, SyncConfig};
71//! use oximedia_align::AlignResult;
72//!
73//! # fn example() -> AlignResult<()> {
74//! // Configure audio synchronization
75//! let config = SyncConfig {
76//!     sample_rate: 48000,
77//!     window_size: 480000, // 10 seconds
78//!     max_offset: 240000,  // ±5 seconds
79//! };
80//!
81//! // Create audio sync analyzer
82//! let sync = AudioSync::new(config);
83//!
84//! // Find offset between two audio tracks
85//! // let offset = sync.find_offset(&audio1, &audio2)?;
86//! # Ok(())
87//! # }
88//! ```
89//!
90//! # Example: Homography Estimation
91//!
92//! ```
93//! use oximedia_align::spatial::{HomographyEstimator, RansacConfig};
94//! use oximedia_align::features::{FeatureMatcher, MatchPair};
95//!
96//! # fn example() -> oximedia_align::AlignResult<()> {
97//! // Configure RANSAC for robust estimation
98//! let config = RansacConfig {
99//!     threshold: 3.0,
100//!     max_iterations: 1000,
101//!     min_inliers: 8,
102//! };
103//!
104//! let estimator = HomographyEstimator::new(config);
105//!
106//! // Estimate homography from matched points
107//! // let (homography, inliers) = estimator.estimate(&matches)?;
108//! # Ok(())
109//! # }
110//! ```
111
112#![forbid(unsafe_code)]
113#![warn(missing_docs)]
114
115pub mod affine;
116pub mod align_report;
117pub mod audio_align;
118pub mod beat_align;
119pub mod color;
120pub mod confidence_map;
121pub mod distortion;
122pub mod drift_correct;
123pub mod drift_correction;
124pub mod elastic_align;
125pub mod farneback_flow;
126pub mod features;
127pub mod frame_matcher;
128pub mod frequency_align;
129pub mod gradient_flow;
130pub mod icp;
131pub mod klt_tracker;
132pub mod lip_sync;
133pub mod markers;
134pub mod motion_compensate;
135pub mod multi_stream;
136pub mod multicam_sync;
137pub mod multitrack_align;
138pub mod optical_flow;
139pub mod phase_correlate;
140pub mod projective_warp;
141pub mod prosac;
142pub mod rigid_transform;
143pub mod rolling_shutter;
144pub mod spatial;
145pub mod stabilize;
146pub mod stereo_depth;
147pub mod stereo_rectify;
148pub mod subframe_interp;
149pub mod sync_score;
150pub mod tempo_align;
151pub mod temporal;
152pub mod temporal_align;
153pub mod transform;
154pub mod warp;
155
156use thiserror::Error;
157
158/// Result type for alignment operations
159pub type AlignResult<T> = Result<T, AlignError>;
160
161/// Errors that can occur during alignment operations
162#[derive(Debug, Error)]
163pub enum AlignError {
164    /// Insufficient data for alignment
165    #[error("Insufficient data: {0}")]
166    InsufficientData(String),
167
168    /// Invalid configuration parameter
169    #[error("Invalid configuration: {0}")]
170    InvalidConfig(String),
171
172    /// No solution found
173    #[error("No solution found: {0}")]
174    NoSolution(String),
175
176    /// Numerical instability
177    #[error("Numerical instability: {0}")]
178    NumericalError(String),
179
180    /// Feature detection failed
181    #[error("Feature detection failed: {0}")]
182    FeatureError(String),
183
184    /// Matching failed
185    #[error("Matching failed: {0}")]
186    MatchingError(String),
187
188    /// Estimation failed
189    #[error("Estimation failed: {0}")]
190    EstimationError(String),
191
192    /// Synchronization failed
193    #[error("Synchronization failed: {0}")]
194    SyncError(String),
195
196    /// Color correction failed
197    #[error("Color correction failed: {0}")]
198    ColorError(String),
199
200    /// Distortion correction failed
201    #[error("Distortion correction failed: {0}")]
202    DistortionError(String),
203
204    /// Rolling shutter correction failed
205    #[error("Rolling shutter correction failed: {0}")]
206    RollingShutterError(String),
207
208    /// Generic error from core
209    #[error("Core error: {0}")]
210    Core(#[from] oximedia_core::error::OxiError),
211}
212
213/// 2D point
214#[derive(Debug, Clone, Copy, PartialEq)]
215pub struct Point2D {
216    /// X coordinate
217    pub x: f64,
218    /// Y coordinate
219    pub y: f64,
220}
221
222impl Point2D {
223    /// Create a new 2D point
224    #[must_use]
225    pub fn new(x: f64, y: f64) -> Self {
226        Self { x, y }
227    }
228
229    /// Compute Euclidean distance to another point
230    #[must_use]
231    pub fn distance(&self, other: &Self) -> f64 {
232        let dx = self.x - other.x;
233        let dy = self.y - other.y;
234        (dx * dx + dy * dy).sqrt()
235    }
236
237    /// Compute squared distance (faster than distance)
238    #[must_use]
239    pub fn distance_squared(&self, other: &Self) -> f64 {
240        let dx = self.x - other.x;
241        let dy = self.y - other.y;
242        dx * dx + dy * dy
243    }
244}
245
246/// Time offset between two streams
247#[derive(Debug, Clone, Copy, PartialEq)]
248pub struct TimeOffset {
249    /// Offset in samples (for audio) or frames (for video)
250    pub samples: i64,
251    /// Confidence score (0.0 to 1.0)
252    pub confidence: f64,
253    /// Cross-correlation peak value
254    pub correlation: f64,
255}
256
257impl TimeOffset {
258    /// Create a new time offset
259    #[must_use]
260    pub fn new(samples: i64, confidence: f64, correlation: f64) -> Self {
261        Self {
262            samples,
263            confidence,
264            correlation,
265        }
266    }
267
268    /// Convert offset to seconds
269    #[must_use]
270    pub fn to_seconds(&self, sample_rate: u32) -> f64 {
271        self.samples as f64 / f64::from(sample_rate)
272    }
273
274    /// Convert offset to milliseconds
275    #[must_use]
276    pub fn to_milliseconds(&self, sample_rate: u32) -> f64 {
277        self.to_seconds(sample_rate) * 1000.0
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    #[test]
286    fn test_point2d_distance() {
287        let p1 = Point2D::new(0.0, 0.0);
288        let p2 = Point2D::new(3.0, 4.0);
289        assert!((p1.distance(&p2) - 5.0).abs() < f64::EPSILON);
290        assert!((p1.distance_squared(&p2) - 25.0).abs() < f64::EPSILON);
291    }
292
293    #[test]
294    fn test_time_offset_conversion() {
295        let offset = TimeOffset::new(48000, 0.95, 0.85);
296        assert!((offset.to_seconds(48000) - 1.0).abs() < f64::EPSILON);
297        assert!((offset.to_milliseconds(48000) - 1000.0).abs() < f64::EPSILON);
298    }
299}