craft-timeline: craft-time is the one time model

craft-timeline's Tick, TimeRange, FrameRate, TimeDisplay, SMPTE field conversion and timecode
formatting are craft-time's, re-exported from time.rs as storytold's 5e24ea380 does, so
craft_timeline::time::* paths keep working. The timeline keeps what is about a timeline: TimeView
and VIEW_EXTENT_PAST_END, and TimeFormat as its time display (frame offset, compact feet + frames,
the audio samples and seconds readers) over craft-time's formatters and parsers. FrameRate's
locale-digit menu label is rates::frame_rate_label.

captions and edl use craft-time's field tuples, as storytold's do. The time trials that repeat
craft-time's own tests go; five that test craft-time code it did not test yet are in
crates/time/tests/timeline.rs.
This commit is contained in:
aiongg
2026-11-13 17:44:40 +00:00
parent 83e75d696a
commit 328af6782e
20 changed files with 278 additions and 1300 deletions
Generated
+1
View File
@@ -2956,6 +2956,7 @@ dependencies = [
"craft-behavior",
"craft-keymap",
"craft-theme",
"craft-time",
"craft-ui",
"craft-xml",
"egui",
+9 -8
View File
@@ -11,7 +11,7 @@
//! voices and STYLE/REGION/NOTE blocks are kept.
//! - **Byte pairs:** [`cea608`] has the CEA-608 character sets and control codes;
//! [`scc::decode_pairs`] turns a timed stream of 608 byte pairs into cues.
//! - **Time:** cue times are exact [`Tick`]s (`craft-timeline`'s). SRT/VTT milliseconds and SCC 29.97 fps
//! - **Time:** cue times are exact [`Tick`]s ([`time`]). SRT/VTT milliseconds and SCC 29.97 fps
//! timecodes (drop-frame or not) convert exactly; [`Document::snap_to_frames`] snaps to a
//! frame grid.
//! - **Limits:** input is at most [`MAX_INPUT`] bytes and a document holds at most [`MAX_CUES`]
@@ -38,12 +38,13 @@ pub mod scc;
pub mod srt;
pub mod stl;
mod text;
/// Exact time: `craft-timeline`'s ticks, frame rates and timecode fields.
pub use craft_timeline::time;
pub mod ttml;
pub mod vtt;
use craft_timeline::timecode::{TimecodeFields, fields_to_frames, frames_to_fields};
pub use craft_timeline::{FrameRate, TICKS_PER_SECOND, Tick};
pub use text::{decode_entities, entity_at, plain_text};
pub use time::{FrameRate, TICKS_PER_SECOND, Tick};
/// The creating program MCC and EBU STL files name when the caller gives none.
pub const PROGRAM: &str = "craft-captions";
@@ -165,8 +166,7 @@ pub struct Document {
/// 30 for 29.97). Negative frames read as zero.
pub fn label_time(frame: i64, rate: FrameRate, drop_frame: bool) -> Tick {
let base = rate.timecode_base();
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: f, .. } =
frames_to_fields(frame.max(0), rate, drop_frame && rate.supports_drop_frame());
let (_, h, m, s, f) = crate::time::frames_to_fields(frame.max(0), rate, drop_frame && rate.supports_drop_frame());
let seconds = h.saturating_mul(3600).saturating_add(m.saturating_mul(60)).saturating_add(s);
Tick(TICKS_PER_SECOND.saturating_mul(seconds)) + FrameRate::new(base, 1).tick_of(f)
}
@@ -176,7 +176,8 @@ pub fn label_time(frame: i64, rate: FrameRate, drop_frame: bool) -> Tick {
pub fn label_frame(label: Tick, rate: FrameRate, drop_frame: bool) -> i64 {
let nominal = FrameRate::new(rate.timecode_base(), 1);
let n = nominal.frame_at(nominal.snap_nearest(label.max(Tick::ZERO)));
fields_to_frames(frames_to_fields(n, nominal, false), rate, drop_frame && rate.supports_drop_frame())
let (_, h, m, s, f) = crate::time::frames_to_fields(n, nominal, false);
crate::time::fields_to_frames(h, m, s, f, rate, drop_frame && rate.supports_drop_frame())
}
impl Document {
@@ -559,8 +560,8 @@ mod tests {
assert_eq!(label_time(108_000, scc, false), secs(3600));
// 01:00:02:00 at 25 fps is 01:00:02;00 drop-frame and 01:00:02:00 non-drop at 29.97
let two = label_time(90_050, FrameRate::FPS_25, false);
assert_eq!(craft_timeline::timecode::format_timecode_frames(label_frame(two, scc, true), scc, true), "01;00;02;00");
assert_eq!(craft_timeline::timecode::format_timecode_frames(label_frame(two, scc, false), scc, false), "01:00:02:00");
assert_eq!(crate::time::format_timecode_frames(label_frame(two, scc, true), scc, true), "01;00;02;00");
assert_eq!(crate::time::format_timecode_frames(label_frame(two, scc, false), scc, false), "01:00:02:00");
// a frame's share of a second goes to the nearest 29.97 label frame
assert_eq!(label_frame(label_time(90_001, FrameRate::FPS_25, false), scc, false), 108_001);
// drop-frame on a rate that has none counts non-drop
+7 -8
View File
@@ -33,8 +33,7 @@
use std::collections::BTreeMap;
use craft_timeline::FrameRate;
use craft_timeline::timecode::{TimecodeFields, fields_to_frames, frames_to_fields};
use crate::time::{FrameRate, fields_to_frames, frames_to_fields};
use crate::cea608::with_parity;
use crate::{Cue, Document, Error, Result, scc};
@@ -687,7 +686,7 @@ pub fn write_padded_to(
f1: f1.next_if(|(frame, _)| *frame == f).map(|(_, pair)| pair),
dtvcc: dtv.next_if(|(frame, _)| *frame == f).map(|(_, pairs)| pairs).unwrap_or_default(),
};
let TimecodeFields { hours: hh, minutes: mm, seconds: ss, frames: ff, .. } = frames_to_fields(f.saturating_add(origin), RATE, drop_frame);
let (_, hh, mm, ss, ff) = frames_to_fields(f.saturating_add(origin), RATE, drop_frame);
let sep = if drop_frame { ';' } else { ':' };
writeln!(out, "{hh:02}:{mm:02}:{ss:02}{sep}{ff:02}\t{}", compress(&build_cdp(seq, &data)))?;
seq = seq.wrapping_add(1);
@@ -742,7 +741,7 @@ pub fn parse(text: &str) -> Result<Document> {
};
let drop_frame = rate.1 || tc.contains(';');
doc.labels.get_or_insert((rate.0, drop_frame));
let frame = fields_to_frames(TimecodeFields { negative: false, hours: *h, minutes: *m, seconds: *s, frames: *f }, rate.0, drop_frame);
let frame = fields_to_frames(*h, *m, *s, *f, rate.0, drop_frame);
let Some(bytes) = expand(data) else {
doc.warnings.push(format!("line {}: bad caption data", n + 1));
continue;
@@ -917,7 +916,7 @@ mod tests {
#[test]
fn time_codes_count_from_the_start_timecode() {
let doc = Document { cues: vec![cue(60, 120, "Caption")], ..Default::default() };
let hour = crate::Tick(3600 * crate::TICKS_PER_SECOND); // the label 01:00:00:00
let hour = crate::time::Tick(3600 * crate::time::TICKS_PER_SECOND); // the label 01:00:00:00
let master = Document { start_timecode: hour, ..doc.clone() };
let lines = |text: &str| -> Vec<(i64, String)> {
text.lines().filter_map(|l| l.split_once('\t')).map(|(tc, data)| (scc::parse_timecode(tc).unwrap(), data.to_string())).collect()
@@ -934,9 +933,9 @@ mod tests {
assert!(back.count_from(hour));
assert_eq!(back.cues, parse(&write(&doc, drop_frame)).unwrap().cues, "read back from the start time code");
}
let negative = Document { start_timecode: crate::Tick(-1), ..doc.clone() };
let negative = Document { start_timecode: crate::time::Tick(-1), ..doc.clone() };
assert_eq!(lines(&write(&negative, true)), lines(&write(&doc, true)), "a negative start counts from zero");
assert!(write(&Document { start_timecode: crate::Tick(i64::MAX), ..doc }, true).contains('\t'));
assert!(write(&Document { start_timecode: crate::time::Tick(i64::MAX), ..doc }, true).contains('\t'));
}
/// Bound output for distant or long cues near the tick limit without changing their timing.
@@ -976,7 +975,7 @@ mod tests {
let lines: Vec<(&str, &str)> = text.lines().filter_map(|line| line.split_once('\t')).collect();
assert_eq!(lines.len(), 2_000);
for (f, (tc, data)) in lines.iter().enumerate() {
let TimecodeFields { hours: hh, minutes: mm, seconds: ss, frames: ff, .. } = frames_to_fields(f as i64, RATE, drop_frame);
let (_, hh, mm, ss, ff) = frames_to_fields(f as i64, RATE, drop_frame);
let sep = if drop_frame { ';' } else { ':' };
assert_eq!(*tc, format!("{hh:02}:{mm:02}:{ss:02}{sep}{ff:02}"));
let bytes = expand(data).unwrap();
+5 -6
View File
@@ -21,8 +21,7 @@
use std::collections::BTreeMap;
use craft_timeline::timecode::{TimecodeFields, fields_to_frames, frames_to_fields};
use craft_timeline::{FrameRate, Tick};
use crate::time::{FrameRate, Tick, fields_to_frames, frames_to_fields};
use crate::cea608::{self, Encoded, misc};
use crate::{Cue, Document, Error, Result};
@@ -42,11 +41,11 @@ pub fn parse_timecode(s: &str) -> Option<i64> {
if m >= 60 || sec >= 60 || f >= 30 {
return None;
}
Some(fields_to_frames(TimecodeFields { negative: false, hours: h, minutes: m, seconds: sec, frames: f }, RATE, df))
Some(fields_to_frames(h, m, sec, f, RATE, df))
}
pub fn format_timecode(frame: i64, drop_frame: bool) -> String {
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: f, .. } = frames_to_fields(frame.max(0), RATE, drop_frame);
let (_, h, m, s, f) = frames_to_fields(frame.max(0), RATE, drop_frame);
format!("{h:02}:{m:02}:{s:02}{}{f:02}", if drop_frame { ';' } else { ':' })
}
@@ -270,7 +269,7 @@ pub fn decode_pairs(pairs: impl IntoIterator<Item = (i64, u8, u8)>, rate: FrameR
dec.pair(f, b1, b2);
last_frame = last_frame.max(f + 1);
}
let one_second = rate.frame_at(Tick(crate::TICKS_PER_SECOND)).max(1);
let one_second = rate.frame_at(Tick(crate::time::TICKS_PER_SECOND)).max(1);
if let Some((s, text)) = dec.open.take() {
let end = last_frame.max(s + 1) + one_second;
dec.cues.push((s, end, text));
@@ -580,7 +579,7 @@ mod tests {
#[test]
fn time_codes_count_from_the_start_timecode() {
let doc = Document { cues: vec![cue(60, 120, "Hello")], ..Default::default() };
let hour = Tick(3600 * crate::TICKS_PER_SECOND); // the label 01:00:00:00
let hour = Tick(3600 * crate::time::TICKS_PER_SECOND); // the label 01:00:00:00
let master = Document { start_timecode: hour, ..doc.clone() };
let lines = |text: &str| -> Vec<(i64, String)> {
text.lines().filter_map(|l| l.split_once('\t')).map(|(tc, words)| (parse_timecode(tc).unwrap(), words.to_string())).collect()
+1 -1
View File
@@ -15,7 +15,7 @@
//! (`X1:… Y2:…`), and cues not separated by a blank line (a new cue starts at a timing line, or at
//! an integer line directly followed by one). Writing renumbers from 1 and rounds to milliseconds.
use crate::Tick;
use crate::time::Tick;
use crate::{Cue, Document, Error, Result, format_clock, parse_clock};
+6 -11
View File
@@ -16,8 +16,7 @@
//! - Long subtitles continue in extension blocks; user-data (`EBN 0xFE`) and comment blocks are
//! skipped.
use craft_timeline::timecode::{TimecodeFields, fields_to_frames, frames_to_fields};
use craft_timeline::{FrameRate, Tick};
use crate::time::{FrameRate, Tick, fields_to_frames, frames_to_fields};
use crate::{Cue, Document, Error, Result};
@@ -305,11 +304,7 @@ fn tc_frames(b: &[u8], rate: FrameRate) -> Option<i64> {
if *minutes >= 60 || *seconds >= 60 || i64::from(*frames) >= max_frames {
return None;
}
Some(fields_to_frames(
TimecodeFields { negative: false, hours: *hours as i64, minutes: *minutes as i64, seconds: *seconds as i64, frames: *frames as i64 },
rate,
false,
))
Some(fields_to_frames(*hours as i64, *minutes as i64, *seconds as i64, *frames as i64, rate, false))
}
/// A subtitle being assembled from its TTI blocks: number, in and out frames, text, and whether
@@ -328,7 +323,7 @@ pub fn parse(bytes: &[u8]) -> Result<Document> {
let tcp = ascii_field(&gsi[256..264]);
let start = if tcp.len() == 8 && tcp.bytes().all(|b| b.is_ascii_digit()) {
let n = |i: usize| tcp[i..i + 2].parse::<i64>().unwrap_or(0);
fields_to_frames(TimecodeFields { negative: false, hours: n(0), minutes: n(2), seconds: n(4), frames: n(6) }, rate, false)
fields_to_frames(n(0), n(2), n(4), n(6), rate, false)
} else {
0
};
@@ -410,7 +405,7 @@ fn file_rate(rate: Option<FrameRate>) -> (FrameRate, &'static str) {
/// The time code [`write`] gives a caption starting at `t` in a programme at `rate`.
pub fn timecode(t: Tick, rate: Option<FrameRate>) -> String {
let (rate, _) = file_rate(rate);
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: f, .. } = frames_to_fields(rate.frame_at(rate.snap_nearest(t)), rate, false);
let (_, h, m, s, f) = frames_to_fields(rate.frame_at(rate.snap_nearest(t)), rate, false);
format!("{h:02}:{m:02}:{s:02}:{f:02}")
}
@@ -438,7 +433,7 @@ pub fn write(doc: &Document, rate: Option<FrameRate>, program: &str) -> Vec<u8>
b[3] = if k + 1 == chunks.len() { 0xff } else { k.min(0xfd) as u8 };
b[4] = 0;
for (at, f) in [(5, tin), (9, tout)] {
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: fr, .. } = frames_to_fields(f, rate, false);
let (_, h, m, s, fr) = frames_to_fields(f, rate, false);
b[at..at + 4].copy_from_slice(&[h.min(255) as u8, m as u8, s as u8, fr as u8]);
}
b[13] = (22 - 2 * (lines - 1)) as u8;
@@ -467,7 +462,7 @@ pub fn write(doc: &Document, rate: Option<FrameRate>, program: &str) -> Vec<u8>
put(&mut gsi, 253, 2, "23");
put(&mut gsi, 255, 1, "1");
put(&mut gsi, 256, 8, "00000000");
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: f, .. } = frames_to_fields(first_in.unwrap_or(0), rate, false);
let (_, h, m, s, f) = frames_to_fields(first_in.unwrap_or(0), rate, false);
put(&mut gsi, 264, 8, &format!("{h:02}{m:02}{s:02}{f:02}"));
put(&mut gsi, 272, 1, "1");
put(&mut gsi, 273, 1, "1");
+1 -1
View File
@@ -16,7 +16,7 @@
use std::collections::{HashMap, HashSet};
use crate::{FrameRate, TICKS_PER_SECOND, Tick};
use crate::time::{FrameRate, TICKS_PER_SECOND, Tick};
use craft_xml::{El, Limits, Node, Options, UnknownEntity};
+1 -1
View File
@@ -208,7 +208,7 @@ pub fn write(doc: &Document) -> String {
mod tests {
use super::*;
use crate::TICKS_PER_MS;
use crate::Tick;
use crate::time::Tick;
const SAMPLE: &str = "WEBVTT - with header\nKind: captions\n\nSTYLE\n::cue { color: yellow }\n\nNOTE a comment\nspanning lines\n\nintro\n00:01.000 --> 00:00:03.500 line:90% align:start\n<v.loud Ann Smith>Hello there\nsecond line\n\n00:00:04.000 --> 00:00:05.000\n<i>plain</i> &amp; tags\n";
+98
View File
@@ -0,0 +1,98 @@
use craft_time::{
FrameRate, TICKS_PER_SECOND, Tick, TimeDisplay, fields_to_frames, format_time, format_timecode_frames, frames_to_fields, parse_timecode_relative,
};
/// Overflowing fields carry into the next one before drop-frame counting, so `01;00;00;30` is the
/// frame `01;00;01;00` names rather than a non-drop count; non-drop overflow is counted as before.
#[test]
fn overflowing_drop_frame_fields_carry_before_counting() {
let df = FrameRate::FPS_29_97;
// (typed, the label it reads as)
let cases = [("01;00;00;30", "01;00;01;00"), ("00;09;59;45", "00;10;00;15"), ("00;00;90;00", "00;01;30;00"), ("01;75;00;02", "02;15;00;02")];
for (typed, label) in cases {
let f = parse_timecode_relative(typed, df, true, 0).unwrap();
assert_eq!((f, format_timecode_frames(f, df, true)), (parse_timecode_relative(label, df, true, 0).unwrap(), label.to_string()), "{typed}");
}
assert_eq!(parse_timecode_relative("00:00:00:90", FrameRate::FPS_25, false, 0).unwrap(), 90);
assert_eq!(parse_timecode_relative("00:00:00:90", df, false, 0).unwrap(), 90);
}
#[test]
fn drop_frame_fields_keep_cancelling_terms_wide_at_storage_limits() {
for rate in [FrameRate::FPS_29_97, FrameRate::FPS_59_94, FrameRate::FPS_119_88] {
for frame in [0, 1, 999_999, i64::MAX - 1, i64::MAX] {
let (negative, h, m, s, f) = frames_to_fields(frame, rate, true);
assert!(!negative);
assert_eq!(fields_to_frames(h, m, s, f, rate, true), frame, "{rate}: {frame}");
assert_eq!(fields_to_frames(-h, -m, -s, -f, rate, true), -frame);
}
let (negative, h, m, s, f) = frames_to_fields(i64::MIN, rate, true);
assert!(negative);
assert_eq!(fields_to_frames(-h, -m, -s, -f, rate, true), i64::MIN);
}
}
#[test]
fn numeric_limits_are_total_across_frame_conversion_and_display() {
let values = [i64::MIN, -i64::MAX, -1, 0, 1, TICKS_PER_SECOND, i64::MAX];
for num in values {
for den in values {
let r = FrameRate { num, den };
let _ = FrameRate::new(num, den);
let _ = r.frame_duration();
assert!(r.timecode_base() >= 1);
for value in values {
let tick = Tick(value);
let _ = r.tick_of(value);
let _ = r.frame_at(tick);
let _ = r.snap(tick);
let _ = r.snap_nearest(tick);
for display in TimeDisplay::ALL {
let _ = format_time(tick, r, true, display, 48_000);
}
let (_, h, m, s, f) = frames_to_fields(value, r, true);
let _ = fields_to_frames(h, m, s, f, r, true);
}
}
}
}
#[test]
fn rational_conversions() {
// 90 kHz MPEG timebase
let t = Tick::from_rational(90_000, 1, 90_000);
assert_eq!(t.0, TICKS_PER_SECOND);
assert_eq!(t.to_rational_floor(1, 90_000), 90_000);
assert_eq!(t.to_rational_round(1, 90_000), 90_000);
// 1 ms timebase (Matroska): to the nearest millisecond, halves up
let ms = |t: Tick| t.to_rational_round(1, 1000);
assert_eq!(ms(FrameRate::FPS_30.tick_of(1)), 33);
assert_eq!(ms(FrameRate::FPS_30.tick_of(2)), 67);
assert_eq!(FrameRate::FPS_30.tick_of(2).to_rational_floor(1, 1000), 66);
assert_eq!(ms(FrameRate::FPS_29_97.tick_of(15)), 501, "500.5 ms");
assert_eq!(ms(Tick::from_rational(-4, 1, 10_000)), 0, "-0.4 ms");
assert_eq!(ms(Tick::from_rational(-5, 1, 10_000)), 0, "-0.5 ms");
assert_eq!(ms(Tick::from_rational(-6, 1, 10_000)), -1, "-0.6 ms");
// a negative timebase is nonsense, but rounds the same way
assert_eq!(FrameRate::FPS_30.tick_of(2).to_rational_round(-1, -1000), 67);
assert_eq!(FrameRate::FPS_29_97.tick_of(15).to_rational_round(-1, -1000), 501);
assert_eq!(FrameRate::from_f64(29.97), FrameRate::FPS_29_97);
}
/// At 11 fps a frame is not a whole number of ticks, so the ticks from one boundary to the next
/// can read as zero frames; counting between frame indices gives one.
#[test]
fn frames_between_counts_boundaries_at_fractional_tick_rates() {
let r = FrameRate::new(11, 1);
for f in 0..1000 {
for n in 1..=12 {
let (a, b) = (r.tick_of(f), r.tick_of(f + n));
assert_eq!(r.frames_between(a, b), n, "frames {f}..{}", f + n);
}
}
assert_eq!(r.frame_at(Tick(r.tick_of(2).0 - r.tick_of(1).0)), 0, "the length alone reads one short");
// frame indices that span the whole integer range saturate instead of overflowing
let fast = FrameRate::new(i64::MAX, 1);
assert_eq!(fast.frames_between(Tick(i64::MIN), Tick(i64::MAX)), i64::MAX);
assert_eq!(fast.frames_between(Tick(i64::MAX), Tick(i64::MIN)), i64::MIN);
}
+1
View File
@@ -30,6 +30,7 @@ otio = ["dep:serde_json"]
[dependencies]
craft-behavior = { workspace = true, optional = true }
craft-keymap = { workspace = true, optional = true }
craft-time = { workspace = true }
craft-theme = { workspace = true, optional = true }
craft-ui = { workspace = true, optional = true }
craft-xml = { workspace = true, optional = true }
+3 -3
View File
@@ -4,9 +4,9 @@ Timelines for Craft apps, from FilmCraft (Premiere Pro), EffectCraft (After Effe
The core is egui-free:
- `time`: `Tick` (254,016,000,000 per second, exact for every broadcast frame rate and common sample rate), `TimeRange`, and `TimeView` (the time-to-pixel map with zoom and scroll).
- `rates`: `FrameRate` (rational), `SampleRate`, `PixelAspect` and their menu presets.
- `timecode`: SMPTE timecode (drop and non-drop), frames, feet + frames, samples and seconds, formatted and parsed the way Premiere's fields do, as ticks (`parse_time`) or frame counts (`parse_frames`).
- `time`: `TimeView` (the time-to-pixel map with zoom and scroll), and craft-time's `Tick` (254,016,000,000 per second, exact for every broadcast frame rate and common sample rate), `TimeRange` and timecode primitives, re-exported.
- `rates`: craft-time's `FrameRate` (rational), `SampleRate`, `PixelAspect` and their menu presets.
- `timecode`: `TimeFormat`, the timeline's time display: SMPTE timecode (drop and non-drop), frames, feet + frames, samples and seconds, formatted and parsed the way Premiere's fields do, as ticks (`parse_time`) or frame counts (`parse_frames`), on craft-time's conversions.
- `clock`: `PlaybackClock` (play, stop, preroll, loop, stop point, an external audio clock) and `Follow` (the view follows the playhead while playing).
- `cache` and `frames`: a byte-budgeted `FrameCache` that spares the frames a playing preview reaches next, and a `FrameServer` that renders frames on worker threads by priority with playback prefetch (on wasm, `pump` runs them on the UI thread).
- `clips`: clip edges, trims and snapping rules; `markers`: timeline markers; `model`: the `TimelineModel` trait the app implements on its sequence.
+10 -11
View File
@@ -16,7 +16,7 @@ use std::collections::BTreeSet;
use crate::rates::FrameRate;
use crate::report::Report;
use crate::timecode::{TimecodeFields, fields_to_frames, format_timecode_frames};
use crate::time::{fields_to_frames, format_timecode_frames};
/// Heuristic: does this text look like an EDL?
pub fn looks_like_edl(text: &str) -> bool {
@@ -29,7 +29,10 @@ pub fn looks_like_edl(text: &str) -> bool {
/// A timecode as written: its four fields, and whether its separators say drop-frame (`;` or `,`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Timecode {
pub fields: TimecodeFields,
pub h: i64,
pub m: i64,
pub s: i64,
pub f: i64,
pub df: bool,
}
@@ -40,8 +43,7 @@ pub fn parse_tc(s: &str) -> Option<Timecode> {
return None;
}
let n: Vec<i64> = parts.iter().map(|p| p.parse().ok()).collect::<Option<_>>()?;
let fields = TimecodeFields { negative: false, hours: n[0], minutes: n[1], seconds: n[2], frames: n[3] };
Some(Timecode { fields, df: s.contains(';') || s.contains(',') })
Some(Timecode { h: n[0], m: n[1], s: n[2], f: n[3], df: s.contains(';') || s.contains(',') })
}
/// The edit type of an event line (`C`, `D`, `Wnnn`, `K B`, `K`, `K O`).
@@ -238,7 +240,7 @@ pub fn parse(text: &str, report: &mut Report) -> Edl {
}
if let Some(line) = parse_event_line(l) {
for tc in &line.tcs {
p.max_ff = p.max_ff.max(tc.fields.frames);
p.max_ff = p.max_ff.max(tc.f);
p.any_df |= tc.df;
}
if let Some(e) = p.events.last_mut().filter(|e| !skip_metadata && e.lines.last().is_some_and(|last| last.num == line.num)) {
@@ -281,7 +283,7 @@ impl Timecode {
/// The frame count at `rate`; drop-frame when the timecode's separators or `drop_frame` (the
/// `FCM:` in force) say so and the rate has drop-frame timecode.
pub fn frames(self, rate: FrameRate, drop_frame: bool) -> i64 {
fields_to_frames(self.fields, rate, self.df || drop_frame)
fields_to_frames(self.h, self.m, self.s, self.f, rate, self.df || drop_frame)
}
}
@@ -431,10 +433,7 @@ mod tests {
for tc in ["9223372036854775808:00:00:00", "00:9223372036854775808:00:00", "00:00:9223372036854775808:00", "00:00:00:9223372036854775808"] {
assert!(parse_tc(tc).is_none(), "accepted {tc}");
}
assert_eq!(
parse_tc("01:02:03:04"),
Some(Timecode { fields: TimecodeFields { negative: false, hours: 1, minutes: 2, seconds: 3, frames: 4 }, df: false })
);
assert_eq!(parse_tc("01:02:03:04"), Some(Timecode { h: 1, m: 2, s: 3, f: 4, df: false }));
}
#[trial]
@@ -529,7 +528,7 @@ AUD 2\n\
fn locators_take_a_colour_word_only_from_the_known_set() {
let text = "001 AX V C 00:00:00:00 00:00:01:00 01:00:00:00 01:00:01:00\n* LOC: 01:00:00:10 red Slate\n* LOC: 01:00:00:20 Take two\n";
let edl = parse(text, &mut Report::default());
let locs: Vec<(i64, &str, &str)> = edl.events[0].locs.iter().map(|(t, c, n)| (t.fields.frames, c.as_str(), n.as_str())).collect();
let locs: Vec<(i64, &str, &str)> = edl.events[0].locs.iter().map(|(t, c, n)| (t.f, c.as_str(), n.as_str())).collect();
assert_eq!(locs, [(10, "red", "Slate"), (20, "", "Take two")]);
}
+1 -1
View File
@@ -784,7 +784,7 @@ impl Exp<'_, '_> {
let id = self.rid();
self.res_out.push(format!(
" <format id=\"{id}\" name=\"FFVideoFormat{h}p{}\" frameDuration=\"{}/{}s\" width=\"{w}\" height=\"{h}\"/>\n",
rate.to_string().replace('.', ""),
rate.label().replace('.', ""),
rate.den,
rate.num
));
+1 -3
View File
@@ -65,7 +65,7 @@ pub use model::{ClipId, ClipInfo, TimelineModel, TrackId, TrackInfo, TrackKind};
pub use rates::{FrameRate, PixelAspect, SampleRate};
pub use report::{Level, Report, ReportEntry};
pub use time::{TICKS_PER_SECOND, Tick, TimeRange, TimeView};
pub use timecode::{TimeDisplay, TimeFormat, TimecodeError, TimecodeFields, format_time, parse_frames, parse_time};
pub use timecode::{TimeDisplay, TimeFormat, TimecodeError, format_time, parse_frames, parse_time};
#[cfg(test)]
mod cache_tests;
@@ -76,8 +76,6 @@ mod clock_tests;
#[cfg(test)]
mod frames_tests;
#[cfg(test)]
mod rates_tests;
#[cfg(test)]
mod time_tests;
#[cfg(test)]
mod timecode_tests;
+11 -223
View File
@@ -2,205 +2,20 @@
//! menus offer (Premiere's sequence settings, After Effects' composition settings, Pro Tools'
//! session rates).
use crate::time::{TICKS_PER_SECOND, Tick};
use crate::time::Tick;
/// A frame rate as an exact rational, `num / den` frames a second. Rates come from files, so
/// every frame computation goes through [`sane`](Self::sane) and a zero or negative rate counts
/// as the default (23.976, as FilmCraft).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct FrameRate {
/// The numerator: frames in `den` seconds.
pub num: i64,
/// The denominator: seconds that `num` frames take.
pub den: i64,
}
pub use craft_time::FrameRate;
impl Default for FrameRate {
fn default() -> Self {
Self::FPS_23_976
}
}
impl FrameRate {
/// 23.976 frames a second (24000/1001).
pub const FPS_23_976: FrameRate = FrameRate::new(24000, 1001);
#[allow(missing_docs)]
pub const FPS_24: FrameRate = FrameRate::new(24, 1);
#[allow(missing_docs)]
pub const FPS_25: FrameRate = FrameRate::new(25, 1);
/// 29.97 frames a second (30000/1001).
pub const FPS_29_97: FrameRate = FrameRate::new(30000, 1001);
#[allow(missing_docs)]
pub const FPS_30: FrameRate = FrameRate::new(30, 1);
#[allow(missing_docs)]
pub const FPS_48: FrameRate = FrameRate::new(48, 1);
#[allow(missing_docs)]
pub const FPS_50: FrameRate = FrameRate::new(50, 1);
/// 59.94 frames a second (60000/1001).
pub const FPS_59_94: FrameRate = FrameRate::new(60000, 1001);
#[allow(missing_docs)]
pub const FPS_60: FrameRate = FrameRate::new(60, 1);
/// 119.88 frames a second (120000/1001).
pub const FPS_119_88: FrameRate = FrameRate::new(120000, 1001);
#[allow(missing_docs)]
pub const FPS_120: FrameRate = FrameRate::new(120, 1);
/// The rates a frame-rate menu offers, in Premiere's order.
pub const COMMON: [FrameRate; 11] = [
Self::FPS_23_976,
Self::FPS_24,
Self::FPS_25,
Self::FPS_29_97,
Self::FPS_30,
Self::FPS_48,
Self::FPS_50,
Self::FPS_59_94,
Self::FPS_60,
Self::FPS_119_88,
Self::FPS_120,
];
/// `num / den` reduced by their greatest common divisor.
// filmcraft: crates/time/src/lib.rs:198 (i128 division by the gcd, at least 1).
pub const fn new(num: i64, den: i64) -> Self {
let mut g = gcd(num.unsigned_abs(), den.unsigned_abs()) as i128;
if g < 1 {
g = 1;
}
FrameRate { num: (num as i128 / g) as i64, den: (den as i128 / g) as i64 }
}
/// The [`COMMON`](Self::COMMON) rate within 0.005 fps of `fps` (a container's average rate),
/// else `round(fps × 1000) / 1000`.
// filmcraft: crates/time/src/lib.rs:204.
pub fn from_f64(fps: f64) -> Self {
if let Some(r) = Self::COMMON.into_iter().find(|r| (r.as_f64() - fps).abs() < 0.005) {
return r;
}
FrameRate::new((fps * 1000.0).round() as i64, 1000)
}
/// The [`COMMON`](Self::COMMON) rate nearest `fps` when it is within `tolerance` of it, as a
/// fraction of the rate (`0.005` is half a percent), else [`from_f64`](Self::from_f64). A
/// container that reports its rate from timestamps rounded to a coarse unit lands slightly off
/// a standard rate: at 90 kHz, whole milliseconds leave a 30 fps clip's average at 30.02 or
/// 29.95.
// filmcraft: crates/time/src/lib.rs:217 (#1700).
pub fn from_f64_within(fps: f64, tolerance: f64) -> Self {
let mut best: Option<(f64, FrameRate)> = None;
for r in Self::COMMON {
let off = (r.as_f64() - fps).abs();
if off <= tolerance * r.as_f64() && best.is_none_or(|(closest, _)| off < closest) {
best = Some((off, r));
}
}
best.map_or_else(|| Self::from_f64(fps), |(_, r)| r)
}
/// This rate when both parts are positive, else the default.
pub fn sane(self) -> FrameRate {
if self.num > 0 && self.den > 0 { self } else { FrameRate::default() }
}
/// The rate in frames a second.
pub fn as_f64(self) -> f64 {
self.num as f64 / self.den as f64
}
/// One frame's exact duration (floored only for exotic rates); saturates at the tick range.
// filmcraft: crates/time/src/lib.rs:225 (`TICKS_PER_SECOND * den / num` in i128).
pub fn frame_duration(self) -> Tick {
let r = self.sane();
Tick(clamp_i64(i128::from(TICKS_PER_SECOND) * i128::from(r.den) / i128::from(r.num)))
}
/// The index of the frame holding `t` (floor), saturated to the frame range.
// filmcraft: crates/time/src/lib.rs:231 (`frame_index`: `t * num / (TICKS_PER_SECOND * den)`
// with `div_euclid` in i128).
pub fn frame_at(self, t: Tick) -> i64 {
clamp_i64(frame_index(self.sane(), t))
}
/// Frames from `start` to `end`, counted between their frame indices. `frame_at(end - start)`
/// can read one short when a frame is not a whole number of ticks: the ticks between two
/// boundaries can be one fewer than the exact length of those frames.
pub fn frames_between(self, start: Tick, end: Tick) -> i64 {
self.frame_at(end).saturating_sub(self.frame_at(start))
}
/// The first tick of frame `f`, by ceiling division, so `frame_at(tick_of(f)) == f` holds
/// for every rate with at least one tick per frame (37.516 fps included: flooring drifts each
/// boundary back a tick and frame stepping stalls).
// filmcraft: crates/time/src/lib.rs:244 (`frame_boundary`).
pub fn tick_of(self, f: i64) -> Tick {
Tick(clamp_i64(frame_boundary(self.sane(), i128::from(f))))
}
/// `t` moved down to its frame's first tick.
// filmcraft: crates/time/src/lib.rs:249.
pub fn snap(self, t: Tick) -> Tick {
let r = self.sane();
Tick(clamp_i64(frame_boundary(r, frame_index(r, t))))
}
/// `t` moved to the nearest frame boundary (the earlier one at the exact middle); both
/// boundaries are compared in i128 before saturating.
// filmcraft: crates/time/src/lib.rs:255.
pub fn snap_nearest(self, t: Tick) -> Tick {
let r = self.sane();
// Both boundaries stay wide until compared: saturating an unrepresentable upper one first
// would make it look closer than it is.
let f = frame_index(r, t);
let a = frame_boundary(r, f);
let b = frame_boundary(r, f.saturating_add(1));
let t = i128::from(t.0);
Tick(clamp_i64(if t - a <= b - t { a } else { b }))
}
/// Frames counted per timecode second: 30 for 29.97, 24 for 23.976 (`num / den` rounded up,
/// at least 1).
// filmcraft: crates/time/src/lib.rs:267.
pub fn timecode_base(self) -> i64 {
let r = self.sane();
(r.num / r.den).saturating_add(i64::from(r.num % r.den != 0)).max(1)
}
/// An NTSC (x/1001) rate.
pub fn is_ntsc(self) -> bool {
self.den == 1001
}
/// Whether drop-frame counting applies: NTSC rates with a base that is a multiple of 30
/// (29.97, 59.94, 119.88).
// filmcraft: crates/time/src/lib.rs:278.
pub fn supports_drop_frame(self) -> bool {
self.is_ntsc() && self.timecode_base() % 30 == 0
}
/// The menu label without the unit: `24`, `23.976`, `29.97` (up to three decimals, in the
/// locale's digits and decimal mark). The unit ("fps") is the menu's word.
// filmcraft: crates/time/src/lib.rs:282.
#[cfg(feature = "ui")]
pub fn label(self, numbers: &craft_ui::runtime::env::Units) -> String {
if self.den == 1 {
return numbers.number(self.num as f64, 0..=0);
}
numbers.number(self.as_f64(), 0..=3)
}
}
/// The rate as documents and diagnostics write it: `24`, `23.976`, `29.97` (ASCII digits, up to
/// three decimals, no unit). Text a person reads in the UI comes from `label`, in the locale's
/// digits, with the unit as the UI's word.
impl std::fmt::Display for FrameRate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.den == 1 {
return write!(f, "{}", self.num);
}
let s = format!("{:.3}", self.as_f64());
f.write_str(s.trim_end_matches('0').trim_end_matches('.'))
/// A frame rate's menu label without the unit: `24`, `23.976`, `29.97` (up to three decimals, in
/// the locale's digits and decimal mark). The unit ("fps") is the menu's word;
/// [`FrameRate::label`] is the ASCII form documents write.
// filmcraft: crates/time/src/lib.rs:282.
#[cfg(feature = "ui")]
pub fn frame_rate_label(rate: FrameRate, numbers: &craft_ui::runtime::env::Units) -> String {
if rate.den == 1 {
return numbers.number(rate.num as f64, 0..=0);
}
numbers.number(rate.as_f64(), 0..=3)
}
/// An audio sample rate in hertz.
@@ -299,30 +114,3 @@ impl PixelAspect {
numbers.number(self.as_f64(), 4..=4)
}
}
/// Narrows after applying the storage bounds, never by a wrapping cast.
fn clamp_i64(value: i128) -> i64 {
value.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
}
/// The frame holding `t`, for a positive rate.
fn frame_index(rate: FrameRate, t: Tick) -> i128 {
(i128::from(t.0) * i128::from(rate.num)).div_euclid(i128::from(TICKS_PER_SECOND) * i128::from(rate.den))
}
/// The ceiling of a frame's rational start. An overflowing numerator over an `i64` rate cannot
/// fit a tick, so saturating it keeps the public result.
fn frame_boundary(rate: FrameRate, frame: i128) -> i128 {
let Some(n) = frame.checked_mul(i128::from(TICKS_PER_SECOND)).and_then(|n| n.checked_mul(i128::from(rate.den))) else {
return if frame < 0 { i128::MIN } else { i128::MAX };
};
let d = i128::from(rate.num);
n.div_euclid(d) + i128::from(n.rem_euclid(d) != 0)
}
const fn gcd(mut a: u64, mut b: u64) -> u64 {
while b != 0 {
(a, b) = (b, a % b);
}
a
}
-17
View File
@@ -1,17 +0,0 @@
//! Frame rates, sample rates and pixel aspect ratios.
use crate::rates::FrameRate;
use crate::time::{TICKS_PER_SECOND, Tick};
use craft_ui::testing::trial;
#[trial]
fn frame_boundaries_round_trip_at_every_rate() {
for rate in FrameRate::COMMON.into_iter().chain([FrameRate::new(37_516, 1000)]) {
for f in [-1000, -1, 0, 1, 2, 29, 1799, 1_000_003] {
assert_eq!(rate.frame_at(rate.tick_of(f)), f, "{rate:?} frame {f}");
assert_eq!(rate.frame_at(rate.tick_of(f) - Tick(1)), f - 1, "{rate:?} before frame {f}");
}
}
assert_eq!(FrameRate::FPS_25.frame_duration(), Tick(TICKS_PER_SECOND / 25));
assert_eq!(FrameRate::new(48, 2), FrameRate::new(24, 1));
}
+8 -201
View File
@@ -1,203 +1,18 @@
//! Exact media time: [`Tick`], [`TimeRange`] and the time-to-pixel map [`TimeView`].
//!
//! [`TICKS_PER_SECOND`] (Premiere's tick) divides evenly into every broadcast frame duration
//! (23.976 … 120 fps, NTSC rates included) and every sample duration of 8 kHz … 384 kHz, so
//! FilmCraft's frames, EffectCraft's comp frames and SoundCraft's samples all convert exactly
//! (`Tick::from_units(samples, 48_000)`). Every conversion is total: a zero or negative rate gives
//! zero, never a division-by-zero panic.
//! Exact media time: craft-time's [`Tick`], [`TimeRange`] and frame and timecode primitives,
//! re-exported so `craft_timeline::time::*` paths keep working, and the timeline's time-to-pixel
//! map [`TimeView`].
use std::ops::{Add, AddAssign, Neg, Sub, SubAssign};
/// Ticks per second.
pub const TICKS_PER_SECOND: i64 = 254_016_000_000;
pub use crate::timecode::format_feet_frames;
pub use craft_time::{
FrameRate, ParseError, SAMPLE_RATES, TICKS_PER_SECOND, Tick, TimeDisplay, TimeRange, fields_to_frames, format_timecode_frames, frames_to_fields,
parse_time_display_relative as parse_time_display, parse_timecode_relative as parse_timecode,
};
/// How far past the end of the content a timeline view reaches: ten minutes, as Premiere's
/// Timeline does (on a 6 s sequence its view stops with 00:10:06 at the right edge). The view
/// cannot be scrolled past it and the scroll bar spans it.
pub const VIEW_EXTENT_PAST_END: Tick = Tick(600 * TICKS_PER_SECOND);
/// A point or a duration in time, in ticks. Arithmetic saturates at the `i64` limits;
/// representable results stay exact.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct Tick(pub i64);
impl Tick {
/// Time zero.
pub const ZERO: Tick = Tick(0);
/// The latest time any widget accepts; a quarter of the storage range, so sums of two stay
/// representable.
pub const MAX: Tick = Tick(i64::MAX / 4);
/// The earliest time any widget accepts; the negative counterpart of [`Tick::MAX`].
pub const MIN: Tick = Tick(i64::MIN / 4);
/// `s` seconds, rounded to the nearest tick.
// filmcraft: crates/time/src/lib.rs:33 (`(s * TICKS_PER_SECOND).round()`; a non-finite `s`
// gives zero here, FilmCraft's cast saturates).
pub fn from_seconds_f64(s: f64) -> Tick {
Tick(if s.is_finite() { (s * TICKS_PER_SECOND as f64).round() as i64 } else { 0 })
}
/// The time in seconds.
pub fn seconds(self) -> f64 {
self.0 as f64 / TICKS_PER_SECOND as f64
}
/// Exact conversion from a count of `units` at `per_second` (samples at 48,000; frames at a
/// whole rate). Zero when `per_second` is zero.
// filmcraft: crates/time/src/lib.rs:40 (i128 product, checked division, clamped to i64).
pub fn from_units(units: i64, per_second: i64) -> Tick {
Tick(clamp_i64((i128::from(units) * i128::from(TICKS_PER_SECOND)).checked_div(i128::from(per_second)).unwrap_or(0)))
}
/// The count of whole units at `per_second` before this time (floor, also for negative times).
// filmcraft: crates/time/src/lib.rs:44 (`div_euclid`).
pub fn to_units_floor(self, per_second: i64) -> i64 {
clamp_i64((i128::from(self.0) * i128::from(per_second)).div_euclid(i128::from(TICKS_PER_SECOND)))
}
/// The time of a rational timestamp `pts × num / den` seconds (a container timebase). Zero
/// when `den` is zero; a product past `i128` saturates to the sign's limit.
// filmcraft: crates/time/src/lib.rs:48.
pub fn from_rational(pts: i64, num: i64, den: i64) -> Tick {
if den == 0 {
return Tick::ZERO;
}
let Some(t) = (i128::from(pts) * i128::from(num)).checked_mul(i128::from(TICKS_PER_SECOND)) else {
return Tick(if (pts < 0) ^ (num < 0) ^ (den < 0) { i64::MIN } else { i64::MAX });
};
Tick(clamp_i64(t.div_euclid(i128::from(den))))
}
/// The inverse of [`Tick::from_rational`], floored to the timebase.
// filmcraft: crates/time/src/lib.rs:59.
pub fn to_rational_floor(self, num: i64, den: i64) -> i64 {
clamp_i64((i128::from(self.0) * i128::from(den)).checked_div_euclid(i128::from(num) * i128::from(TICKS_PER_SECOND)).unwrap_or(0))
}
/// The inverse of [`Tick::from_rational`], rounded to the nearest unit (halves up): containers
/// store timestamps rounded to their timebase, so flooring misses frames stamped half a unit
/// late.
// filmcraft: crates/time/src/lib.rs:67.
pub fn to_rational_round(self, num: i64, den: i64) -> i64 {
let n = i128::from(self.0) * i128::from(den);
let unit = i128::from(num) * i128::from(TICKS_PER_SECOND);
let (n, unit) = if unit < 0 { (-n, -unit) } else { (n, unit) };
let (Some(q), Some(r)) = (n.checked_div_euclid(unit), n.checked_rem_euclid(unit)) else {
return 0;
};
clamp_i64(if r * 2 >= unit { q + 1 } else { q })
}
/// Scaled by `num / den`, floored; zero when `den` is zero.
// filmcraft: crates/time/src/lib.rs:89.
pub fn mul_ratio(self, num: i64, den: i64) -> Tick {
Tick(clamp_i64((i128::from(self.0) * i128::from(num)).checked_div_euclid(i128::from(den)).unwrap_or(0)))
}
/// The absolute value; saturates at the maximum.
pub fn abs(self) -> Tick {
Tick(self.0.saturating_abs())
}
/// The earlier of two times.
pub fn min(self, o: Tick) -> Tick {
Tick(self.0.min(o.0))
}
/// The later of two times.
pub fn max(self, o: Tick) -> Tick {
Tick(self.0.max(o.0))
}
/// Clamped to `lo..=hi`; never panics when the bounds cross (`hi` wins).
pub fn clamp(self, lo: Tick, hi: Tick) -> Tick {
Tick(self.0.max(lo.0).min(hi.0))
}
}
impl Add for Tick {
type Output = Tick;
fn add(self, o: Tick) -> Tick {
Tick(self.0.saturating_add(o.0))
}
}
impl Sub for Tick {
type Output = Tick;
fn sub(self, o: Tick) -> Tick {
Tick(self.0.saturating_sub(o.0))
}
}
impl Neg for Tick {
type Output = Tick;
fn neg(self) -> Tick {
Tick(self.0.saturating_neg())
}
}
impl AddAssign for Tick {
fn add_assign(&mut self, o: Tick) {
self.0 = self.0.saturating_add(o.0);
}
}
impl SubAssign for Tick {
fn sub_assign(&mut self, o: Tick) {
self.0 = self.0.saturating_sub(o.0);
}
}
/// A half-open range `[start, start + duration)`. A zero or negative duration is empty and
/// overlaps nothing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct TimeRange {
/// The first tick in the range.
pub start: Tick,
/// The length; zero or negative makes the range empty.
pub duration: Tick,
}
impl TimeRange {
/// A range from `start` lasting `duration`.
pub fn new(start: Tick, duration: Tick) -> Self {
Self { start, duration }
}
/// A range from `start` up to, not including, `end`.
pub fn from_bounds(start: Tick, end: Tick) -> Self {
Self { start, duration: end - start }
}
/// The first tick after the range.
pub fn end(&self) -> Tick {
self.start + self.duration
}
/// Whether the range has zero or negative duration.
pub fn is_empty(&self) -> bool {
self.duration.0 <= 0
}
/// Whether `t` lies in `[start, end)`.
pub fn contains(&self, t: Tick) -> bool {
t >= self.start && t < self.end()
}
/// Whether both ranges are non-empty and share at least one tick.
pub fn overlaps(&self, o: &TimeRange) -> bool {
!self.is_empty() && !o.is_empty() && self.start < o.end() && o.start < self.end()
}
/// The common part, `None` when it is empty.
pub fn intersect(&self, o: &TimeRange) -> Option<TimeRange> {
let s = self.start.max(o.start);
let e = self.end().min(o.end());
(e > s).then(|| TimeRange::from_bounds(s, e))
}
}
/// How a timeline shows time: the time at its left edge and its zoom in points per second. The
/// app keeps one per sequence (Premiere's sequence tabs each keep theirs) and saves it beside the
/// document, never in its undo history.
@@ -314,11 +129,3 @@ impl TimeView {
/// The latest start [`TimeView::checked`] accepts, in seconds.
const MAX_START_SECONDS: i64 = 10_000_000;
/// Narrows after applying the storage bounds, never by a wrapping cast.
fn clamp_i64(value: i128) -> i64 {
value.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
}
#[cfg(test)]
mod tests;
-550
View File
@@ -1,550 +0,0 @@
use super::*;
use crate::rates::{FrameRate, SampleRate};
use crate::timecode::{
TimeDisplay, TimeFormat, TimecodeFields, fields_to_frames, format_feet_frames, format_time, format_timecode_frames, frames_to_fields,
parse_frames,
};
use craft_ui::testing::trial;
use proptest::prelude::*;
#[trial]
fn empty_time_ranges_never_overlap() {
let clip = TimeRange::new(Tick(0), Tick(10));
for duration in [0, -1, -5] {
let empty = TimeRange::new(Tick(5), Tick(duration));
assert!(empty.is_empty());
assert_eq!(empty.intersect(&clip), None);
assert!(!empty.overlaps(&clip), "duration {duration}");
assert!(!clip.overlaps(&empty), "duration {duration}");
}
}
#[trial]
fn time_range_overlap_respects_half_open_boundaries() {
let clip = TimeRange::new(Tick(0), Tick(10));
for (start, duration, expected) in [(-5, 5, false), (10, 5, false), (-5, 6, true), (9, 5, true), (2, 3, true)] {
let other = TimeRange::new(Tick(start), Tick(duration));
assert_eq!(clip.overlaps(&other), expected);
assert_eq!(other.overlaps(&clip), expected);
}
}
#[trial]
fn seconds_display_has_no_negative_zero() {
let f = |t: i64| format_time(Tick(t), &TimeFormat::timecode(FrameRate::default()).drop_frame(false).display(TimeDisplay::Seconds));
assert_eq!(f(-1), "0.000");
assert_eq!(f(-2), "0.000");
assert_eq!(f(-(TICKS_PER_SECOND / 2500)), "0.000");
assert_eq!(f(-TICKS_PER_SECOND), "-1.000");
assert_eq!(f(-TICKS_PER_SECOND / 1000), "-0.001");
}
#[trial]
fn audio_samples_negative_time_has_leading_minus() {
let r = FrameRate::new(30000, 1001);
let f = |t| format_time(Tick(t), &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::AudioSamples));
assert_eq!(f(-TICKS_PER_SECOND), "-00:00:01:00000");
assert_eq!(f(-(TICKS_PER_SECOND + TICKS_PER_SECOND / 2)), "-00:00:01:24000");
}
/// Damaged files and projects can carry zero / negative rates and timebases, and users or
/// agents can type huge timecodes: these used to panic (division by zero, overflow,
/// crossed `clamp` bounds).
#[trial]
fn hostile_rates_and_timecodes_never_panic() {
let zero = FrameRate { num: 0, den: 0 };
for r in [
zero,
FrameRate { num: 0, den: 1 },
FrameRate { num: 25, den: 0 },
FrameRate { num: -30, den: 1 },
FrameRate::from_f64(0.0),
FrameRate::from_f64(f64::NAN),
] {
assert_eq!(r.tick_of(10), FrameRate::default().tick_of(10));
assert_eq!(r.frame_at(Tick(TICKS_PER_SECOND)), FrameRate::default().frame_at(Tick(TICKS_PER_SECOND)));
assert!(r.frame_duration() > Tick::ZERO);
assert!(r.timecode_base() >= 1);
let _ = r.snap_nearest(Tick(12345));
let _ = format_time(Tick(TICKS_PER_SECOND), &TimeFormat::timecode(r).drop_frame(true).display(TimeDisplay::Timecode));
}
assert_eq!(Tick::from_rational(100, 1, 0), Tick::ZERO);
assert_eq!(Tick::from_units(100, 0), Tick::ZERO);
assert_eq!(Tick(5).to_rational_floor(0, 1), 0);
assert_eq!(Tick(5).to_rational_round(0, 1), 0);
for t in [i64::MIN, -1, 0, 1, i64::MAX] {
for (n, d) in [(i64::MIN, 1), (-1, 1000), (1, i64::MAX), (i64::MAX, i64::MIN), (1, 0)] {
let _ = Tick(t).to_rational_round(n, d);
}
}
assert_eq!(Tick(5).mul_ratio(1, 0), Tick::ZERO);
assert_eq!(Tick(5).clamp(Tick(10), Tick(0)), Tick(0));
let _ = format_timecode_frames(i64::MIN, FrameRate::FPS_29_97, true);
for tc in ["99999999999:99:99:99", "9223372036854775807", "+9223372036854775807", "99999999999;59;59;29"] {
let _ = parse_frames(tc, &TimeFormat::timecode(FrameRate::FPS_29_97).drop_frame(true), i64::MAX);
let _ = parse_frames(tc, &TimeFormat::timecode(FrameRate::FPS_25).drop_frame(false), i64::MIN);
}
}
#[trial]
fn boundary_rates_saturate_without_wrapping_and_keep_representable_values_exact() {
let slow = FrameRate { num: 1, den: i64::MAX };
assert_eq!(slow.frame_duration(), Tick(i64::MAX));
assert_eq!(slow.tick_of(i64::MAX), Tick(i64::MAX));
assert_eq!(slow.tick_of(i64::MIN), Tick(i64::MIN));
assert_eq!(slow.snap_nearest(Tick(i64::MAX)), Tick::ZERO, "compare the real boundary before saturating");
assert_eq!(slow.snap_nearest(Tick(i64::MIN)), Tick::ZERO);
let fast = FrameRate { num: i64::MAX, den: 1 };
assert_eq!(fast.tick_of(i64::MAX), Tick(TICKS_PER_SECOND), "large factors can cancel exactly");
assert_eq!(fast.tick_of(-i64::MAX), Tick(-TICKS_PER_SECOND));
assert_eq!(fast.frame_at(Tick(TICKS_PER_SECOND)), i64::MAX);
assert_eq!(fast.frame_at(Tick(i64::MAX)), i64::MAX);
assert_eq!(fast.frame_at(Tick(i64::MIN)), i64::MIN);
assert_eq!(fast.timecode_base(), i64::MAX);
for t in [i64::MIN, -TICKS_PER_SECOND, -1, 0, 1, TICKS_PER_SECOND, i64::MAX] {
assert_eq!(fast.snap(Tick(t)), Tick(t), "sub-tick frames include every integer tick");
assert_eq!(fast.snap_nearest(Tick(t)), Tick(t));
}
let balanced = FrameRate { num: i64::MAX, den: i64::MAX };
assert_eq!(balanced.frame_duration(), Tick(TICKS_PER_SECOND));
assert_eq!(balanced.tick_of(2), Tick(2 * TICKS_PER_SECOND));
assert_eq!(balanced.frame_at(Tick(2 * TICKS_PER_SECOND)), 2);
assert_eq!(balanced.timecode_base(), 1);
assert_eq!(FrameRate::new(i64::MIN, i64::MIN), FrameRate { num: -1, den: -1 });
assert_eq!(FrameRate::new(i64::MIN, 0), FrameRate { num: -1, den: 0 });
assert_eq!(FrameRate::new(i64::MIN, 1), FrameRate { num: i64::MIN, den: 1 });
}
#[trial]
fn scalar_time_conversions_saturate_at_storage_limits() {
assert_eq!(Tick::from_units(i64::MAX, 1), Tick(i64::MAX));
assert_eq!(Tick::from_units(i64::MIN, 1), Tick(i64::MIN));
assert_eq!(Tick(i64::MAX).to_units_floor(i64::MAX), i64::MAX);
assert_eq!(Tick(i64::MIN).to_units_floor(i64::MAX), i64::MIN);
assert_eq!(Tick::from_rational(i64::MAX, i64::MAX, 1), Tick(i64::MAX));
assert_eq!(Tick::from_rational(i64::MIN, i64::MAX, 1), Tick(i64::MIN));
assert_eq!(Tick::from_rational(i64::MIN, i64::MAX, -1), Tick(i64::MAX));
assert_eq!(Tick::from_rational(i64::MAX, i64::MAX, 0), Tick::ZERO);
assert_eq!(Tick(i64::MAX).to_rational_floor(1, i64::MAX), i64::MAX);
assert_eq!(Tick(i64::MIN).to_rational_round(1, i64::MAX), i64::MIN);
assert_eq!(Tick(i64::MAX).mul_ratio(i64::MAX, 1), Tick(i64::MAX));
assert_eq!(Tick(i64::MIN).abs(), Tick(i64::MAX));
}
/// The fields with every count negated (the sign flag cleared).
fn negated(f: TimecodeFields) -> TimecodeFields {
TimecodeFields { negative: false, hours: -f.hours, minutes: -f.minutes, seconds: -f.seconds, frames: -f.frames }
}
#[trial]
fn drop_frame_fields_keep_cancelling_terms_wide_at_storage_limits() {
for rate in [FrameRate::FPS_29_97, FrameRate::FPS_59_94, FrameRate::FPS_119_88] {
for frame in [0, 1, 999_999, i64::MAX - 1, i64::MAX] {
let fields = frames_to_fields(frame, rate, true);
assert!(!fields.negative);
assert_eq!(fields_to_frames(fields, rate, true), frame, "{rate}: {frame}");
assert_eq!(fields_to_frames(negated(fields), rate, true), -frame);
}
let fields = frames_to_fields(i64::MIN, rate, true);
assert!(fields.negative);
assert_eq!(fields_to_frames(negated(fields), rate, true), i64::MIN);
}
}
#[trial]
fn tick_arithmetic_saturates_only_outside_storage_limits() {
let values = [i64::MIN, i64::MIN + 1, Tick::MIN.0, -1, 0, 1, Tick::MAX.0, i64::MAX - 1, i64::MAX];
for a in values {
assert_eq!(-Tick(a), Tick(clamp_i64(-i128::from(a))));
for b in values {
let sum = Tick(clamp_i64(i128::from(a) + i128::from(b)));
let difference = Tick(clamp_i64(i128::from(a) - i128::from(b)));
assert_eq!(Tick(a) + Tick(b), sum);
assert_eq!(Tick(a) - Tick(b), difference);
let mut assigned = Tick(a);
assigned += Tick(b);
assert_eq!(assigned, sum);
assigned = Tick(a);
assigned -= Tick(b);
assert_eq!(assigned, difference);
}
}
assert_eq!(Tick::MAX + Tick(1), Tick(Tick::MAX.0 + 1), "project bounds are not storage bounds");
assert_eq!(Tick::MIN - Tick(1), Tick(Tick::MIN.0 - 1));
assert_eq!(TimeRange::new(Tick(i64::MAX), Tick(1)).end(), Tick(i64::MAX));
assert_eq!(TimeRange::new(Tick(i64::MIN), Tick(-1)).end(), Tick(i64::MIN));
assert_eq!(TimeRange::from_bounds(Tick(i64::MIN), Tick(i64::MAX)).duration, Tick(i64::MAX));
assert_eq!(TimeRange::from_bounds(Tick(i64::MAX), Tick(i64::MIN)).duration, Tick(i64::MIN));
let ordinary = TimeRange::from_bounds(Tick::MIN, Tick::MAX);
assert_eq!(ordinary.end(), Tick::MAX);
}
#[trial]
fn numeric_limits_are_total_across_frame_conversion_and_display() {
let values = [i64::MIN, -i64::MAX, -1, 0, 1, TICKS_PER_SECOND, i64::MAX];
for num in values {
for den in values {
let r = FrameRate { num, den };
let _ = FrameRate::new(num, den);
let _ = r.frame_duration();
assert!(r.timecode_base() >= 1);
for value in values {
let tick = Tick(value);
let _ = r.tick_of(value);
let _ = r.frame_at(tick);
let _ = r.snap(tick);
let _ = r.snap_nearest(tick);
for display in TimeDisplay::ALL {
let _ = format_time(tick, &TimeFormat::timecode(r).drop_frame(true).display(display));
}
let _ = fields_to_frames(frames_to_fields(value, r, true), r, true);
}
}
}
}
#[trial]
fn every_common_rate_is_exact() {
for r in FrameRate::COMMON {
let d = r.frame_duration();
assert_eq!(d.0 as i128 * r.num as i128, TICKS_PER_SECOND as i128 * r.den as i128, "{r}");
}
let menus = SampleRate::COMMON.into_iter().chain(SampleRate::VIDEO).map(|r| i64::from(r.hz()));
for sr in menus.chain([8000, 11025, 16000, 22050, 176_400]) {
assert_eq!(TICKS_PER_SECOND % sr, 0, "{sr}");
}
}
#[trial]
fn drop_frame_known_values() {
let r = FrameRate::FPS_29_97;
assert_eq!(format_timecode_frames(0, r, true), "00;00;00;00");
assert_eq!(format_timecode_frames(1799, r, true), "00;00;59;29");
assert_eq!(format_timecode_frames(1800, r, true), "00;01;00;02");
assert_eq!(format_timecode_frames(17982, r, true), "00;10;00;00");
assert_eq!(format_timecode_frames(107892, r, true), "01;00;00;00");
assert_eq!(format_timecode_frames(1800, r, false), "00:01:00:00");
let r60 = FrameRate::FPS_59_94;
assert_eq!(format_timecode_frames(3600, r60, true), "00;01;00;04");
}
#[trial]
fn parse_forms() {
let r = FrameRate::FPS_25;
assert_eq!(parse_frames("00:00:10:00", &TimeFormat::timecode(r).drop_frame(false), 0).unwrap(), 250);
assert_eq!(parse_frames("1000", &TimeFormat::timecode(r).drop_frame(false), 0).unwrap(), 250);
assert_eq!(parse_frames("1.00", &TimeFormat::timecode(r).drop_frame(false), 0).unwrap(), 25);
assert_eq!(parse_frames("+15", &TimeFormat::timecode(r).drop_frame(false), 100).unwrap(), 115);
assert_eq!(parse_frames("-1.00", &TimeFormat::timecode(r).drop_frame(false), 100).unwrap(), 75);
assert_eq!(parse_frames("00;01;00;02", &TimeFormat::timecode(FrameRate::FPS_29_97).drop_frame(true), 0).unwrap(), 1800);
assert!(parse_frames("abc", &TimeFormat::timecode(r).drop_frame(false), 0).is_err());
}
/// Overflowing fields carry into the next one before drop-frame counting, so `01;00;00;30` is the
/// frame `01;00;01;00` names rather than a non-drop count; non-drop overflow is counted as before.
#[trial]
fn overflowing_drop_frame_fields_carry_before_counting() {
let df = FrameRate::FPS_29_97;
// (typed, the label it reads as)
let cases = [("01;00;00;30", "01;00;01;00"), ("00;09;59;45", "00;10;00;15"), ("00;00;90;00", "00;01;30;00"), ("01;75;00;02", "02;15;00;02")];
for (typed, label) in cases {
let f = parse_frames(typed, &TimeFormat::timecode(df).drop_frame(true), 0).unwrap();
assert_eq!(
(f, format_timecode_frames(f, df, true)),
(parse_frames(label, &TimeFormat::timecode(df).drop_frame(true), 0).unwrap(), label.to_string()),
"{typed}"
);
}
assert_eq!(parse_frames("00:00:00:90", &TimeFormat::timecode(FrameRate::FPS_25).drop_frame(false), 0).unwrap(), 90);
assert_eq!(parse_frames("00:00:00:90", &TimeFormat::timecode(df).drop_frame(false), 0).unwrap(), 90);
}
#[trial]
fn signed_field_rejected() {
let r = FrameRate::FPS_25;
assert!(parse_frames("00:00:-5:00", &TimeFormat::timecode(r).drop_frame(false), 0).is_err());
assert!(parse_frames("00:+1:00:00", &TimeFormat::timecode(r).drop_frame(false), 0).is_err());
assert_eq!(parse_frames("00:00:10:00", &TimeFormat::timecode(r).drop_frame(false), 0).unwrap(), 250);
}
#[trial]
fn feet_frames_roll_over_at_the_foot() {
let r = FrameRate::FPS_24;
let f = |frame: i64, d| format_time(r.tick_of(frame), &TimeFormat::timecode(r).drop_frame(false).display(d));
for (frame, ft35, ft16) in
[(0, "0+00", "0+00"), (15, "0+15", "0+15"), (16, "1+00", "0+16"), (39, "2+07", "0+39"), (40, "2+08", "1+00"), (41, "2+09", "1+01")]
{
assert_eq!(f(frame, TimeDisplay::Feet35), ft35, "35mm frame {frame}");
assert_eq!(f(frame, TimeDisplay::Feet16), ft16, "16mm frame {frame}");
assert_eq!(f(frame, TimeDisplay::Frames), frame.to_string());
}
// negative: sign in front, magnitude as usual
assert_eq!(f(-1, TimeDisplay::Feet35), "-0+01");
assert_eq!(f(-16, TimeDisplay::Feet35), "-1+00");
assert_eq!(f(-41, TimeDisplay::Feet16), "-1+01");
assert_eq!(f(-5, TimeDisplay::Frames), "-5");
// large: a 10 hour show at 24 fps
assert_eq!(f(864_000, TimeDisplay::Feet35), "54000+00");
assert_eq!(f(864_039, TimeDisplay::Feet16), "21600+39");
assert_eq!(f(864_000, TimeDisplay::Frames), "864000");
assert_eq!(format_feet_frames(i64::MIN, 16), "-576460752303423488+00");
assert_eq!(format_feet_frames(5, 0), "5+00", "a zero foot never divides by zero");
}
#[trial]
fn feet_frames_follow_the_frame_not_the_rate() {
// 1 s of film is the rate's frame count whatever the rate
for (r, frames) in [(FrameRate::FPS_23_976, 24), (FrameRate::FPS_24, 24), (FrameRate::FPS_25, 25), (FrameRate::FPS_30, 30)] {
let one_second = Tick(TICKS_PER_SECOND);
// 23.976 fps is 24 frames in 1.001 s: one second is frame 23 (floor)
let want = r.frame_at(one_second);
assert!((frames - 1..=frames).contains(&want), "{r:?}");
assert_eq!(format_time(one_second, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Frames)), want.to_string());
assert_eq!(
format_time(one_second, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Feet35)),
format!("{}+{:02}", want / 16, want % 16)
);
assert_eq!(
format_time(one_second, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Feet16)),
format!("{}+{:02}", want / 40, want % 40)
);
}
// drop-frame only changes timecode
let r = FrameRate::FPS_29_97;
let t = r.tick_of(1800);
assert_eq!(
format_time(t, &TimeFormat::timecode(r).drop_frame(true).display(TimeDisplay::Frames)),
format_time(t, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Frames))
);
assert_eq!(format_time(t, &TimeFormat::timecode(r).drop_frame(true).display(TimeDisplay::Feet35)), "112+08");
assert_ne!(
format_time(t, &TimeFormat::timecode(r).drop_frame(true).display(TimeDisplay::Timecode)),
format_time(t, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Timecode))
);
}
#[trial]
fn display_ids_round_trip() {
for d in TimeDisplay::ALL {
assert_eq!(TimeDisplay::from_id(d.id()), Some(d));
}
assert_eq!(TimeDisplay::from_id("FEET35"), Some(TimeDisplay::Feet35));
assert_eq!(TimeDisplay::from_id("nope"), None);
assert_eq!(TimeDisplay::Feet35.frames_per_foot(), Some(16));
assert_eq!(TimeDisplay::Feet16.frames_per_foot(), Some(40));
assert_eq!(TimeDisplay::Frames.frames_per_foot(), None);
}
#[trial]
fn feet_frames_and_frames_parse_back() {
let r = FrameRate::FPS_24;
let p = |s: &str, d, cur| parse_frames(s, &TimeFormat::timecode(r).display(d), cur);
assert_eq!(p("2+08", TimeDisplay::Feet35, 0), Ok(40));
assert_eq!(p("1+00", TimeDisplay::Feet16, 0), Ok(40));
assert_eq!(p("0+15", TimeDisplay::Feet35, 0), Ok(15));
assert_eq!(p("1+20", TimeDisplay::Feet35, 0), Ok(36), "the frames field rolls over");
assert_eq!(p("2.08", TimeDisplay::Feet35, 0), Ok(40));
assert_eq!(p("40", TimeDisplay::Feet35, 0), Ok(40), "a bare number is frames");
assert_eq!(p("40", TimeDisplay::Frames, 0), Ok(40));
assert_eq!(p(" 7 ", TimeDisplay::Frames, 0), Ok(7));
assert_eq!(p("+5", TimeDisplay::Frames, 100), Ok(105));
assert_eq!(p("-5", TimeDisplay::Feet16, 100), Ok(95));
assert_eq!(p("+1+02", TimeDisplay::Feet35, 10), Ok(28));
assert!(p("", TimeDisplay::Frames, 0).is_err());
assert!(p("1+2", TimeDisplay::Frames, 0).is_err(), "Frames has no feet");
assert!(p("1+2+3", TimeDisplay::Feet35, 0).is_err());
assert!(p("a+1", TimeDisplay::Feet35, 0).is_err());
assert!(p("99999999999999999999", TimeDisplay::Frames, 0).is_err());
assert_eq!(p("999999999999999999+15", TimeDisplay::Feet35, 0), Ok(i64::MAX), "saturates");
// timecode displays still parse as timecode
assert_eq!(p("00:00:10:00", TimeDisplay::Timecode, 0), Ok(240));
// formatting and parsing agree for every format, around the foot boundaries
for d in [TimeDisplay::Feet35, TimeDisplay::Feet16, TimeDisplay::Frames] {
for frame in [0, 1, 15, 16, 17, 39, 40, 41, 1000, 864_000] {
let text = format_time(r.tick_of(frame), &TimeFormat::timecode(r).drop_frame(false).display(d));
assert_eq!(p(&text, d, 0), Ok(frame), "{d:?} {text}");
}
}
}
#[trial]
fn display_modes() {
let r = FrameRate::FPS_24;
let t = r.tick_of(40);
assert_eq!(format_time(t, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Feet35)), "2+08");
assert_eq!(format_time(t, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Feet16)), "1+00");
assert_eq!(format_time(t, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Frames)), "40");
assert_eq!(
format_time(Tick::from_units(48_001, 48_000), &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::AudioSamples)),
"00:00:01:00001"
);
}
#[trial]
fn rational_conversions() {
// 90 kHz MPEG timebase
let t = Tick::from_rational(90_000, 1, 90_000);
assert_eq!(t.0, TICKS_PER_SECOND);
assert_eq!(t.to_rational_floor(1, 90_000), 90_000);
assert_eq!(t.to_rational_round(1, 90_000), 90_000);
// 1 ms timebase (Matroska): to the nearest millisecond, halves up
let ms = |t: Tick| t.to_rational_round(1, 1000);
assert_eq!(ms(FrameRate::FPS_30.tick_of(1)), 33);
assert_eq!(ms(FrameRate::FPS_30.tick_of(2)), 67);
assert_eq!(FrameRate::FPS_30.tick_of(2).to_rational_floor(1, 1000), 66);
assert_eq!(ms(FrameRate::FPS_29_97.tick_of(15)), 501, "500.5 ms");
assert_eq!(ms(Tick::from_rational(-4, 1, 10_000)), 0, "-0.4 ms");
assert_eq!(ms(Tick::from_rational(-5, 1, 10_000)), 0, "-0.5 ms");
assert_eq!(ms(Tick::from_rational(-6, 1, 10_000)), -1, "-0.6 ms");
// a negative timebase is nonsense, but rounds the same way
assert_eq!(FrameRate::FPS_30.tick_of(2).to_rational_round(-1, -1000), 67);
assert_eq!(FrameRate::FPS_29_97.tick_of(15).to_rational_round(-1, -1000), 501);
assert_eq!(FrameRate::from_f64(29.97), FrameRate::FPS_29_97);
assert_eq!(FrameRate::FPS_23_976.to_string(), "23.976");
}
#[trial]
fn exotic_frame_rate_roundtrip() {
// Issue #301: 37.516 fps footage. The frame duration is
// 254_016_000_000 * 250 / 9379 = 6_770_871_094.999… ticks — not an
// integer. Floor division in `tick_of` truncated to 6_770_871_094,
// losing ~1 tick/frame so `frame_at(tick_of(f))` returned `f - 1`.
// Ceiling division makes the round-trip exact for all integer frames.
let rates: &[(FrameRate, &str)] = &[
(FrameRate::from_f64(37.516), "37.516"),
(FrameRate::from_f64(37.5161), "37.5161"),
(FrameRate::from_f64(12.345), "12.345"),
(FrameRate::from_f64(59.9401), "59.9401"),
(FrameRate::from_f64(23.9761), "23.9761"),
];
for &(r, name) in rates {
// Round-trip over a wide range including negatives.
let bad: Vec<i64> = (-20_000..20_000).filter(|&f| r.frame_at(r.tick_of(f)) != f).collect();
assert!(bad.is_empty(), "{name}: {} round-trip failures, first {bad:?}", r);
// snap(tick_of(f)) == tick_of(f): snapping a frame boundary is a no-op.
for f in -100i64..100 {
assert_eq!(r.snap(r.tick_of(f)), r.tick_of(f), "{name}: snap(tick_of({f}))");
}
// Step-back: the last tick of frame f is one tick before tick_of(f+1),
// and frame_at of that is still f. Also check the frame_duration path:
// frame_at(tick_of(f) - frame_duration()) == f - 1.
for f in 1..2000i64 {
let last_tick = r.tick_of(f + 1) - Tick(1);
assert_eq!(r.frame_at(last_tick), f, "{name}: last tick of frame {f}");
let prev = r.tick_of(f) - r.frame_duration();
assert_eq!(r.frame_at(prev), f - 1, "{name}: tick_of({f}) - frame_duration");
}
}
// Stepping simulation: frame_at(playhead) + 1, tick_of, snap.
// Before the fix this stalled at frame 0 (step forward did nothing).
let r = FrameRate::from_f64(37.516);
let mut tick = Tick::ZERO;
for expected in 0..50 {
let frame = r.frame_at(tick);
assert_eq!(frame, expected, "stepping forward at frame {expected}");
tick = r.tick_of(frame + 1);
tick = r.snap(tick); // set_playhead calls snap
}
// Stepping backward from frame 50 should land on 49, 48, … 0
tick = r.tick_of(50);
let mut last = 50;
while last > 0 {
let frame = r.frame_at(tick);
let target = frame - 1;
if target < 0 {
break;
}
tick = r.snap(r.tick_of(target));
let landed = r.frame_at(tick);
assert_eq!(landed, target, "stepping backward to frame {target}");
last = landed;
}
}
#[trial]
fn exotic_frame_rate_durations() {
// frame_duration uses floor (not round) so that `end - frame_duration()`
// lands on the previous frame, not two frames back, for exotic rates.
let r = FrameRate::from_f64(37.516);
// 254_016_000_000 * 250 / 9379 = 6_770_871_094.999… → floor = 6_770_871_094
assert_eq!(r.frame_duration().0, 6_770_871_094);
// Standard rates must remain exact (unchanged).
assert_eq!(FrameRate::FPS_23_976.frame_duration().0, 10_594_584_000);
assert_eq!(FrameRate::FPS_24.frame_duration().0, 10_584_000_000);
assert_eq!(FrameRate::FPS_25.frame_duration().0, 10_160_640_000);
assert_eq!(FrameRate::FPS_29_97.frame_duration().0, 8_475_667_200);
assert_eq!(FrameRate::FPS_30.frame_duration().0, 8_467_200_000);
assert_eq!(FrameRate::FPS_60.frame_duration().0, 4_233_600_000);
}
proptest! {
#[trial]
fn extreme_frame_math_stays_monotonic(num in 1i64..=i64::MAX, den in 1i64..=i64::MAX, a in any::<i64>(), b in any::<i64>()) {
let r = FrameRate { num, den };
let (lo, hi) = (a.min(b), a.max(b));
prop_assert!(r.tick_of(lo) <= r.tick_of(hi));
prop_assert!(r.frame_at(Tick(lo)) <= r.frame_at(Tick(hi)));
prop_assert!(r.snap(Tick(lo)) <= r.snap(Tick(hi)));
prop_assert!(r.snap_nearest(Tick(lo)) <= r.snap_nearest(Tick(hi)));
let snapped = r.snap_nearest(Tick(a));
prop_assert_eq!(r.snap_nearest(snapped), snapped);
}
#[trial]
fn frame_tick_roundtrip(f in -1_000_000i64..10_000_000, ri in 0usize..11) {
let r = FrameRate::COMMON[ri];
prop_assert_eq!(r.frame_at(r.tick_of(f)), f);
prop_assert_eq!(r.frame_at(r.tick_of(f) + r.frame_duration() - Tick(1)), f);
}
#[trial]
fn exotic_frame_tick_roundtrip(f in -100_000i64..100_000, num in 1u64..200_000, den in 1u64..2_000) {
// Skip rates that divide evenly (those are covered by COMMON above).
let r = FrameRate::new(num as i64, den as i64);
if (TICKS_PER_SECOND as i128 * r.den as i128) % r.num as i128 == 0 {
return Ok(());
}
prop_assert_eq!(r.frame_at(r.tick_of(f)), f, "rate={}/{}, f={}", r.num, r.den, f);
}
#[trial]
fn drop_frame_bijection(f in 0i64..(24 * 107_892)) {
let r = FrameRate::FPS_29_97;
let fields = frames_to_fields(f, r, true);
// dropped labels never appear
prop_assert!(!(fields.seconds == 0 && fields.frames < 2 && fields.minutes % 10 != 0));
prop_assert_eq!(fields_to_frames(fields, r, true), f);
let txt = format_timecode_frames(f, r, true);
prop_assert_eq!(parse_frames(&txt, &TimeFormat::timecode(r).drop_frame(true), 0).unwrap(), f);
}
#[trial]
fn ndf_parse_roundtrip(f in 0i64..10_000_000, ri in 0usize..11) {
let r = FrameRate::COMMON[ri];
let txt = format_timecode_frames(f, r, false);
prop_assert_eq!(parse_frames(&txt, &TimeFormat::timecode(r).drop_frame(false), 0).unwrap(), f);
}
}
/// At 11 fps a frame is not a whole number of ticks, so the ticks from one boundary to the next
/// can read as zero frames; counting between frame indices gives one.
#[trial]
fn frames_between_counts_boundaries_at_fractional_tick_rates() {
let r = FrameRate::new(11, 1);
for f in 0..1000 {
for n in 1..=12 {
let (a, b) = (r.tick_of(f), r.tick_of(f + n));
assert_eq!(r.frames_between(a, b), n, "frames {f}..{}", f + n);
}
}
assert_eq!(r.frame_at(Tick(r.tick_of(2).0 - r.tick_of(1).0)), 0, "the length alone reads one short");
// frame indices that span the whole integer range saturate instead of overflowing
let fast = FrameRate::new(i64::MAX, 1);
assert_eq!(fast.frames_between(Tick(i64::MIN), Tick(i64::MAX)), i64::MAX);
assert_eq!(fast.frames_between(Tick(i64::MAX), Tick(i64::MIN)), i64::MIN);
}
+17 -227
View File
@@ -7,60 +7,7 @@
use crate::rates::{FrameRate, SampleRate};
use crate::time::{TICKS_PER_SECOND, Tick};
/// How time is shown (Premiere: Timecode, Feet + Frames 16 mm / 35 mm, Frames, Audio Samples;
/// After Effects' frame numbers; seconds for scripts).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum TimeDisplay {
/// `HH:MM:SS:FF`, `HH;MM;SS;FF` for drop-frame; three frame digits from 100 fps.
#[default]
Timecode,
/// The frame number, counted from [`TimeFormat::frame_offset`] (After Effects' Start
/// Numbering Frames At).
Frames,
/// `feet+frames` at 40 frames a foot.
Feet16,
/// `feet+frames` at 16 frames a foot.
Feet35,
/// `HH:MM:SS:sssss`, the samples past the second.
AudioSamples,
/// Seconds with three decimals.
Seconds,
}
impl TimeDisplay {
/// The order of Premiere's Time Display menu.
pub const ALL: [TimeDisplay; 6] =
[TimeDisplay::Timecode, TimeDisplay::Feet35, TimeDisplay::Feet16, TimeDisplay::Frames, TimeDisplay::AudioSamples, TimeDisplay::Seconds];
/// The display's stable id for commands, settings and scripts: `timecode`, `frames`, `feet16`,
/// `feet35`, `samples`, `seconds`.
// filmcraft: crates/time/src/lib.rs:376.
pub fn id(self) -> &'static str {
match self {
TimeDisplay::Timecode => "timecode",
TimeDisplay::Frames => "frames",
TimeDisplay::Feet16 => "feet16",
TimeDisplay::Feet35 => "feet35",
TimeDisplay::AudioSamples => "samples",
TimeDisplay::Seconds => "seconds",
}
}
/// The display with this [`id`](Self::id), ignoring ASCII case.
pub fn from_id(id: &str) -> Option<TimeDisplay> {
TimeDisplay::ALL.into_iter().find(|d| d.id().eq_ignore_ascii_case(id))
}
/// Frames in a foot of film for the feet + frames displays: 16 for 35 mm 4-perf, 40 for 16 mm.
// filmcraft: crates/time/src/lib.rs:393.
pub fn frames_per_foot(self) -> Option<i64> {
match self {
TimeDisplay::Feet35 => Some(16),
TimeDisplay::Feet16 => Some(40),
_ => None,
}
}
}
pub use craft_time::{TimeDisplay, format_timecode_frames};
/// Everything a time display needs: the rate, drop-frame, the display, the sample rate (for
/// [`TimeDisplay::AudioSamples`]) and the first frame's number.
@@ -97,21 +44,6 @@ impl TimeFormat {
}
}
/// SMPTE fields of a frame count.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TimecodeFields {
/// Whether the time is before zero.
pub negative: bool,
/// Hours, from zero.
pub hours: i64,
/// Minutes, 0 to 59.
pub minutes: i64,
/// Seconds, 0 to 59.
pub seconds: i64,
/// Frames within the second, below the nominal frame rate.
pub frames: i64,
}
/// Why typed time was refused. The UI shows it as a notice through its own words.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TimecodeError {
@@ -132,90 +64,29 @@ impl std::fmt::Display for TimecodeError {
impl std::error::Error for TimecodeError {}
/// The SMPTE fields of `frame` at `rate`. Drop-frame (when asked and the rate supports it) skips
/// `base / 15` labels at the start of each minute except every tenth: 2 at 29.97, 4 at 59.94.
// filmcraft: crates/time/src/lib.rs:363 `frames_to_fields` (and `df_params` above it).
pub fn frames_to_fields(frame: i64, rate: FrameRate, drop_frame: bool) -> TimecodeFields {
let negative = frame < 0;
let mut n = i128::from(frame).abs();
let (drop, base) = df_params(rate);
if drop_frame && rate.supports_drop_frame() {
let per_min = base * 60 - drop;
let per_10 = per_min * 10 + drop;
let d = n / per_10;
let m = n % per_10;
n = n.saturating_add(drop * 9 * d);
if m > drop {
n = n.saturating_add(drop * ((m - drop) / per_min));
}
}
TimecodeFields {
negative,
hours: clamp_i64(n / (base * 3600)),
minutes: clamp_i64((n / (base * 60)) % 60),
seconds: clamp_i64((n / base) % 60),
frames: clamp_i64(n % base),
}
}
/// The frame count of SMPTE fields; the inverse of [`frames_to_fields`], in i128 so nominal
/// drop-frame labels past `i64` still give a frame that fits.
// filmcraft: crates/time/src/lib.rs:386 `fields_to_frames`.
pub fn fields_to_frames(fields: TimecodeFields, rate: FrameRate, drop_frame: bool) -> i64 {
let (drop, base) = df_params(rate);
let seconds = i128::from(fields.hours) * 3600 + i128::from(fields.minutes) * 60 + i128::from(fields.seconds);
let mut n = seconds.saturating_mul(base).saturating_add(i128::from(fields.frames));
if drop_frame && rate.supports_drop_frame() {
let total_min = i128::from(fields.hours) * 60 + i128::from(fields.minutes);
n = n.saturating_sub(drop * (total_min - total_min / 10));
}
clamp_i64(n)
}
/// `t` as text in `format`: timecode `00:00:10:00` (as [`format_timecode_frames`]); frames `250`
/// (plus the offset); feet + frames `15+10` (as [`format_feet_frames`]); samples `00:00:10:00000`
/// (five digits of samples past the second); seconds `10.000` (`-0.000` shown as `0.000`).
// filmcraft: crates/time/src/lib.rs:462 `format_time`.
pub fn format_time(t: Tick, format: &TimeFormat) -> String {
let rate = format.rate;
let frame = rate.frame_at(t);
match format.display {
TimeDisplay::Timecode => format_timecode_frames(frame, rate, format.drop_frame),
TimeDisplay::Frames => frame.saturating_add(format.frame_offset).to_string(),
TimeDisplay::Feet35 | TimeDisplay::Feet16 => format_feet_frames(frame, format.display.frames_per_foot().unwrap_or(16)),
TimeDisplay::AudioSamples => {
let a = t.0.unsigned_abs();
let tps = TICKS_PER_SECOND.unsigned_abs();
let secs = a / tps;
let samples = Tick((a % tps) as i64).to_units_floor(i64::from(format.sample_rate.hz()));
format!("{}{:02}:{:02}:{:02}:{samples:05}", sign(t.0 < 0), secs / 3600, (secs / 60) % 60, secs % 60)
}
TimeDisplay::Seconds => {
let s = format!("{:.3}", t.seconds());
if s == "-0.000" { "0.000".to_string() } else { s }
TimeDisplay::Timecode => format_timecode_frames(rate.frame_at(t), rate, format.drop_frame),
TimeDisplay::Frames => rate.frame_at(t).saturating_add(format.frame_offset).to_string(),
TimeDisplay::Feet35 | TimeDisplay::Feet16 => format_feet_frames(rate.frame_at(t), format.display.frames_per_foot().unwrap_or(16)),
TimeDisplay::AudioSamples | TimeDisplay::Seconds => {
craft_time::format_time(t, rate, format.drop_frame, format.display, i64::from(format.sample_rate.hz()))
}
}
}
/// Frame `frame` at `rate` as SMPTE timecode: `HH:MM:SS:FF`, `HH;MM;SS;FF` when `drop_frame` is
/// asked and the rate supports it, three frame digits from a 100 fps base, a leading `-` before
/// zero.
// filmcraft: crates/time/src/lib.rs:453.
pub fn format_timecode_frames(frame: i64, rate: FrameRate, drop_frame: bool) -> String {
let drop = drop_frame && rate.supports_drop_frame();
let f = frames_to_fields(frame, rate, drop);
let sep = if drop { ';' } else { ':' };
let width = if rate.timecode_base() >= 100 { 3 } else { 2 };
format!("{}{:02}{sep}{:02}{sep}{:02}{sep}{:0width$}", sign(f.negative), f.hours, f.minutes, f.seconds, f.frames)
}
/// A frame count as film feet + frames, `ft+ff` (`2+08`; `-2+08` before zero). A
/// `frames_per_foot` below 1 counts as 1, so a bad value never divides by zero.
// filmcraft: crates/time/src/lib.rs:404.
pub fn format_feet_frames(frame: i64, frames_per_foot: i64) -> String {
let per_foot = frames_per_foot.max(1).unsigned_abs();
let a = frame.unsigned_abs();
format!("{}{}+{:02}", sign(frame < 0), a / per_foot, a % per_foot)
format!("{}{}+{:02}", if frame < 0 { "-" } else { "" }, a / per_foot, a % per_foot)
}
/// Typed time in `format` as a tick, the way Premiere's fields read it:
@@ -225,8 +96,8 @@ pub fn format_feet_frames(frame: i64, frames_per_foot: i64) -> String {
/// second earlier);
/// - in [`TimeDisplay::Frames`] a bare number is a frame number (less the offset); in
/// [`TimeDisplay::Seconds`] a decimal number of seconds; feet + frames reads `ft+ff` (any of
/// `+:;.,` separates; frames past the foot roll over, `1+20` at 35 mm is 36 frames; `-ft+ff`
/// is before zero, as [`format_feet_frames`] writes it) and a bare number as frames.
/// `+:;.,` separates; frames past the foot roll over, `1+20` at 35 mm is 36 frames; a leading
/// sign counts from `current` as in the other displays) and a bare number as frames.
///
/// The result is the first tick of the frame; [`TimeDisplay::AudioSamples`] gives the sample's
/// tick.
@@ -274,54 +145,24 @@ pub fn parse_time(input: &str, format: &TimeFormat, current: Tick) -> Result<Tic
// filmcraft: crates/time/src/lib.rs:499 `parse_timecode`, `:575` `parse_time_display`.
pub fn parse_frames(input: &str, format: &TimeFormat, current: i64) -> Result<i64, TimecodeError> {
let rate = format.rate;
let (relative, body) = split_sign(input)?;
let bad = || TimecodeError::NotATime(input.to_string());
let from_current = |n: i64, sign: i64| current.saturating_add(n.saturating_mul(sign));
let (relative, _) = split_sign(input)?;
match format.display {
TimeDisplay::Timecode => parse_timecode_frames(body, relative, format, current).ok_or_else(bad),
TimeDisplay::Frames => {
let n = parse_digits(body).ok_or_else(bad)?;
Ok(relative.map_or_else(|| n.saturating_sub(format.frame_offset), |sign| from_current(n, sign)))
}
TimeDisplay::Feet16 | TimeDisplay::Feet35 => {
let per_foot = format.display.frames_per_foot().unwrap_or(16);
match body.split(['+', ':', ';', '.', ',']).collect::<Vec<_>>()[..] {
[n] => {
let n = parse_digits(n).ok_or_else(bad)?;
Ok(relative.map_or(n, |sign| from_current(n, sign)))
}
[feet, frames] => {
let total = parse_digits(feet.trim())
.zip(parse_digits(frames.trim()))
.map(|(ft, fr)| ft.saturating_mul(per_foot).saturating_add(fr))
.ok_or_else(bad)?;
Ok(match relative {
Some(1) => current.saturating_add(total),
Some(_) => total.saturating_neg(),
None => total,
})
}
_ => Err(bad()),
}
TimeDisplay::Timecode | TimeDisplay::Frames | TimeDisplay::Feet16 | TimeDisplay::Feet35 => {
let frames = craft_time::parse_time_display_relative(input, rate, format.drop_frame, format.display, current)
.map_err(|_| TimecodeError::NotATime(input.to_string()))?;
Ok(match (format.display, relative) {
(TimeDisplay::Frames, None) => frames.saturating_sub(format.frame_offset),
_ => frames,
})
}
TimeDisplay::AudioSamples | TimeDisplay::Seconds => parse_time(input, format, rate.tick_of(current)).map(|t| rate.frame_at(t)),
}
}
/// Drop-frame parameters: labels dropped per minute and the nominal base (30 gives 2, 60 gives 4).
fn df_params(rate: FrameRate) -> (i128, i128) {
let base = rate.timecode_base();
(i128::from(base / 15), i128::from(base))
}
fn clamp_i64(value: i128) -> i64 {
value.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
}
fn sign(negative: bool) -> &'static str {
if negative { "-" } else { "" }
}
/// The trimmed input as its leading sign (`+` is 1, `-` is -1: relative to the current time) and
/// the rest.
fn split_sign(input: &str) -> Result<(Option<i64>, &str), TimecodeError> {
@@ -345,54 +186,3 @@ fn parse_digits(s: &str) -> Option<i64> {
}
s.parse().ok()
}
/// Typed timecode as a frame count: separated fields, or bare digits read right-aligned in pairs
/// (a relative bare number is a frame count). Fields may overflow their unit (90 frames).
fn parse_timecode_frames(body: &str, relative: Option<i64>, format: &TimeFormat, current: i64) -> Option<i64> {
let rate = format.rate;
let parts: Vec<&str> = body.split([':', ';', '.', ',']).collect();
let nums: Vec<i64> = if parts.len() == 1 {
let digits = parts[0];
if relative.is_some() {
vec![parse_digits(digits)?]
} else {
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let mut v = Vec::new();
let mut end = digits.len();
while end > 0 {
let start = end.saturating_sub(2);
v.push(digits[start..end].parse::<i64>().unwrap_or(0));
end = start;
}
v.reverse();
v
}
} else {
parts.iter().map(|p| if p.is_empty() { Some(0) } else { parse_digits(p) }).collect::<Option<_>>()?
};
if nums.len() > 4 {
return None;
}
let mut fields = [0i64; 4];
fields[4 - nums.len()..].copy_from_slice(&nums);
let [h, m, s, f] = fields;
let base = rate.timecode_base();
let frames = if nums.len() == 1 && relative.is_some() {
f
} else if format.drop_frame && rate.supports_drop_frame() {
// Fields past their range carry into the next one first, then drop-frame counting applies:
// 01;00;00;30 is the frame 01;00;01;00 names.
let (s, f) = (s.saturating_add(f / base), f % base);
let (m, s) = (m.saturating_add(s / 60), s % 60);
let (h, m) = (h.saturating_add(m / 60), m % 60);
fields_to_frames(TimecodeFields { negative: false, hours: h, minutes: m, seconds: s, frames: f }, rate, true)
} else {
h.saturating_mul(3600).saturating_add(m.saturating_mul(60)).saturating_add(s).saturating_mul(base).saturating_add(f)
};
Some(match relative {
Some(sign) => current.saturating_add(frames.saturating_mul(sign)),
None => frames,
})
}
+97 -28
View File
@@ -1,8 +1,8 @@
//! Formatting and parsing time.
//! Formatting and parsing time through a [`TimeFormat`].
use crate::rates::{FrameRate, SampleRate};
use crate::time::{TICKS_PER_SECOND, Tick};
use crate::timecode::{TimeDisplay, TimeFormat, TimecodeFields, fields_to_frames, format_time, frames_to_fields, parse_time};
use crate::timecode::{TimeDisplay, TimeFormat, format_feet_frames, format_time, parse_frames, parse_time};
use craft_ui::testing::trial;
fn df() -> TimeFormat {
@@ -10,32 +10,13 @@ fn df() -> TimeFormat {
}
#[trial]
fn drop_frame_skips_two_labels_a_minute() {
let rate = FrameRate::FPS_29_97;
assert_eq!(format_time(rate.tick_of(1800), &df()), "00;01;00;02");
assert_eq!(format_time(rate.tick_of(17_982), &df()), "00;10;00;00");
assert_eq!(format_time(rate.tick_of(1799), &df()), "00;00;59;29");
for frame in [0, 1, 1799, 1800, 17_981, 17_982, 107_892, -1800] {
let fields = frames_to_fields(frame, rate, true);
assert_eq!(fields_to_frames(fields, rate, true) * if fields.negative { -1 } else { 1 }, frame, "frame {frame}");
}
assert_eq!(frames_to_fields(-30, rate, false), TimecodeFields { negative: true, hours: 0, minutes: 0, seconds: 1, frames: 0 });
}
/// A drop-frame time code with a field past its range carries into the next field before the
/// dropped labels are counted; counting it as non-drop frames lands on another frame.
#[trial]
fn overflowing_drop_frame_fields_carry_before_counting() {
let rate = FrameRate::FPS_29_97;
// (typed, the label it reads as)
for (typed, label) in
[("01;00;00;30", "01;00;01;00"), ("00;09;59;45", "00;10;00;15"), ("00;00;90;00", "00;01;30;00"), ("01;75;00;02", "02;15;00;02")]
{
let t = parse_time(typed, &df(), Tick::ZERO).expect(typed);
assert_eq!((t, format_time(t, &df())), (parse_time(label, &df(), Tick::ZERO).expect(label), label.to_string()), "{typed}");
}
let nd = TimeFormat::timecode(rate);
assert_eq!(parse_time("00:00:00:90", &nd, Tick::ZERO), Ok(rate.tick_of(90)));
fn seconds_display_has_no_negative_zero() {
let f = |t: i64| format_time(Tick(t), &TimeFormat::timecode(FrameRate::default()).drop_frame(false).display(TimeDisplay::Seconds));
assert_eq!(f(-1), "0.000");
assert_eq!(f(-2), "0.000");
assert_eq!(f(-(TICKS_PER_SECOND / 2500)), "0.000");
assert_eq!(f(-TICKS_PER_SECOND), "-1.000");
assert_eq!(f(-TICKS_PER_SECOND / 1000), "-0.001");
}
#[trial]
@@ -61,3 +42,91 @@ fn parses_premiere_input() {
assert_eq!(parse_time("00:00:10:24000", &tc.display(TimeDisplay::AudioSamples), Tick::ZERO), Ok(Tick(TICKS_PER_SECOND * 21 / 2)));
assert_eq!(SampleRate::default().hz(), 48_000);
}
#[trial]
fn feet_frames_roll_over_at_the_foot() {
let r = FrameRate::FPS_24;
let f = |frame: i64, d| format_time(r.tick_of(frame), &TimeFormat::timecode(r).drop_frame(false).display(d));
for (frame, ft35, ft16) in
[(0, "0+00", "0+00"), (15, "0+15", "0+15"), (16, "1+00", "0+16"), (39, "2+07", "0+39"), (40, "2+08", "1+00"), (41, "2+09", "1+01")]
{
assert_eq!(f(frame, TimeDisplay::Feet35), ft35, "35mm frame {frame}");
assert_eq!(f(frame, TimeDisplay::Feet16), ft16, "16mm frame {frame}");
assert_eq!(f(frame, TimeDisplay::Frames), frame.to_string());
}
// negative: sign in front, magnitude as usual
assert_eq!(f(-1, TimeDisplay::Feet35), "-0+01");
assert_eq!(f(-16, TimeDisplay::Feet35), "-1+00");
assert_eq!(f(-41, TimeDisplay::Feet16), "-1+01");
assert_eq!(f(-5, TimeDisplay::Frames), "-5");
// large: a 10 hour show at 24 fps
assert_eq!(f(864_000, TimeDisplay::Feet35), "54000+00");
assert_eq!(f(864_039, TimeDisplay::Feet16), "21600+39");
assert_eq!(f(864_000, TimeDisplay::Frames), "864000");
assert_eq!(format_feet_frames(i64::MIN, 16), "-576460752303423488+00");
assert_eq!(format_feet_frames(5, 0), "5+00", "a zero foot never divides by zero");
}
#[trial]
fn feet_frames_follow_the_frame_not_the_rate() {
// 1 s of film is the rate's frame count whatever the rate
for (r, frames) in [(FrameRate::FPS_23_976, 24), (FrameRate::FPS_24, 24), (FrameRate::FPS_25, 25), (FrameRate::FPS_30, 30)] {
let one_second = Tick(TICKS_PER_SECOND);
// 23.976 fps is 24 frames in 1.001 s: one second is frame 23 (floor)
let want = r.frame_at(one_second);
assert!((frames - 1..=frames).contains(&want), "{r:?}");
assert_eq!(format_time(one_second, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Frames)), want.to_string());
assert_eq!(
format_time(one_second, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Feet35)),
format!("{}+{:02}", want / 16, want % 16)
);
assert_eq!(
format_time(one_second, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Feet16)),
format!("{}+{:02}", want / 40, want % 40)
);
}
// drop-frame only changes timecode
let r = FrameRate::FPS_29_97;
let t = r.tick_of(1800);
assert_eq!(
format_time(t, &TimeFormat::timecode(r).drop_frame(true).display(TimeDisplay::Frames)),
format_time(t, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Frames))
);
assert_eq!(format_time(t, &TimeFormat::timecode(r).drop_frame(true).display(TimeDisplay::Feet35)), "112+08");
assert_ne!(
format_time(t, &TimeFormat::timecode(r).drop_frame(true).display(TimeDisplay::Timecode)),
format_time(t, &TimeFormat::timecode(r).drop_frame(false).display(TimeDisplay::Timecode))
);
}
#[trial]
fn feet_frames_and_frames_parse_back() {
let r = FrameRate::FPS_24;
let p = |s: &str, d, cur| parse_frames(s, &TimeFormat::timecode(r).display(d), cur);
assert_eq!(p("2+08", TimeDisplay::Feet35, 0), Ok(40));
assert_eq!(p("1+00", TimeDisplay::Feet16, 0), Ok(40));
assert_eq!(p("0+15", TimeDisplay::Feet35, 0), Ok(15));
assert_eq!(p("1+20", TimeDisplay::Feet35, 0), Ok(36), "the frames field rolls over");
assert_eq!(p("2.08", TimeDisplay::Feet35, 0), Ok(40));
assert_eq!(p("40", TimeDisplay::Feet35, 0), Ok(40), "a bare number is frames");
assert_eq!(p("40", TimeDisplay::Frames, 0), Ok(40));
assert_eq!(p(" 7 ", TimeDisplay::Frames, 0), Ok(7));
assert_eq!(p("+5", TimeDisplay::Frames, 100), Ok(105));
assert_eq!(p("-5", TimeDisplay::Feet16, 100), Ok(95));
assert_eq!(p("+1+02", TimeDisplay::Feet35, 10), Ok(28));
assert!(p("", TimeDisplay::Frames, 0).is_err());
assert!(p("1+2", TimeDisplay::Frames, 0).is_err(), "Frames has no feet");
assert!(p("1+2+3", TimeDisplay::Feet35, 0).is_err());
assert!(p("a+1", TimeDisplay::Feet35, 0).is_err());
assert!(p("99999999999999999999", TimeDisplay::Frames, 0).is_err());
assert_eq!(p("999999999999999999+15", TimeDisplay::Feet35, 0), Ok(i64::MAX), "saturates");
// timecode displays still parse as timecode
assert_eq!(p("00:00:10:00", TimeDisplay::Timecode, 0), Ok(240));
// formatting and parsing agree for every format, around the foot boundaries
for d in [TimeDisplay::Feet35, TimeDisplay::Feet16, TimeDisplay::Frames] {
for frame in [0, 1, 15, 16, 17, 39, 40, 41, 1000, 864_000] {
let text = format_time(r.tick_of(frame), &TimeFormat::timecode(r).drop_frame(false).display(d));
assert_eq!(p(&text, d, 0), Ok(frame), "{d:?} {text}");
}
}
}