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_rectify;
147pub mod subframe_interp;
148pub mod sync_score;
149pub mod tempo_align;
150pub mod temporal;
151pub mod temporal_align;
152pub mod transform;
153pub mod warp;
154
155use thiserror::Error;
156
157/// Result type for alignment operations
158pub type AlignResult<T> = Result<T, AlignError>;
159
160/// Errors that can occur during alignment operations
161#[derive(Debug, Error)]
162pub enum AlignError {
163 /// Insufficient data for alignment
164 #[error("Insufficient data: {0}")]
165 InsufficientData(String),
166
167 /// Invalid configuration parameter
168 #[error("Invalid configuration: {0}")]
169 InvalidConfig(String),
170
171 /// No solution found
172 #[error("No solution found: {0}")]
173 NoSolution(String),
174
175 /// Numerical instability
176 #[error("Numerical instability: {0}")]
177 NumericalError(String),
178
179 /// Feature detection failed
180 #[error("Feature detection failed: {0}")]
181 FeatureError(String),
182
183 /// Matching failed
184 #[error("Matching failed: {0}")]
185 MatchingError(String),
186
187 /// Estimation failed
188 #[error("Estimation failed: {0}")]
189 EstimationError(String),
190
191 /// Synchronization failed
192 #[error("Synchronization failed: {0}")]
193 SyncError(String),
194
195 /// Color correction failed
196 #[error("Color correction failed: {0}")]
197 ColorError(String),
198
199 /// Distortion correction failed
200 #[error("Distortion correction failed: {0}")]
201 DistortionError(String),
202
203 /// Rolling shutter correction failed
204 #[error("Rolling shutter correction failed: {0}")]
205 RollingShutterError(String),
206
207 /// Generic error from core
208 #[error("Core error: {0}")]
209 Core(#[from] oximedia_core::error::OxiError),
210}
211
212/// 2D point
213#[derive(Debug, Clone, Copy, PartialEq)]
214pub struct Point2D {
215 /// X coordinate
216 pub x: f64,
217 /// Y coordinate
218 pub y: f64,
219}
220
221impl Point2D {
222 /// Create a new 2D point
223 #[must_use]
224 pub fn new(x: f64, y: f64) -> Self {
225 Self { x, y }
226 }
227
228 /// Compute Euclidean distance to another point
229 #[must_use]
230 pub fn distance(&self, other: &Self) -> f64 {
231 let dx = self.x - other.x;
232 let dy = self.y - other.y;
233 (dx * dx + dy * dy).sqrt()
234 }
235
236 /// Compute squared distance (faster than distance)
237 #[must_use]
238 pub fn distance_squared(&self, other: &Self) -> f64 {
239 let dx = self.x - other.x;
240 let dy = self.y - other.y;
241 dx * dx + dy * dy
242 }
243}
244
245/// Time offset between two streams
246#[derive(Debug, Clone, Copy, PartialEq)]
247pub struct TimeOffset {
248 /// Offset in samples (for audio) or frames (for video)
249 pub samples: i64,
250 /// Confidence score (0.0 to 1.0)
251 pub confidence: f64,
252 /// Cross-correlation peak value
253 pub correlation: f64,
254}
255
256impl TimeOffset {
257 /// Create a new time offset
258 #[must_use]
259 pub fn new(samples: i64, confidence: f64, correlation: f64) -> Self {
260 Self {
261 samples,
262 confidence,
263 correlation,
264 }
265 }
266
267 /// Convert offset to seconds
268 #[must_use]
269 pub fn to_seconds(&self, sample_rate: u32) -> f64 {
270 self.samples as f64 / f64::from(sample_rate)
271 }
272
273 /// Convert offset to milliseconds
274 #[must_use]
275 pub fn to_milliseconds(&self, sample_rate: u32) -> f64 {
276 self.to_seconds(sample_rate) * 1000.0
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283
284 #[test]
285 fn test_point2d_distance() {
286 let p1 = Point2D::new(0.0, 0.0);
287 let p2 = Point2D::new(3.0, 4.0);
288 assert!((p1.distance(&p2) - 5.0).abs() < f64::EPSILON);
289 assert!((p1.distance_squared(&p2) - 25.0).abs() < f64::EPSILON);
290 }
291
292 #[test]
293 fn test_time_offset_conversion() {
294 let offset = TimeOffset::new(48000, 0.95, 0.85);
295 assert!((offset.to_seconds(48000) - 1.0).abs() < f64::EPSILON);
296 assert!((offset.to_milliseconds(48000) - 1000.0).abs() < f64::EPSILON);
297 }
298}