mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 07:35:02 +00:00
craft-captions: read and write timecode through craft-timeline's timecode module
SCC, MCC and EBU STL labels go through TimecodeFields with timecode::{frames_to_fields, fields_to_frames}. FrameRate, Tick and TICKS_PER_SECOND stay re-exported at the crate root; the re-export of craft-timeline's time module goes, since frame rates and timecode live in rates and timecode.
This commit is contained in:
@@ -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 ([`time`]). SRT/VTT milliseconds and SCC 29.97 fps
|
||||
//! - **Time:** cue times are exact [`Tick`]s (`craft-timeline`'s). 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,13 +38,12 @@ 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";
|
||||
@@ -166,7 +165,8 @@ 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 (_, h, m, s, f) = crate::time::frames_to_fields(frame.max(0), rate, drop_frame && rate.supports_drop_frame());
|
||||
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: f, .. } =
|
||||
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,8 +176,7 @@ 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)));
|
||||
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())
|
||||
fields_to_frames(frames_to_fields(n, nominal, false), rate, drop_frame && rate.supports_drop_frame())
|
||||
}
|
||||
|
||||
impl Document {
|
||||
@@ -560,8 +559,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!(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");
|
||||
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");
|
||||
// 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
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::time::{FrameRate, fields_to_frames, frames_to_fields};
|
||||
use craft_timeline::FrameRate;
|
||||
use craft_timeline::timecode::{TimecodeFields, fields_to_frames, frames_to_fields};
|
||||
|
||||
use crate::cea608::with_parity;
|
||||
use crate::{Cue, Document, Error, Result, scc};
|
||||
@@ -686,7 +687,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 (_, hh, mm, ss, ff) = frames_to_fields(f.saturating_add(origin), RATE, drop_frame);
|
||||
let TimecodeFields { hours: hh, minutes: mm, seconds: ss, frames: 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);
|
||||
@@ -741,7 +742,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(*h, *m, *s, *f, 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 Some(bytes) = expand(data) else {
|
||||
doc.warnings.push(format!("line {}: bad caption data", n + 1));
|
||||
continue;
|
||||
@@ -916,7 +917,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::time::Tick(3600 * crate::time::TICKS_PER_SECOND); // the label 01:00:00:00
|
||||
let hour = crate::Tick(3600 * crate::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()
|
||||
@@ -933,9 +934,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::time::Tick(-1), ..doc.clone() };
|
||||
let negative = Document { start_timecode: crate::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::time::Tick(i64::MAX), ..doc }, true).contains('\t'));
|
||||
assert!(write(&Document { start_timecode: crate::Tick(i64::MAX), ..doc }, true).contains('\t'));
|
||||
}
|
||||
|
||||
/// Bound output for distant or long cues near the tick limit without changing their timing.
|
||||
@@ -975,7 +976,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 (_, hh, mm, ss, ff) = frames_to_fields(f as i64, RATE, drop_frame);
|
||||
let TimecodeFields { hours: hh, minutes: mm, seconds: ss, frames: 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();
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::time::{FrameRate, Tick, fields_to_frames, frames_to_fields};
|
||||
use craft_timeline::timecode::{TimecodeFields, fields_to_frames, frames_to_fields};
|
||||
use craft_timeline::{FrameRate, Tick};
|
||||
|
||||
use crate::cea608::{self, Encoded, misc};
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
@@ -41,11 +42,11 @@ pub fn parse_timecode(s: &str) -> Option<i64> {
|
||||
if m >= 60 || sec >= 60 || f >= 30 {
|
||||
return None;
|
||||
}
|
||||
Some(fields_to_frames(h, m, sec, f, RATE, df))
|
||||
Some(fields_to_frames(TimecodeFields { negative: false, hours: h, minutes: m, seconds: sec, frames: f }, RATE, df))
|
||||
}
|
||||
|
||||
pub fn format_timecode(frame: i64, drop_frame: bool) -> String {
|
||||
let (_, h, m, s, f) = frames_to_fields(frame.max(0), RATE, drop_frame);
|
||||
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: f, .. } = frames_to_fields(frame.max(0), RATE, drop_frame);
|
||||
format!("{h:02}:{m:02}:{s:02}{}{f:02}", if drop_frame { ';' } else { ':' })
|
||||
}
|
||||
|
||||
@@ -269,7 +270,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::time::TICKS_PER_SECOND)).max(1);
|
||||
let one_second = rate.frame_at(Tick(crate::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));
|
||||
@@ -579,7 +580,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::time::TICKS_PER_SECOND); // the label 01:00:00:00
|
||||
let hour = Tick(3600 * crate::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()
|
||||
|
||||
@@ -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::time::Tick;
|
||||
use crate::Tick;
|
||||
|
||||
use crate::{Cue, Document, Error, Result, format_clock, parse_clock};
|
||||
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
//! - Long subtitles continue in extension blocks; user-data (`EBN 0xFE`) and comment blocks are
|
||||
//! skipped.
|
||||
|
||||
use crate::time::{FrameRate, Tick, fields_to_frames, frames_to_fields};
|
||||
use craft_timeline::timecode::{TimecodeFields, fields_to_frames, frames_to_fields};
|
||||
use craft_timeline::{FrameRate, Tick};
|
||||
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
@@ -304,7 +305,11 @@ 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(*hours as i64, *minutes as i64, *seconds as i64, *frames as i64, rate, false))
|
||||
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,
|
||||
))
|
||||
}
|
||||
|
||||
/// A subtitle being assembled from its TTI blocks: number, in and out frames, text, and whether
|
||||
@@ -323,7 +328,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(n(0), n(2), n(4), n(6), rate, false)
|
||||
fields_to_frames(TimecodeFields { negative: false, hours: n(0), minutes: n(2), seconds: n(4), frames: n(6) }, rate, false)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
@@ -405,7 +410,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 (_, h, m, s, f) = frames_to_fields(rate.frame_at(rate.snap_nearest(t)), rate, false);
|
||||
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: f, .. } = frames_to_fields(rate.frame_at(rate.snap_nearest(t)), rate, false);
|
||||
format!("{h:02}:{m:02}:{s:02}:{f:02}")
|
||||
}
|
||||
|
||||
@@ -433,7 +438,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 (_, h, m, s, fr) = frames_to_fields(f, rate, false);
|
||||
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: 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;
|
||||
@@ -462,7 +467,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 (_, h, m, s, f) = frames_to_fields(first_in.unwrap_or(0), rate, false);
|
||||
let TimecodeFields { hours: h, minutes: m, seconds: s, frames: 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");
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::time::{FrameRate, TICKS_PER_SECOND, Tick};
|
||||
use crate::{FrameRate, TICKS_PER_SECOND, Tick};
|
||||
|
||||
use craft_xml::{El, Limits, Node, Options, UnknownEntity};
|
||||
|
||||
|
||||
@@ -208,7 +208,7 @@ pub fn write(doc: &Document) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::TICKS_PER_MS;
|
||||
use crate::time::Tick;
|
||||
use crate::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> & tags\n";
|
||||
|
||||
|
||||
Reference in New Issue
Block a user