From b05cf4e9060edf3e96b9c35acd18fea2e26cb235 Mon Sep 17 00:00:00 2001 From: REVPKD Date: Thu, 19 Nov 2026 14:00:33 +0100 Subject: [PATCH 1/3] Estimate unmatched clips from same-device timestamps Use embedded recording-time differences from waveform-matched clips on the same device to estimate positions for clips that remain unmatched. Keep estimates explicitly unconfirmed in results, timeline previews, and exports without changing waveform matches. --- crates/align-core/src/export/fcpxml.rs | 1 + crates/align-core/src/export/model.rs | 163 ++++++++++++++++++++++- crates/align-core/src/export/otio.rs | 1 + crates/align-core/src/export/premiere.rs | 12 +- crates/align-core/src/model.rs | 18 +++ crates/align-decode/src/pipeline.rs | 159 +++++++++++++++++++++- crates/align-gpui/src/lane.rs | 4 + crates/align-gpui/src/state.rs | 8 +- crates/align-gpui/src/views/controls.rs | 1 + 9 files changed, 360 insertions(+), 7 deletions(-) diff --git a/crates/align-core/src/export/fcpxml.rs b/crates/align-core/src/export/fcpxml.rs index c6cfcc4..cf869ac 100644 --- a/crates/align-core/src/export/fcpxml.rs +++ b/crates/align-core/src/export/fcpxml.rs @@ -1720,6 +1720,7 @@ mod tests { placements: vec![placement("cam"), placement("rec")], }], unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: crate::model::TemporalPolicy::default(), }; diff --git a/crates/align-core/src/export/model.rs b/crates/align-core/src/export/model.rs index a291136..fe227e0 100644 --- a/crates/align-core/src/export/model.rs +++ b/crates/align-core/src/export/model.rs @@ -148,6 +148,8 @@ pub struct ExportItem { pub mapping_rate: f64, pub mapping_points: Vec, pub confidence: f64, + /// This item's position is a same-device timestamp estimate, not a sync. + pub estimated: bool, pub corrected_audio_url: Option, pub precision_audio_urls: Vec, pub enabled: bool, @@ -209,6 +211,7 @@ impl ExportItem { mapping_rate, mapping_points, confidence, + estimated: false, corrected_audio_url: None, precision_audio_urls: Vec::new(), enabled: true, @@ -933,6 +936,14 @@ fn unmatched_item(clip: &Clip, options: &ExportAssemblyOptions) -> ExportItem { item } +fn estimated_item(clip: &Clip, start: f64, options: &ExportAssemblyOptions) -> ExportItem { + let mut item = unmatched_item(clip, options); + item.start = start; + item.display_name = Some(format!("[ESTIMATED] {}", file_name(&clip.url))); + item.estimated = true; + item +} + /// Each track moves by the median difference between where the solve /// places its edits' media and where the edit placed them. Preserved /// tracks stay put and the others move relative to them. @@ -1000,6 +1011,7 @@ struct ImportedAssembly<'a> { /// The video edit owning each linked audio edit. parent_by_linked: HashMap<&'a str, &'a str>, unmatched_ids: HashSet<&'a ClipId>, + estimated_ids: HashSet<&'a ClipId>, } impl ImportedAssembly<'_> { @@ -1030,6 +1042,7 @@ impl ImportedAssembly<'_> { .as_ref() .map(|audio| self.linked_audio(audio, base, shift)); let is_unmatched = self.unmatched_ids.contains(&edit.clip_id); + let is_estimated = self.estimated_ids.contains(&edit.clip_id); let fallback_name = || { edit.name .clone() @@ -1037,7 +1050,14 @@ impl ImportedAssembly<'_> { }; let mut item = ExportItem { instance_id: format!("imported-{media_str}-{}", edit.id), - display_name: if is_unmatched { + display_name: if is_estimated { + Some(format!( + "[ESTIMATED] {}", + self.options + .unmatched_label(&fallback_name()) + .unwrap_or_else(&fallback_name) + )) + } else if is_unmatched { self.options.unmatched_label(&fallback_name()) } else { self.options @@ -1096,6 +1116,7 @@ impl ImportedAssembly<'_> { mapping_rate: base.mapping_rate, mapping_points: base.mapping_points.clone(), confidence: base.confidence, + estimated: is_estimated, corrected_audio_url: None, precision_audio_urls: Vec::new(), linked_audio_edit: linked, @@ -1247,8 +1268,39 @@ impl ExportTimeline { let mut order_only_islands = HashSet::new(); if options.unmatched != UnmatchedPlacement::Remove { + let estimated_ids: HashSet<&ClipId> = result + .estimated_placements + .iter() + .map(|placement| &placement.clip_id) + .collect(); + for placement in &result.estimated_placements { + let Some(clip) = clips_by_id.get(&placement.clip_id) else { + continue; + }; + let Some(island) = groups.iter_mut().find(|island| { + island + .clips + .iter() + .any(|item| item.clip.id == placement.anchor_clip_id) + }) else { + continue; + }; + island.clips.push(estimated_item( + clip, + placement.timeline_start.as_seconds(), + &options, + )); + island.duration = island + .duration + .max(placement.timeline_start.as_seconds() + clip.duration.as_seconds()); + } let next_id = groups.iter().map(|g| g.id as i64).max().unwrap_or(-1) + 1; - for (index, clip_id) in result.unmatched.iter().enumerate() { + for (index, clip_id) in result + .unmatched + .iter() + .filter(|clip_id| !estimated_ids.contains(clip_id)) + .enumerate() + { let Some(clip) = clips_by_id.get(clip_id) else { continue; }; @@ -1319,12 +1371,31 @@ impl ExportTimeline { }) .collect(), unmatched_ids: result.unmatched.iter().collect(), + estimated_ids: result + .estimated_placements + .iter() + .map(|placement| &placement.clip_id) + .collect(), }; + let imported_clip_ids: HashSet<&ClipId> = + imported.edits.iter().map(|edit| &edit.clip_id).collect(); let mut imported_items: Vec = imported .edits .iter() .filter_map(|edit| assembly.item(edit)) .collect(); + // Imported edit placement wins when the clip is already on the edit + // timeline. Estimates without an imported edit still need to appear + // alongside the imported sequence at their inferred synchronized + // position, rather than disappearing during the edit reconstruction. + for placement in &result.estimated_placements { + if imported_clip_ids.contains(&placement.clip_id) { + continue; + } + if let Some(item) = assembly.base_by_id.get(&placement.clip_id) { + imported_items.push((**item).clone()); + } + } if imported_items.is_empty() { return Err(TimelineExportError::NoImportedEdits); } @@ -1600,6 +1671,7 @@ impl ExportTimeline { duration: item.timeline_duration, confidence: item.confidence, matched: !unmatched.contains(&item.clip.id), + estimated: item.estimated, }) .collect() } @@ -1966,6 +2038,7 @@ mod tests { }, islands: Vec::new(), unmatched: vec![first.id.clone(), second.id.clone()], + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: TemporalPolicy::default(), }; @@ -2107,6 +2180,7 @@ mod tests { placements: vec![placement(&camera.id, 20.0), placement(&recorder.id, 22.0)], }], unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: Default::default(), }; @@ -2408,6 +2482,7 @@ mod tests { }, islands: Vec::new(), unmatched: vec![first.clip.id.clone(), second.clip.id.clone()], + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: TemporalPolicy::default(), } @@ -2438,11 +2513,95 @@ mod tests { }], }], unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: TemporalPolicy::default(), } } + #[test] + fn estimated_unmatched_clip_is_exported_at_estimate_and_marked_unconfirmed() { + let mut result = synced_result(); + let estimated = placed_clip("camera-take.mov", true, 0.0, 8.0); + let estimated_id = estimated.clip.id.clone(); + result.project.clips.push(estimated.clip); + result.unmatched.push(estimated_id.clone()); + result + .estimated_placements + .push(crate::model::EstimatedPlacement { + clip_id: estimated_id.clone(), + anchor_clip_id: result.islands[0].placements[0].clip_id.clone(), + timeline_start: MediaTime::seconds(80.0), + timestamp_delta: MediaTime::seconds(80.0), + }); + + let timeline = ExportTimeline::from_result(&result, true).expect("estimated timeline"); + let unmatched: HashSet = result.unmatched.iter().cloned().collect(); + let item = timeline + .preview_items(&unmatched) + .into_iter() + .find(|item| item.clip_id == estimated_id) + .expect("estimated clip in timeline"); + assert_eq!(item.start, 80.0); + assert!(!item.matched); + assert!(item.estimated); + assert!(item.name.starts_with("[ESTIMATED]")); + let anchor = timeline + .preview_items(&unmatched) + .into_iter() + .find(|item| item.clip_id == result.islands[0].placements[0].clip_id) + .expect("waveform-matched anchor remains in place"); + assert!(anchor.matched); + assert_eq!(anchor.start, 0.0); + + result.project.imported_timeline = Some(crate::model::ImportedTimeline { + name: "Imported edit".into(), + frame_duration: MediaTime::new(1, 25), + edits: vec![crate::model::TimelineEdit { + id: "anchor-edit".into(), + name: Some("anchor-edit".into()), + clip_id: result.islands[0].placements[0].clip_id.clone(), + media_type: MediaKind::Audio, + source_in: MediaTime::seconds(0.0), + source_out: MediaTime::seconds(10.0), + timeline_start: MediaTime::seconds(0.0), + timeline_end: MediaTime::seconds(10.0), + playback_rate: 1.0, + plays_backward: false, + fcp7_time_remap_xml: None, + fcp7_filter_xmls: Vec::new(), + fcp7_retime_in: None, + fcp7_retime_out: None, + fcp7_retime_duration: None, + fcp7_labels_xml: None, + audio_source_channel: None, + fcpxml_audio_role: None, + track_index: 0, + audio_track_index: None, + enabled: true, + track_enabled: true, + track_locked: false, + audio_enabled: None, + audio_track_enabled: None, + audio_track_locked: None, + transition_after: None, + audio_transition_after: None, + linked_audio_edit: None, + }], + }); + let imported_timeline = + ExportTimeline::from_result(&result, true).expect("estimated imported timeline"); + let imported_preview = imported_timeline.preview_items(&unmatched); + let imported_estimate = imported_preview + .iter() + .find(|item| item.clip_id == estimated_id) + .expect("estimate survives imported timeline assembly"); + assert_eq!(imported_estimate.start, 80.0); + assert!(!imported_estimate.matched); + assert!(imported_estimate.estimated); + assert!(imported_estimate.name.starts_with("[ESTIMATED]")); + } + #[test] fn synced_name_color_and_role_reach_writers() { let timeline = ExportTimeline::from_result_with_options( diff --git a/crates/align-core/src/export/otio.rs b/crates/align-core/src/export/otio.rs index 00d3436..1ba196a 100644 --- a/crates/align-core/src/export/otio.rs +++ b/crates/align-core/src/export/otio.rs @@ -669,6 +669,7 @@ pub(crate) mod tests { placements: vec![placement("cam", 0.0, 10.0), placement("rec", 0.5, 12.0)], }], unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: crate::model::TemporalPolicy::default(), } diff --git a/crates/align-core/src/export/premiere.rs b/crates/align-core/src/export/premiere.rs index ad13641..cccc14c 100644 --- a/crates/align-core/src/export/premiere.rs +++ b/crates/align-core/src/export/premiere.rs @@ -572,7 +572,14 @@ fn replaced_island(island: &ExportIsland) -> Option { .inverted(); replacements.push(ExportItem { instance_id: video.instance_id.clone(), - display_name: recorder.display_name.clone(), + display_name: if video.estimated || recorder.estimated { + Some(format!( + "[ESTIMATED] {}", + recorder.display_name.as_deref().unwrap_or("External audio") + )) + } else { + recorder.display_name.clone() + }, clip: recorder.clip.clone(), start: overlap_start, source_in: recorder.source_in.max(inverse.value_at(overlap_start)), @@ -593,6 +600,7 @@ fn replaced_island(island: &ExportIsland) -> Option { mapping_rate: recorder.mapping_rate, mapping_points: recorder.mapping_points.clone(), confidence: video.confidence.min(recorder.confidence), + estimated: video.estimated || recorder.estimated, corrected_audio_url: recorder.corrected_audio_url.clone(), precision_audio_urls: Vec::new(), enabled: recorder.enabled, @@ -2407,6 +2415,7 @@ mod tests { }], }], unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: crate::model::TemporalPolicy::default(), }; @@ -2565,6 +2574,7 @@ mod tests { }], }], unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: crate::model::TemporalPolicy::default(), }; diff --git a/crates/align-core/src/model.rs b/crates/align-core/src/model.rs index e1bb2ca..9fe0ec8 100644 --- a/crates/align-core/src/model.rs +++ b/crates/align-core/src/model.rs @@ -387,6 +387,18 @@ pub struct Clip { pub media_span: Option, } +/// A best-effort timeline position inferred from another clip recorded by +/// the same device. This is deliberately separate from solved placements: +/// estimates are never waveform matches and remain explicitly unconfirmed. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EstimatedPlacement { + pub clip_id: ClipId, + pub anchor_clip_id: ClipId, + pub timeline_start: MediaTime, + pub timestamp_delta: MediaTime, +} + impl Clip { pub fn source_timecode(&self) -> Option<&SourceTimecode> { self.video @@ -535,6 +547,7 @@ pub struct TimelinePreviewItem { pub duration: f64, pub confidence: f64, pub matched: bool, + pub estimated: bool, } /// Live match preview for progress callbacks. @@ -579,6 +592,9 @@ pub struct SyncResult { pub project: SyncProject, pub islands: Vec, pub unmatched: Vec, + /// Unconfirmed same-device recording-time estimates for unmatched clips. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub estimated_placements: Vec, pub matches: Vec, /// Temporal evidence policy used for this solve. Old serializations /// without the field load with the current Automatic policy. @@ -635,6 +651,8 @@ impl SyncResult { }; self.islands = stage.islands.clone(); self.unmatched = stage.unmatched.clone(); + self.estimated_placements + .retain(|placement| self.unmatched.contains(&placement.clip_id)); self.matches = stage.matches.clone(); self.selected_stage = Some(index); true diff --git a/crates/align-decode/src/pipeline.rs b/crates/align-decode/src/pipeline.rs index e6b0bc6..7b47b4b 100644 --- a/crates/align-decode/src/pipeline.rs +++ b/crates/align-decode/src/pipeline.rs @@ -18,9 +18,9 @@ use std::path::{Path, PathBuf}; use align_core::{ AudioAnalysisSource, AudioSummary, Clip, ClipId, ClipPlacement, ClipTimingHints, - FingerprintCache, FingerprintExtractor, MappingPoint, MatchSummary, MediaKind, MediaTime, - RecordingTimestampSource, SyncConstraint, SyncIsland, SyncProject, SyncWarning, TimeMap, - match_fingerprints, refine_forest, solve_graph, + EstimatedPlacement, FingerprintCache, FingerprintExtractor, MappingPoint, MatchSummary, + MediaKind, MediaTime, RecordingTimestampSource, SyncConstraint, SyncIsland, SyncProject, + SyncWarning, TimeMap, match_fingerprints, refine_forest, solve_graph, }; use sha2::{Digest, Sha256}; @@ -573,6 +573,12 @@ impl Pipeline { cancel, )?; let chosen = stages[selected].clone(); + let waveform_stage = stages + .iter() + .find(|stage| stage.kind == align_core::SyncStageKind::Waveform); + let estimated_placements = waveform_stage.map_or_else(Vec::new, |stage| { + estimate_unmatched_by_device_timestamp(&clips, &stage.islands, &chosen.unmatched) + }); // One-stage results retain legacy JSON, with no redundant history. let selected_stage = (stages.len() > 1).then_some(selected); if selected_stage.is_none() { @@ -596,6 +602,7 @@ impl Pipeline { }, islands: chosen.islands, unmatched: chosen.unmatched, + estimated_placements, matches: chosen.matches, temporal_policy: options.temporal.clone(), }) @@ -1126,6 +1133,60 @@ impl Pipeline { } } +/// Estimate only clips still unmatched in the selected result, using an +/// explicitly identified, waveform-matched clip from the same device. The +/// closest timestamp anchor minimizes accumulated timestamp error. Embedded +/// timestamps only: filesystem timestamps are not recording clocks. +fn estimate_unmatched_by_device_timestamp( + clips: &[Clip], + waveform_islands: &[SyncIsland], + unmatched: &[ClipId], +) -> Vec { + let by_id: HashMap<&ClipId, &Clip> = clips.iter().map(|clip| (&clip.id, clip)).collect(); + let anchors: Vec<_> = waveform_islands + .iter() + .flat_map(|island| &island.placements) + .filter_map(|placement| { + let clip = by_id.get(&placement.clip_id).copied()?; + let source = clip.source_identifier.as_ref()?; + let timestamp = clip.recorded_at.filter(|_| { + clip.recorded_at_source == Some(RecordingTimestampSource::EmbeddedMetadata) + })?; + let start = placement.mapping.points.first()?.island.as_seconds(); + Some((clip, source, timestamp, start)) + }) + .collect(); + let mut estimates = Vec::new(); + for clip_id in unmatched { + let Some(clip) = by_id.get(clip_id).copied() else { + continue; + }; + let (Some(source), Some(timestamp)) = ( + clip.source_identifier.as_ref(), + clip.recorded_at.filter(|_| { + clip.recorded_at_source == Some(RecordingTimestampSource::EmbeddedMetadata) + }), + ) else { + continue; + }; + let anchor = anchors + .iter() + .filter(|(_, anchor_source, _, _)| *anchor_source == source) + .min_by_key(|(_, _, anchor_timestamp, _)| timestamp.abs_diff(*anchor_timestamp)); + let Some((anchor_clip, _, anchor_timestamp, anchor_start)) = anchor else { + continue; + }; + let delta = timestamp.saturating_sub(*anchor_timestamp); + estimates.push(EstimatedPlacement { + clip_id: clip_id.clone(), + anchor_clip_id: anchor_clip.id.clone(), + timeline_start: MediaTime::seconds(*anchor_start + delta as f64), + timestamp_delta: MediaTime::seconds(delta as f64), + }); + } + estimates +} + /// Solves each evidence stage that changes the matches (waveform, then file /// spans, then timecode) and selects the one placing the most clips; equal /// counts retain the later stage. Cancellation keeps the stages solved so @@ -1528,6 +1589,98 @@ fn normalize(p: &Path) -> PathBuf { mod tests { use super::*; + fn timestamped_video(id: &str, device: &str, timestamp: i64) -> Clip { + Clip { + id: ClipId::new(id), + url: PathBuf::from(format!("{id}.mov")), + kind: MediaKind::Video, + duration: MediaTime::seconds(10.0), + audio: Vec::new(), + video: None, + recorded_at: Some(timestamp), + recorded_at_source: Some(RecordingTimestampSource::EmbeddedMetadata), + source_identifier: Some(device.to_string()), + media_span: None, + } + } + + fn timestamp_anchor(clip_id: &str, timeline_start: f64) -> ClipPlacement { + ClipPlacement { + clip_id: ClipId::new(clip_id), + mapping: TimeMap { + points: vec![ + MappingPoint { + source: MediaTime::seconds(0.0), + island: MediaTime::seconds(timeline_start), + }, + MappingPoint { + source: MediaTime::seconds(10.0), + island: MediaTime::seconds(timeline_start + 10.0), + }, + ], + }, + confidence: 0.95, + } + } + + #[test] + fn unmatched_clip_is_estimated_from_same_devices_waveform_anchor() { + let anchor_time = 11 * 3600 + 38 * 60; + let later_time = 12 * 3600 + 58 * 60; + let clips = vec![ + timestamped_video("c0032", "device:cam-a", anchor_time), + timestamped_video("c0033", "device:cam-a", later_time), + timestamped_video("recorder", "device:recorder", anchor_time), + ]; + let islands = vec![SyncIsland { + id: 0, + placements: vec![ + timestamp_anchor("c0032", 125.0), + timestamp_anchor("recorder", 0.0), + ], + }]; + let unmatched = vec![ClipId::new("c0033")]; + + let estimates = estimate_unmatched_by_device_timestamp(&clips, &islands, &unmatched); + + assert_eq!(estimates.len(), 1); + assert_eq!(estimates[0].anchor_clip_id, ClipId::new("c0032")); + assert_eq!(estimates[0].timestamp_delta.as_seconds(), 4800.0); + assert_eq!(estimates[0].timeline_start.as_seconds(), 4925.0); + assert_eq!(unmatched, vec![ClipId::new("c0033")]); + } + + #[test] + fn timestamp_estimates_do_not_cross_devices_or_use_filesystem_times() { + let timestamp = 1_700_000_000; + let anchor = timestamped_video("anchor", "device:cam-a", timestamp); + let mut other_device = timestamped_video("other", "device:cam-b", timestamp + 60); + let mut filesystem = timestamped_video("filesystem", "device:cam-a", timestamp + 60); + filesystem.recorded_at_source = Some(RecordingTimestampSource::FileSystem); + let islands = vec![SyncIsland { + id: 0, + placements: vec![timestamp_anchor("anchor", 0.0)], + }]; + + assert!( + estimate_unmatched_by_device_timestamp( + &[anchor.clone(), other_device.clone()], + &islands, + &[other_device.id.clone()], + ) + .is_empty() + ); + other_device.source_identifier = anchor.source_identifier.clone(); + assert!( + estimate_unmatched_by_device_timestamp( + &[anchor, filesystem.clone()], + &islands, + &[filesystem.id], + ) + .is_empty() + ); + } + #[test] fn waveform_preview_uses_real_amplitude_and_preserves_silence() { let mut accumulator = WaveformPreview::new(4.0); diff --git a/crates/align-gpui/src/lane.rs b/crates/align-gpui/src/lane.rs index e1fb609..addf3da 100644 --- a/crates/align-gpui/src/lane.rs +++ b/crates/align-gpui/src/lane.rs @@ -15,6 +15,7 @@ use align_core::{ pub enum BarMatchState { Pending, Matched, + Estimated, Unmatched, } @@ -209,6 +210,8 @@ pub fn final_bars(result: &align_core::SyncResult) -> FinalTimeline { confidence: item.confidence, match_state: if item.matched { BarMatchState::Matched + } else if item.estimated { + BarMatchState::Estimated } else { BarMatchState::Unmatched }, @@ -661,6 +664,7 @@ mod tests { }, islands: vec![island(0, "a"), island(1, "b")], unmatched: vec![ClipId::new("c")], + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: TemporalPolicy::default(), }; diff --git a/crates/align-gpui/src/state.rs b/crates/align-gpui/src/state.rs index c526136..b15e843 100644 --- a/crates/align-gpui/src/state.rs +++ b/crates/align-gpui/src/state.rs @@ -2298,7 +2298,9 @@ fn imported_preview(result: &SyncResult) -> ImportedPreview { .preview_items(&unmatched) .into_iter() .map(|item| { - let state = if unmatched.contains(&item.clip_id) { + let state = if item.estimated { + lane::BarMatchState::Estimated + } else if unmatched.contains(&item.clip_id) { lane::BarMatchState::Unmatched } else { lane::BarMatchState::Matched @@ -2404,6 +2406,7 @@ mod tests { }, islands: Vec::new(), unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: Default::default(), } @@ -2648,6 +2651,7 @@ mod tests { placements: vec![placement("a.mov", 0.0, 10.0), placement("b.wav", 0.5, 10.0)], }], unmatched: vec![ClipId::new("c.wav")], + estimated_placements: Vec::new(), matches: vec![MatchSummary { left: ClipId::new("a.mov"), right: ClipId::new("b.wav"), @@ -3053,6 +3057,7 @@ mod tests { }, islands: Vec::new(), unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: align_core::TemporalPolicy::default(), }); @@ -3350,6 +3355,7 @@ mod tests { placements: vec![placement("camera.mov")], }], unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: align_core::TemporalPolicy::default(), }); diff --git a/crates/align-gpui/src/views/controls.rs b/crates/align-gpui/src/views/controls.rs index 3bc3d1b..522d949 100644 --- a/crates/align-gpui/src/views/controls.rs +++ b/crates/align-gpui/src/views/controls.rs @@ -348,6 +348,7 @@ pub(super) fn clip_color(state: crate::lane::BarMatchState) -> u32 { match state { BarMatchState::Pending => 0x007AFF, BarMatchState::Matched => 0x34C759, + BarMatchState::Estimated => 0xAF52DE, BarMatchState::Unmatched => 0xFF9500, } } From 033c3adf74c2f63f9cd1594be5c4c7a27e842a15 Mon Sep 17 00:00:00 2001 From: REVPKD Date: Fri, 20 Nov 2026 09:03:57 +0100 Subject: [PATCH 2/3] fix(export): bound generated audio paths --- Support/aaf/test_bridge.py | 7 ++++--- crates/align-decode/src/export.rs | 20 ++++++++++++++++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/Support/aaf/test_bridge.py b/Support/aaf/test_bridge.py index 9606021..8c36e9c 100644 --- a/Support/aaf/test_bridge.py +++ b/Support/aaf/test_bridge.py @@ -40,11 +40,12 @@ def test_path_repair_writes_copy_and_preserves_source(self): self.assertEqual(changed, 1) with aaf2.open(str(source), 'r') as container: locator = next(iter(container.content.sourcemobs())).descriptor['Locator'].value[0] - self.assertEqual(locator_path(locator['URLString'].value), str(old.resolve())) + self.assertEqual(locator_path(locator['URLString'].value), + str(old.resolve()).replace('\\', '/')) with aaf2.open(str(output), 'r') as container: locator = next(iter(container.content.sourcemobs())).descriptor['Locator'].value[0] self.assertEqual(locator_path(locator['URLString'].value), - str(replacement.resolve())) + str(replacement.resolve()).replace('\\', '/')) def test_embedded_pcm_extracts_exact_samples_without_external_source(self): with tempfile.TemporaryDirectory() as directory: @@ -460,7 +461,7 @@ def test_linked_picture_preserves_fractional_edit_rate(self): track = result['sequences'][0]['tracks'][0] self.assertEqual(track['media_kind'], 'picture') self.assertEqual(track['edit_rate'], {'numerator': 30000, 'denominator': 1001}) - self.assertEqual(track['clips'], [{'path': str(media), 'start': 7, + self.assertEqual(track['clips'], [{'path': str(media).replace('\\', '/'), 'start': 7, 'source_in': 11, 'length': 101, 'channel': None}]) with self.assertRaises(ValueError): read_timeline(path, audio_only=True) diff --git a/crates/align-decode/src/export.rs b/crates/align-decode/src/export.rs index 5b57c3a..e146cc5 100644 --- a/crates/align-decode/src/export.rs +++ b/crates/align-decode/src/export.rs @@ -477,10 +477,13 @@ const AUDIO_SIDECAR_REVISION: u32 = 16; /// file in an editor's bin; the hash keeps every rendering input, so a file /// with this name can be reused as is. fn sidecar_name(media: &Path, label: &str, identity: &[&str]) -> String { - let stem = media + let stem: String = media .file_stem() .and_then(|name| name.to_str()) - .unwrap_or("clip"); + .unwrap_or("clip") + .chars() + .take(32) + .collect(); let mut hash = blake3::Hasher::new(); hash.update(&AUDIO_SIDECAR_REVISION.to_le_bytes()); for part in identity { @@ -1036,6 +1039,19 @@ mod tests { AudioSummary, Clip, ClipId, MediaKind, MediaTime, VideoFrameRateMode, VideoSummary, }; + #[test] + fn prepared_audio_name_bounds_long_source_stems() { + let media = PathBuf::from(format!("{}.wav", "a".repeat(96))); + let name = sidecar_name(&media, "channel 1", &["source", "identity"]); + + assert!( + name.len() <= 80, + "sidecar name too long: {} chars", + name.len() + ); + assert!(name.ends_with(".wav")); + } + #[cfg(unix)] #[test] fn source_revision_invalidates_restored_mtime_and_honors_cancel() { From dbc2c9feae4f35dde29a710f55908334942e8ad1 Mon Sep 17 00:00:00 2001 From: REVPKD Date: Mon, 23 Nov 2026 19:56:14 +0100 Subject: [PATCH 3/3] fix: estimate unmatched clips from same-device timestamps Apply relative recording-time deltas from waveform-matched clips on the selected export stage. Keep unmatched clips visible when an anchor cannot be applied, preserve source-to-timeline mapping, bound large gaps, and require explicit opt-in before estimated placements enter exports. --- crates/align-cli/src/export_job.rs | 2 + crates/align-cli/src/main.rs | 6 + crates/align-core/src/export/model.rs | 175 +++++++++++++++++------ crates/align-core/src/export/premiere.rs | 55 +++++++ crates/align-core/src/model.rs | 149 ++++++++++++++++++- crates/align-decode/src/pipeline.rs | 148 +++++++++++-------- crates/align-gpui/src/state.rs | 6 + crates/align-gpui/src/views/export.rs | 13 ++ crates/align-gpui/src/views/mod.rs | 1 + 9 files changed, 451 insertions(+), 104 deletions(-) diff --git a/crates/align-cli/src/export_job.rs b/crates/align-cli/src/export_job.rs index 85ea104..68a016e 100644 --- a/crates/align-cli/src/export_job.rs +++ b/crates/align-cli/src/export_job.rs @@ -54,6 +54,7 @@ impl ExportOptions { no_fcpxml_multicam, export_media, unmatched, + apply_estimated_placements, prevent_group_overlaps, disable_unmatched, label_synced, @@ -68,6 +69,7 @@ impl ExportOptions { result, align_core::export_model::ExportAssemblyOptions { unmatched: unmatched.core(), + apply_estimated_placements, prevent_group_overlaps, disable_unmatched, label_synced, diff --git a/crates/align-cli/src/main.rs b/crates/align-cli/src/main.rs index 9c1abb6..b7d9aad 100644 --- a/crates/align-cli/src/main.rs +++ b/crates/align-cli/src/main.rs @@ -106,6 +106,9 @@ struct ExportOptions { /// Placement policy for clips without a synchronization match. #[arg(long, value_enum, default_value_t = Unmatched::OrderTime)] unmatched: Unmatched, + /// Explicitly apply unconfirmed same-device timestamp estimates to exports. + #[arg(long)] + apply_estimated_placements: bool, /// Place independent synchronization groups without overlaps. #[arg(long)] prevent_group_overlaps: bool, @@ -926,6 +929,7 @@ mod tests { "--media-bins", "--no-fcpxml-multicam", "--export-media", + "--apply-estimated-placements", "--label-synced", "--label-unmatched", "--synced-symbol", @@ -951,6 +955,7 @@ mod tests { no_fcpxml_timeline, no_fcpxml_multicam, export_media, + apply_estimated_placements, label_synced, label_unmatched, assign, @@ -994,6 +999,7 @@ mod tests { assert!(!no_fcpxml_timeline); assert!(no_fcpxml_multicam); assert!(export_media); + assert!(apply_estimated_placements); assert!(label_synced); assert!(label_unmatched); assert_eq!(assign.synced_symbol.as_deref(), Some("✓")); diff --git a/crates/align-core/src/export/model.rs b/crates/align-core/src/export/model.rs index fe227e0..8f8a500 100644 --- a/crates/align-core/src/export/model.rs +++ b/crates/align-core/src/export/model.rs @@ -514,6 +514,9 @@ pub enum UnmatchedPlacement { #[derive(Clone, Debug, Default, PartialEq)] pub struct ExportAssemblyOptions { pub unmatched: UnmatchedPlacement, + /// Apply same-device timestamp estimates to the export timeline. Estimates + /// remain unconfirmed, so this is deliberately opt-in. + pub apply_estimated_placements: bool, pub prevent_group_overlaps: bool, pub disable_unmatched: bool, pub label_synced: bool, @@ -939,6 +942,9 @@ fn unmatched_item(clip: &Clip, options: &ExportAssemblyOptions) -> ExportItem { fn estimated_item(clip: &Clip, start: f64, options: &ExportAssemblyOptions) -> ExportItem { let mut item = unmatched_item(clip, options); item.start = start; + for point in &mut item.mapping_points { + point.island = MediaTime::seconds(point.island.as_seconds() + start); + } item.display_name = Some(format!("[ESTIMATED] {}", file_name(&clip.url))); item.estimated = true; item @@ -1268,37 +1274,36 @@ impl ExportTimeline { let mut order_only_islands = HashSet::new(); if options.unmatched != UnmatchedPlacement::Remove { - let estimated_ids: HashSet<&ClipId> = result - .estimated_placements - .iter() - .map(|placement| &placement.clip_id) - .collect(); - for placement in &result.estimated_placements { - let Some(clip) = clips_by_id.get(&placement.clip_id) else { - continue; - }; - let Some(island) = groups.iter_mut().find(|island| { - island - .clips - .iter() - .any(|item| item.clip.id == placement.anchor_clip_id) - }) else { - continue; - }; - island.clips.push(estimated_item( - clip, - placement.timeline_start.as_seconds(), - &options, - )); - island.duration = island - .duration - .max(placement.timeline_start.as_seconds() + clip.duration.as_seconds()); + let mut applied_estimate_ids = HashSet::new(); + if options.apply_estimated_placements { + for placement in &result.estimated_placements { + let Some(clip) = clips_by_id.get(&placement.clip_id) else { + continue; + }; + let Some(island) = groups.iter_mut().find(|island| { + island + .clips + .iter() + .any(|item| item.clip.id == placement.anchor_clip_id) + }) else { + continue; + }; + applied_estimate_ids.insert(placement.clip_id.clone()); + island.clips.push(estimated_item( + clip, + placement.timeline_start.as_seconds(), + &options, + )); + island.duration = island + .duration + .max(placement.timeline_start.as_seconds() + clip.duration.as_seconds()); + } } let next_id = groups.iter().map(|g| g.id as i64).max().unwrap_or(-1) + 1; for (index, clip_id) in result .unmatched .iter() - .filter(|clip_id| !estimated_ids.contains(clip_id)) + .filter(|clip_id| !applied_estimate_ids.contains(*clip_id)) .enumerate() { let Some(clip) = clips_by_id.get(clip_id) else { @@ -1356,6 +1361,12 @@ impl ExportTimeline { combined_base.order_only_islands = order_only_islands; let combined = combined_base.combined_island(1.0); let base_by_id = combined.clips.iter().map(|i| (&i.clip.id, i)).collect(); + let estimated_ids: HashSet<&ClipId> = combined + .clips + .iter() + .filter(|item| item.estimated) + .map(|item| &item.clip.id) + .collect(); let assembly = ImportedAssembly { result, options: &options, @@ -1371,11 +1382,7 @@ impl ExportTimeline { }) .collect(), unmatched_ids: result.unmatched.iter().collect(), - estimated_ids: result - .estimated_placements - .iter() - .map(|placement| &placement.clip_id) - .collect(), + estimated_ids, }; let imported_clip_ids: HashSet<&ClipId> = imported.edits.iter().map(|edit| &edit.clip_id).collect(); @@ -1388,12 +1395,17 @@ impl ExportTimeline { // timeline. Estimates without an imported edit still need to appear // alongside the imported sequence at their inferred synchronized // position, rather than disappearing during the edit reconstruction. - for placement in &result.estimated_placements { - if imported_clip_ids.contains(&placement.clip_id) { - continue; - } - if let Some(item) = assembly.base_by_id.get(&placement.clip_id) { - imported_items.push((**item).clone()); + if options.apply_estimated_placements { + for placement in &result.estimated_placements { + if !assembly.estimated_ids.contains(&placement.clip_id) { + continue; + } + if imported_clip_ids.contains(&placement.clip_id) { + continue; + } + if let Some(item) = assembly.base_by_id.get(&placement.clip_id) { + imported_items.push((**item).clone()); + } } } if imported_items.is_empty() { @@ -2535,7 +2547,14 @@ mod tests { timestamp_delta: MediaTime::seconds(80.0), }); - let timeline = ExportTimeline::from_result(&result, true).expect("estimated timeline"); + let timeline = ExportTimeline::from_result_with_options( + &result, + ExportAssemblyOptions { + apply_estimated_placements: true, + ..Default::default() + }, + ) + .expect("estimated timeline"); let unmatched: HashSet = result.unmatched.iter().cloned().collect(); let item = timeline .preview_items(&unmatched) @@ -2546,6 +2565,14 @@ mod tests { assert!(!item.matched); assert!(item.estimated); assert!(item.name.starts_with("[ESTIMATED]")); + let mapped_item = timeline + .combined_island(1.0) + .clips + .into_iter() + .find(|item| item.clip.id == estimated_id) + .expect("estimated source mapping"); + assert_eq!(mapped_item.mapping_points[0].island.as_seconds(), 80.0); + assert_eq!(mapped_item.mapping_points[1].island.as_seconds(), 88.0); let anchor = timeline .preview_items(&unmatched) .into_iter() @@ -2589,8 +2616,14 @@ mod tests { linked_audio_edit: None, }], }); - let imported_timeline = - ExportTimeline::from_result(&result, true).expect("estimated imported timeline"); + let imported_timeline = ExportTimeline::from_result_with_options( + &result, + ExportAssemblyOptions { + apply_estimated_placements: true, + ..Default::default() + }, + ) + .expect("estimated imported timeline"); let imported_preview = imported_timeline.preview_items(&unmatched); let imported_estimate = imported_preview .iter() @@ -2602,6 +2635,68 @@ mod tests { assert!(imported_estimate.name.starts_with("[ESTIMATED]")); } + #[test] + fn estimated_placements_are_not_applied_without_explicit_opt_in() { + let mut result = synced_result(); + let estimated = placed_clip("camera-take.mov", true, 0.0, 8.0); + let estimated_id = estimated.clip.id.clone(); + result.project.clips.push(estimated.clip); + result.unmatched.push(estimated_id.clone()); + result + .estimated_placements + .push(crate::model::EstimatedPlacement { + clip_id: estimated_id.clone(), + anchor_clip_id: result.islands[0].placements[0].clip_id.clone(), + timeline_start: MediaTime::seconds(80.0), + timestamp_delta: MediaTime::seconds(80.0), + }); + + let timeline = ExportTimeline::from_result(&result, true).expect("timeline"); + let unmatched: HashSet = result.unmatched.iter().cloned().collect(); + let item = timeline + .preview_items(&unmatched) + .into_iter() + .find(|item| item.clip_id == estimated_id) + .expect("unmatched clip remains in normal export handling"); + assert_eq!(item.start, 11.0); + assert!(!item.estimated); + assert!(!item.name.starts_with("[ESTIMATED]")); + } + + #[test] + fn estimate_without_anchor_on_selected_stage_remains_unmatched_in_export() { + let mut result = synced_result(); + let estimated = placed_clip("camera-take.mov", true, 0.0, 8.0); + let estimated_id = estimated.clip.id.clone(); + result.project.clips.push(estimated.clip); + result.unmatched.push(estimated_id.clone()); + result + .estimated_placements + .push(crate::model::EstimatedPlacement { + clip_id: estimated_id.clone(), + anchor_clip_id: ClipId::new("anchor-not-on-selected-stage"), + timeline_start: MediaTime::seconds(80.0), + timestamp_delta: MediaTime::seconds(80.0), + }); + + let timeline = ExportTimeline::from_result_with_options( + &result, + ExportAssemblyOptions { + apply_estimated_placements: true, + ..Default::default() + }, + ) + .expect("timeline"); + let unmatched: HashSet = result.unmatched.iter().cloned().collect(); + let item = timeline + .preview_items(&unmatched) + .into_iter() + .find(|item| item.clip_id == estimated_id) + .expect("unapplied estimate remains unmatched"); + assert_eq!(item.start, 11.0); + assert!(!item.estimated); + } + #[test] fn synced_name_color_and_role_reach_writers() { let timeline = ExportTimeline::from_result_with_options( diff --git a/crates/align-core/src/export/premiere.rs b/crates/align-core/src/export/premiere.rs index cccc14c..bdb64cd 100644 --- a/crates/align-core/src/export/premiere.rs +++ b/crates/align-core/src/export/premiere.rs @@ -1725,6 +1725,61 @@ mod tests { assert!(!resolve.contains("subframeoffset")); } + #[test] + fn replacement_audio_source_in_uses_estimated_clip_timeline_mapping() { + use crate::{MediaTime, model::MappingPoint}; + + let mut timeline = fixture_timeline(); + let island = &mut timeline.islands[0]; + let camera = island + .clips + .iter_mut() + .find(|item| item.clip.id.0 == "cam") + .expect("camera clip"); + camera.start = 112.0; + camera.timeline_duration = 8.0; + camera.estimated = true; + camera.mapping_points = vec![ + MappingPoint { + source: MediaTime::seconds(0.0), + island: MediaTime::seconds(112.0), + }, + MappingPoint { + source: MediaTime::seconds(8.0), + island: MediaTime::seconds(120.0), + }, + ]; + let recorder = island + .clips + .iter_mut() + .find(|item| item.clip.id.0 == "rec") + .expect("recorder clip"); + recorder.start = 107.0; + recorder.mapping_points = vec![ + MappingPoint { + source: MediaTime::seconds(0.0), + island: MediaTime::seconds(107.0), + }, + MappingPoint { + source: MediaTime::seconds(12.0), + island: MediaTime::seconds(119.0), + }, + ]; + + let xml = write( + &timeline, + TimelineExportFormat::PremiereXML, + PremiereOptions { + replaced_sequence: true, + ..Default::default() + }, + ); + let replacement_at = xml.find("id=\"sequence-2\"").expect("replacement sequence"); + let replacement = &xml[replacement_at..]; + assert!(replacement.contains("125"), "{replacement}"); + assert!(!replacement.contains("375"), "{replacement}"); + } + /// The source range moves with the start's rounding: a start 0.49 of a /// frame past frame 25 with a source in 0.51 past frame 12 plays within /// a fiftieth of a frame, where rounding each alone was a frame off. diff --git a/crates/align-core/src/model.rs b/crates/align-core/src/model.rs index 9fe0ec8..d9916a6 100644 --- a/crates/align-core/src/model.rs +++ b/crates/align-core/src/model.rs @@ -3,7 +3,7 @@ //! Serialized field names are part of the saved-result and CLI JSON contracts. use serde::{Deserialize, Serialize}; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; // ---------------------------------------------------------------- Clip IDs @@ -651,14 +651,87 @@ impl SyncResult { }; self.islands = stage.islands.clone(); self.unmatched = stage.unmatched.clone(); - self.estimated_placements - .retain(|placement| self.unmatched.contains(&placement.clip_id)); + let waveform_islands = self + .stages + .iter() + .find(|candidate| candidate.kind == SyncStageKind::Waveform) + .map(|candidate| candidate.islands.as_slice()) + .unwrap_or(&self.islands); + self.estimated_placements = estimate_unmatched_by_device_timestamp( + &self.project.clips, + waveform_islands, + &self.islands, + &self.unmatched, + ); self.matches = stage.matches.clone(); self.selected_stage = Some(index); true } } +/// Estimate unmatched clips from embedded timestamps, anchored only to a +/// waveform-matched clip from the same source. Positions come from the +/// selected stage; large clock gaps are deliberately left unplaced. +pub fn estimate_unmatched_by_device_timestamp( + clips: &[Clip], + waveform_islands: &[SyncIsland], + selected_islands: &[SyncIsland], + unmatched: &[ClipId], +) -> Vec { + let by_id: HashMap<&ClipId, &Clip> = clips.iter().map(|clip| (&clip.id, clip)).collect(); + let waveform_matched: HashSet<&ClipId> = waveform_islands + .iter() + .flat_map(|island| &island.placements) + .map(|placement| &placement.clip_id) + .collect(); + let anchors: Vec<_> = selected_islands + .iter() + .flat_map(|island| &island.placements) + .filter(|placement| waveform_matched.contains(&placement.clip_id)) + .filter_map(|placement| { + let clip = by_id.get(&placement.clip_id).copied()?; + let source = clip.source_identifier.as_ref()?; + let timestamp = clip.recorded_at.filter(|_| { + clip.recorded_at_source == Some(RecordingTimestampSource::EmbeddedMetadata) + })?; + let start = placement.mapping.points.first()?.island.as_seconds(); + Some((clip, source, timestamp, start)) + }) + .collect(); + let mut estimates = Vec::new(); + for clip_id in unmatched { + let Some(clip) = by_id.get(clip_id).copied() else { + continue; + }; + let (Some(source), Some(timestamp)) = ( + clip.source_identifier.as_ref(), + clip.recorded_at.filter(|_| { + clip.recorded_at_source == Some(RecordingTimestampSource::EmbeddedMetadata) + }), + ) else { + continue; + }; + let anchor = anchors + .iter() + .filter(|(_, anchor_source, _, _)| *anchor_source == source) + .min_by_key(|(_, _, anchor_timestamp, _)| timestamp.abs_diff(*anchor_timestamp)); + let Some((anchor_clip, _, anchor_timestamp, anchor_start)) = anchor else { + continue; + }; + let delta = i128::from(timestamp) - i128::from(*anchor_timestamp); + if delta.unsigned_abs() > 6 * 60 * 60 { + continue; + } + estimates.push(EstimatedPlacement { + clip_id: clip_id.clone(), + anchor_clip_id: anchor_clip.id.clone(), + timeline_start: MediaTime::seconds(*anchor_start + delta as f64), + timestamp_delta: MediaTime::seconds(delta as f64), + }); + } + estimates +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncIsland { pub id: usize, @@ -1100,6 +1173,76 @@ mod tests { ); } + #[test] + fn selecting_stage_reanchors_unconfirmed_timestamp_estimates() { + use std::path::PathBuf; + let clip = |id: &str, timestamp: i64| Clip { + id: ClipId::new(id), + url: PathBuf::from(format!("/{id}.mov")), + kind: MediaKind::Video, + duration: MediaTime::seconds(10.0), + audio: Vec::new(), + video: None, + recorded_at: Some(timestamp), + recorded_at_source: Some(RecordingTimestampSource::EmbeddedMetadata), + source_identifier: Some("camera-a".into()), + media_span: None, + }; + let anchor_id = ClipId::new("anchor"); + let unmatched_id = ClipId::new("later"); + let placement = |start: f64| ClipPlacement { + clip_id: anchor_id.clone(), + mapping: TimeMap { + points: vec![MappingPoint { + source: MediaTime::seconds(0.0), + island: MediaTime::seconds(start), + }], + }, + confidence: 1.0, + }; + let stage = |kind, start| SyncStage { + kind, + islands: vec![SyncIsland { + id: 0, + placements: vec![placement(start)], + }], + unmatched: vec![unmatched_id.clone()], + matches: Vec::new(), + }; + let waveform_stage = stage(SyncStageKind::Waveform, 2.0); + let selected_stage = stage(SyncStageKind::FileSpans, 102.0); + let mut result = SyncResult { + search_overrides: HashMap::new(), + stopped: false, + stages: vec![waveform_stage.clone(), selected_stage], + selected_stage: Some(0), + search_accuracy: crate::SearchAccuracy::default(), + preserve_editing_tracks: Default::default(), + project: SyncProject { + clips: vec![clip("anchor", 100), clip("later", 110)], + warnings: Vec::new(), + imported_timeline: None, + }, + islands: waveform_stage.islands, + unmatched: vec![unmatched_id.clone()], + estimated_placements: vec![EstimatedPlacement { + clip_id: unmatched_id.clone(), + anchor_clip_id: anchor_id, + timeline_start: MediaTime::seconds(12.0), + timestamp_delta: MediaTime::seconds(10.0), + }], + matches: Vec::new(), + temporal_policy: TemporalPolicy::default(), + }; + + assert!(result.select_stage(1)); + assert_eq!(result.estimated_placements.len(), 1); + assert_eq!( + result.estimated_placements[0].timeline_start.as_seconds(), + 112.0 + ); + } + #[test] fn temporal_mode_anchors_and_round_trip() { use std::path::PathBuf; diff --git a/crates/align-decode/src/pipeline.rs b/crates/align-decode/src/pipeline.rs index 7b47b4b..e93b4f4 100644 --- a/crates/align-decode/src/pipeline.rs +++ b/crates/align-decode/src/pipeline.rs @@ -18,9 +18,9 @@ use std::path::{Path, PathBuf}; use align_core::{ AudioAnalysisSource, AudioSummary, Clip, ClipId, ClipPlacement, ClipTimingHints, - EstimatedPlacement, FingerprintCache, FingerprintExtractor, MappingPoint, MatchSummary, - MediaKind, MediaTime, RecordingTimestampSource, SyncConstraint, SyncIsland, SyncProject, - SyncWarning, TimeMap, match_fingerprints, refine_forest, solve_graph, + FingerprintCache, FingerprintExtractor, MappingPoint, MatchSummary, MediaKind, MediaTime, + RecordingTimestampSource, SyncConstraint, SyncIsland, SyncProject, SyncWarning, TimeMap, + match_fingerprints, refine_forest, solve_graph, }; use sha2::{Digest, Sha256}; @@ -577,7 +577,12 @@ impl Pipeline { .iter() .find(|stage| stage.kind == align_core::SyncStageKind::Waveform); let estimated_placements = waveform_stage.map_or_else(Vec::new, |stage| { - estimate_unmatched_by_device_timestamp(&clips, &stage.islands, &chosen.unmatched) + align_core::estimate_unmatched_by_device_timestamp( + &clips, + &stage.islands, + &chosen.islands, + &chosen.unmatched, + ) }); // One-stage results retain legacy JSON, with no redundant history. let selected_stage = (stages.len() > 1).then_some(selected); @@ -1133,60 +1138,6 @@ impl Pipeline { } } -/// Estimate only clips still unmatched in the selected result, using an -/// explicitly identified, waveform-matched clip from the same device. The -/// closest timestamp anchor minimizes accumulated timestamp error. Embedded -/// timestamps only: filesystem timestamps are not recording clocks. -fn estimate_unmatched_by_device_timestamp( - clips: &[Clip], - waveform_islands: &[SyncIsland], - unmatched: &[ClipId], -) -> Vec { - let by_id: HashMap<&ClipId, &Clip> = clips.iter().map(|clip| (&clip.id, clip)).collect(); - let anchors: Vec<_> = waveform_islands - .iter() - .flat_map(|island| &island.placements) - .filter_map(|placement| { - let clip = by_id.get(&placement.clip_id).copied()?; - let source = clip.source_identifier.as_ref()?; - let timestamp = clip.recorded_at.filter(|_| { - clip.recorded_at_source == Some(RecordingTimestampSource::EmbeddedMetadata) - })?; - let start = placement.mapping.points.first()?.island.as_seconds(); - Some((clip, source, timestamp, start)) - }) - .collect(); - let mut estimates = Vec::new(); - for clip_id in unmatched { - let Some(clip) = by_id.get(clip_id).copied() else { - continue; - }; - let (Some(source), Some(timestamp)) = ( - clip.source_identifier.as_ref(), - clip.recorded_at.filter(|_| { - clip.recorded_at_source == Some(RecordingTimestampSource::EmbeddedMetadata) - }), - ) else { - continue; - }; - let anchor = anchors - .iter() - .filter(|(_, anchor_source, _, _)| *anchor_source == source) - .min_by_key(|(_, _, anchor_timestamp, _)| timestamp.abs_diff(*anchor_timestamp)); - let Some((anchor_clip, _, anchor_timestamp, anchor_start)) = anchor else { - continue; - }; - let delta = timestamp.saturating_sub(*anchor_timestamp); - estimates.push(EstimatedPlacement { - clip_id: clip_id.clone(), - anchor_clip_id: anchor_clip.id.clone(), - timeline_start: MediaTime::seconds(*anchor_start + delta as f64), - timestamp_delta: MediaTime::seconds(delta as f64), - }); - } - estimates -} - /// Solves each evidence stage that changes the matches (waveform, then file /// spans, then timecode) and selects the one placing the most clips; equal /// counts retain the later stage. Cancellation keeps the stages solved so @@ -1641,7 +1592,9 @@ mod tests { }]; let unmatched = vec![ClipId::new("c0033")]; - let estimates = estimate_unmatched_by_device_timestamp(&clips, &islands, &unmatched); + let estimates = align_core::estimate_unmatched_by_device_timestamp( + &clips, &islands, &islands, &unmatched, + ); assert_eq!(estimates.len(), 1); assert_eq!(estimates[0].anchor_clip_id, ClipId::new("c0032")); @@ -1650,6 +1603,77 @@ mod tests { assert_eq!(unmatched, vec![ClipId::new("c0033")]); } + #[test] + fn timestamp_estimate_uses_the_anchor_position_on_the_selected_stage() { + let timestamp = 1_700_000_000; + let clips = vec![ + timestamped_video("anchor", "device:cam-a", timestamp), + timestamped_video("later", "device:cam-a", timestamp + 10), + ]; + let waveform = vec![SyncIsland { + id: 0, + placements: vec![timestamp_anchor("anchor", 2.0)], + }]; + let selected = vec![SyncIsland { + id: 0, + placements: vec![timestamp_anchor("anchor", 102.0)], + }]; + + let estimates = align_core::estimate_unmatched_by_device_timestamp( + &clips, + &waveform, + &selected, + &[ClipId::new("later")], + ); + + assert_eq!(estimates.len(), 1); + assert_eq!(estimates[0].timeline_start.as_seconds(), 112.0); + } + + #[test] + fn timestamp_estimate_stays_unmatched_when_waveform_anchor_is_absent_on_selected_stage() { + let timestamp = 1_700_000_000; + let clips = vec![ + timestamped_video("anchor", "device:cam-a", timestamp), + timestamped_video("later", "device:cam-a", timestamp + 10), + ]; + let waveform = vec![SyncIsland { + id: 0, + placements: vec![timestamp_anchor("anchor", 2.0)], + }]; + + let estimates = align_core::estimate_unmatched_by_device_timestamp( + &clips, + &waveform, + &[], + &[ClipId::new("later")], + ); + + assert!(estimates.is_empty()); + } + + #[test] + fn timestamp_estimate_rejects_deltas_over_six_hours() { + let timestamp = 1_700_000_000; + let clips = vec![ + timestamped_video("anchor", "device:cam-a", timestamp), + timestamped_video("later", "device:cam-a", timestamp + 6 * 60 * 60 + 1), + ]; + let islands = vec![SyncIsland { + id: 0, + placements: vec![timestamp_anchor("anchor", 2.0)], + }]; + + let estimates = align_core::estimate_unmatched_by_device_timestamp( + &clips, + &islands, + &islands, + &[ClipId::new("later")], + ); + + assert!(estimates.is_empty()); + } + #[test] fn timestamp_estimates_do_not_cross_devices_or_use_filesystem_times() { let timestamp = 1_700_000_000; @@ -1663,18 +1687,20 @@ mod tests { }]; assert!( - estimate_unmatched_by_device_timestamp( + align_core::estimate_unmatched_by_device_timestamp( &[anchor.clone(), other_device.clone()], &islands, + &islands, &[other_device.id.clone()], ) .is_empty() ); other_device.source_identifier = anchor.source_identifier.clone(); assert!( - estimate_unmatched_by_device_timestamp( + align_core::estimate_unmatched_by_device_timestamp( &[anchor, filesystem.clone()], &islands, + &islands, &[filesystem.id], ) .is_empty() diff --git a/crates/align-gpui/src/state.rs b/crates/align-gpui/src/state.rs index b15e843..0e5c5f7 100644 --- a/crates/align-gpui/src/state.rs +++ b/crates/align-gpui/src/state.rs @@ -131,6 +131,7 @@ pub struct ExportSettings { pub aaf_frame_duration: Option, pub media_files: bool, pub unmatched: UnmatchedPlacement, + pub apply_estimated_placements: bool, pub prevent_group_overlaps: bool, pub disable_unmatched: bool, pub label_synced: bool, @@ -171,6 +172,7 @@ impl Default for ExportSettings { aaf_frame_duration: None, media_files: false, unmatched: UnmatchedPlacement::ByOrderAndTime, + apply_estimated_placements: false, prevent_group_overlaps: false, disable_unmatched: false, label_synced: false, @@ -388,6 +390,7 @@ pub struct AppData { pub export_aaf_frame_duration: Option, pub export_media: bool, pub export_unmatched: UnmatchedPlacement, + pub export_apply_estimates: bool, pub export_prevent_overlaps: bool, pub export_disable_unmatched: bool, pub export_label_synced: bool, @@ -478,6 +481,7 @@ impl Default for AppData { export_aaf_frame_duration: None, export_media: false, export_unmatched: UnmatchedPlacement::ByOrderAndTime, + export_apply_estimates: false, export_prevent_overlaps: false, export_disable_unmatched: false, export_label_synced: false, @@ -949,6 +953,7 @@ impl AppData { aaf_frame_duration: self.export_aaf_frame_duration, media_files: self.export_media, unmatched: self.export_unmatched, + apply_estimated_placements: self.export_apply_estimates, prevent_group_overlaps: self.export_prevent_overlaps, disable_unmatched: self.export_disable_unmatched, label_synced: self.export_label_synced, @@ -976,6 +981,7 @@ impl AppData { self.export_aaf_frame_duration = settings.aaf_frame_duration; self.export_media = settings.media_files; self.export_unmatched = settings.unmatched; + self.export_apply_estimates = settings.apply_estimated_placements; self.export_prevent_overlaps = settings.prevent_group_overlaps; self.export_disable_unmatched = settings.disable_unmatched; self.export_label_synced = settings.label_synced; diff --git a/crates/align-gpui/src/views/export.rs b/crates/align-gpui/src/views/export.rs index bc99a2d..b632bc8 100644 --- a/crates/align-gpui/src/views/export.rs +++ b/crates/align-gpui/src/views/export.rs @@ -1611,6 +1611,19 @@ fn export_unmatched_section(cx: &mut Context, sheet: SheetContext) -> 92., menu, )); + group = group.child(check_row( + cx, + theme, + "exp-apply-estimates", + data.export_apply_estimates, + "Apply unconfirmed timestamp estimates to exports".to_string(), + !busy, + |this, _, _, cx| { + this.update_export_options(cx, |data| { + data.export_apply_estimates = !data.export_apply_estimates; + }); + }, + )); if reveals.unmatched_kept || reveals_closing.contains_key("export-unmatched-kept") { group = group.child(export_reveal( export_dependent_options( diff --git a/crates/align-gpui/src/views/mod.rs b/crates/align-gpui/src/views/mod.rs index c4e0a42..053f071 100644 --- a/crates/align-gpui/src/views/mod.rs +++ b/crates/align-gpui/src/views/mod.rs @@ -1583,6 +1583,7 @@ impl AlignApp { for (index, result) in results.iter().enumerate() { let options = ExportAssemblyOptions { unmatched: self.data.export_unmatched, + apply_estimated_placements: self.data.export_apply_estimates, prevent_group_overlaps: self.data.export_prevent_overlaps, disable_unmatched: self.data.export_disable_unmatched, label_synced: self.data.export_label_synced,