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-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/lib.rs b/crates/align-cli/src/lib.rs index 4f34d14..8eea49b 100644 --- a/crates/align-cli/src/lib.rs +++ b/crates/align-cli/src/lib.rs @@ -109,6 +109,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, @@ -944,6 +947,7 @@ mod tests { "--media-bins", "--no-fcpxml-multicam", "--export-media", + "--apply-estimated-placements", "--label-synced", "--label-unmatched", "--synced-symbol", @@ -969,6 +973,7 @@ mod tests { no_fcpxml_timeline, no_fcpxml_multicam, export_media, + apply_estimated_placements, label_synced, label_unmatched, assign, @@ -1012,6 +1017,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/fcpxml.rs b/crates/align-core/src/export/fcpxml.rs index 284180a..33d4c1e 100644 --- a/crates/align-core/src/export/fcpxml.rs +++ b/crates/align-core/src/export/fcpxml.rs @@ -1725,6 +1725,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 b9117f8..92b6546 100644 --- a/crates/align-core/src/export/model.rs +++ b/crates/align-core/src/export/model.rs @@ -139,6 +139,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 flags: crate::model::TrackFlags, @@ -195,6 +197,7 @@ impl ExportItem { mapping_rate, mapping_points, confidence, + estimated: false, corrected_audio_url: None, precision_audio_urls: Vec::new(), flags: Default::default(), @@ -500,6 +503,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, @@ -925,6 +931,17 @@ 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; + 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 +} + /// 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. @@ -992,6 +1009,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<'_> { @@ -1022,6 +1040,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() @@ -1029,7 +1048,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 @@ -1087,6 +1113,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, @@ -1237,8 +1264,38 @@ impl ExportTimeline { let mut order_only_islands = HashSet::new(); if options.unmatched != UnmatchedPlacement::Remove { + 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().enumerate() { + for (index, clip_id) in result + .unmatched + .iter() + .filter(|clip_id| !applied_estimate_ids.contains(*clip_id)) + .enumerate() + { let Some(clip) = clips_by_id.get(clip_id) else { continue; }; @@ -1294,6 +1351,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, @@ -1309,12 +1372,32 @@ impl ExportTimeline { }) .collect(), unmatched_ids: result.unmatched.iter().collect(), + estimated_ids, }; + 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. + 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() { return Err(TimelineExportError::NoImportedEdits); } @@ -1590,6 +1673,7 @@ impl ExportTimeline { duration: item.timeline_duration, confidence: item.confidence, matched: !unmatched.contains(&item.clip.id), + estimated: item.estimated, }) .collect() } @@ -1956,6 +2040,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(), }; @@ -2092,6 +2177,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(), }; @@ -2388,6 +2474,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(), } @@ -2418,11 +2505,170 @@ 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_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) + .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 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() + .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), + retime: Default::default(), + fcp7: Default::default(), + audio_source_channel: None, + fcpxml_audio_role: None, + track_index: 0, + audio_track_index: None, + flags: Default::default(), + 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_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() + .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 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/otio.rs b/crates/align-core/src/export/otio.rs index 729770e..3016f88 100644 --- a/crates/align-core/src/export/otio.rs +++ b/crates/align-core/src/export/otio.rs @@ -584,6 +584,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 742a915..438c85c 100644 --- a/crates/align-core/src/export/premiere.rs +++ b/crates/align-core/src/export/premiere.rs @@ -571,7 +571,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)), @@ -592,6 +599,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(), flags: recorder.flags, @@ -1609,6 +1617,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. @@ -2299,6 +2362,7 @@ mod tests { }], }], unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: crate::model::TemporalPolicy::default(), }; @@ -2458,6 +2522,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 fabc7f4..b9d1361 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 @@ -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 @@ -553,6 +565,7 @@ pub struct TimelinePreviewItem { pub duration: f64, pub confidence: f64, pub matched: bool, + pub estimated: bool, } /// Live match preview for progress callbacks. @@ -597,6 +610,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. @@ -653,12 +669,87 @@ impl SyncResult { }; self.islands = stage.islands.clone(); self.unmatched = stage.unmatched.clone(); + 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, @@ -1111,6 +1202,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/export.rs b/crates/align-decode/src/export.rs index e88da99..a805a62 100644 --- a/crates/align-decode/src/export.rs +++ b/crates/align-decode/src/export.rs @@ -680,10 +680,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 { @@ -1263,6 +1266,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() { diff --git a/crates/align-decode/src/pipeline.rs b/crates/align-decode/src/pipeline.rs index 6dbc918..41048fd 100644 --- a/crates/align-decode/src/pipeline.rs +++ b/crates/align-decode/src/pipeline.rs @@ -691,6 +691,17 @@ 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| { + 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); if selected_stage.is_none() { @@ -715,6 +726,7 @@ impl Pipeline { }, islands: chosen.islands, unmatched: chosen.unmatched, + estimated_placements, matches: chosen.matches, temporal_policy: options.temporal.clone(), }) @@ -1927,6 +1939,173 @@ 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 = 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")); + 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_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; + 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!( + 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!( + align_core::estimate_unmatched_by_device_timestamp( + &[anchor, filesystem.clone()], + &islands, + &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 ec10dbd..6f528d8 100644 --- a/crates/align-gpui/src/state.rs +++ b/crates/align-gpui/src/state.rs @@ -158,6 +158,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, @@ -198,6 +199,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, @@ -2212,7 +2214,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 @@ -2318,6 +2322,7 @@ mod tests { }, islands: Vec::new(), unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: Default::default(), } @@ -2562,6 +2567,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"), @@ -2967,6 +2973,7 @@ mod tests { }, islands: Vec::new(), unmatched: Vec::new(), + estimated_placements: Vec::new(), matches: Vec::new(), temporal_policy: align_core::TemporalPolicy::default(), }); @@ -3302,6 +3309,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 a494ac6..dd35d09 100644 --- a/crates/align-gpui/src/views/controls.rs +++ b/crates/align-gpui/src/views/controls.rs @@ -355,6 +355,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, } } diff --git a/crates/align-gpui/src/views/export.rs b/crates/align-gpui/src/views/export.rs index b9138ca..2d9cdfe 100644 --- a/crates/align-gpui/src/views/export.rs +++ b/crates/align-gpui/src/views/export.rs @@ -1624,6 +1624,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_estimated_placements, + "Apply unconfirmed timestamp estimates to exports".to_string(), + !busy, + |this, _, _, cx| { + this.update_export_options(cx, |data| { + data.export.apply_estimated_placements = !data.export.apply_estimated_placements; + }); + }, + )); 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 ea78f64..84020a1 100644 --- a/crates/align-gpui/src/views/mod.rs +++ b/crates/align-gpui/src/views/mod.rs @@ -1718,6 +1718,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_estimated_placements, prevent_group_overlaps: self.data.export.prevent_group_overlaps, disable_unmatched: self.data.export.disable_unmatched, label_synced: self.data.export.label_synced,