forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

captions.rs240 lines, 9.0 KiBHistoryRawDownload
1//! Embedded closed captions (CEA-608 CC1-CC4, CEA-708 service 1) as subtitle tracks.
2//!
3//! The captions ride inside the *picture* track (H.264/HEVC SEI, MPEG-2 user data), so finding
4//! them reads every picture packet: the walk is lazy and cached. [`present`] is the cheap
5//! answer for a track list (the first seconds only); [`tracks`] is the full scan an import runs.
6//! Both are cached per file (path, size, mtime).
7//!
8//! A caption track's `number` is synthetic ([`TRACK_BASE`] plus the channel) so it can sit in the
9//! same `(file, track)` row a container's own subtitle track does. CC1-CC4 are 1-4, service 1 is 5.
10//!
11//! corner-cut: QuickTime `c608`/`c708` caption tracks of an mov are not read -- `ec-mp4` exposes
12//! no stream for a sample entry it does not know, so their samples are out of reach from here.
13
14use std::collections::HashMap;
15use std::sync::{Arc, Mutex};
16use std::time::SystemTime;
17
18use super::*;
19
20/// Added to the channel to make a caption track's number in a `(file, track)` row; far above any
21/// real container track number.
22pub const TRACK_BASE: u64 = 1 << 32;
23
24/// Seconds of picture the presence probe reads.
25const PROBE_SECS: i64 = 10;
26
27/// Whether a track number names an embedded caption track.
28pub fn is_caption_track(number: u64) -> bool {
29 number > TRACK_BASE && number <= TRACK_BASE + 5
30}
31
32/// What a list shows for caption track `number`: `CC1 (608)` ... `CC4 (608)`, `Service 1 (708)`.
33pub fn track_name(number: u64) -> String {
34 match number.saturating_sub(TRACK_BASE) {
35 n @ 1..=4 => format!("CC{n} (608)"),
36 5 => "Service 1 (708)".to_string(),
37 _ => format!("caption track {number}"),
38 }
39}
40
41/// One embedded caption track: its number, its name and, for a full scan, its cues.
42#[derive(Clone, Debug)]
43pub struct CaptionTrack {
44 pub number: u64,
45 pub name: String,
46 pub cues: Vec<ec_cc::CaptionCue>,
47}
48
49type Key = (std::path::PathBuf, u64, Option<SystemTime>);
50type Cache = Mutex<HashMap<Key, Arc<Vec<CaptionTrack>>>>;
51
52fn key(path: &Path) -> Key {
53 let meta = std::fs::metadata(path).ok();
54 (
55 path.to_path_buf(),
56 meta.as_ref().map_or(0, |m| m.len()),
57 meta.and_then(|m| m.modified().ok()),
58 )
59}
60
61fn cache(full: bool) -> &'static Cache {
62 static FULL: std::sync::OnceLock<Cache> = std::sync::OnceLock::new();
63 static PROBE: std::sync::OnceLock<Cache> = std::sync::OnceLock::new();
64 if full { &FULL } else { &PROBE }.get_or_init(Default::default)
65}
66
67/// Every picture of `path` as presentation-ordered caption triplets, whichever container.
68fn scan(path: &Path, limit_us: Option<i64>) -> crate::Result<Vec<ec_cc::TimedCc>> {
69 if is_matroska(path) {
70 scan_mkv(path, limit_us)
71 } else if ps::is_mpeg_system(path) {
72 ts::caption_triplets(path, limit_us)
73 } else {
74 scan_mp4(path, limit_us)
75 }
76}
77
78fn scan_mkv(path: &Path, limit_us: Option<i64>) -> crate::Result<Vec<ec_cc::TimedCc>> {
79 let (meta, mut mkv) = MkvDemuxer::open(path)?;
80 let fmt = |n: u8| ec_cc::extract::NalFormat::LengthPrefixed(n);
81 let rate = ((meta.frame_rate * 1000.0).round().max(1.0) as u32, 1000);
82 let private = mkv.codec_private().to_vec();
83 enum Ex {
84 H264(ec_cc::H264Extractor),
85 Hevc(ec_cc::HevcExtractor),
86 }
87 let mut ex = match meta.codec {
88 Codec::H264 => {
89 let mut e = ec_cc::H264Extractor::new(fmt(4));
90 e.set_extradata(&private);
91 Ex::H264(e)
92 }
93 Codec::Hevc => {
94 let mut e = ec_cc::HevcExtractor::new(fmt(4));
95 e.set_extradata(&private);
96 Ex::Hevc(e)
97 }
98 _ => return Ok(Vec::new()),
99 };
100 for i in 0..mkv.block_count() {
101 let Some(block) = mkv.coded_block(i)? else { break };
102 let us = block.ts_ns / 1000;
103 if limit_us.is_some_and(|l| us > l) {
104 break;
105 }
106 match &mut ex {
107 Ex::H264(e) => e.push(block.bytes, Some(us)),
108 Ex::Hevc(e) => e.push(block.bytes, Some(us)),
109 }
110 }
111 Ok(match ex {
112 Ex::H264(e) => e.finish(rate),
113 Ex::Hevc(e) => e.finish(rate),
114 })
115}
116
117fn scan_mp4(path: &Path, limit_us: Option<i64>) -> crate::Result<Vec<ec_cc::TimedCc>> {
118 let file = File::open(path)?;
119 let mut reader = ec_mp4::Mp4Demuxer::new(BufReader::new(file)).map_err(mp4_error)?;
120 let Some(info) = reader
121 .tracks()
122 .iter()
123 .find(|t| t.media == Some(ec_core::MediaType::Video) && t.stream.is_some())
124 .cloned()
125 else {
126 return Ok(Vec::new());
127 };
128 let stream = info.stream.unwrap_or(0);
129 let (fourcc, entry) = sample_entry(path, info.track_id)?;
130 let (num, den) = reader
131 .streams()
132 .iter()
133 .find(|s| s.index == stream)
134 .map_or((1, 1000), |s| (s.time_base.num(), s.time_base.den()));
135 let us = move |ticks: i64| (i128::from(ticks) * i128::from(num) * 1_000_000 / i128::from(den.max(1))) as i64;
136 let count = reader.samples(stream).len();
137 let ticks = reader.samples(stream).iter().map(|s| i64::from(s.duration)).sum::<i64>().max(1);
138 let rate = (((count as i128 * i128::from(den.max(1))) / i128::from(ticks.max(1)) * 1000) as u32, 1000);
139 let rate = if rate.0 == 0 { (30_000, 1000) } else { rate };
140 let body = entry.get(78..).unwrap_or_default();
141 enum Ex {
142 H264(ec_cc::H264Extractor),
143 Hevc(ec_cc::HevcExtractor),
144 }
145 let mut ex = match &fourcc {
146 b"avc1" | b"avc3" => {
147 let mut e = ec_cc::H264Extractor::new(ec_cc::extract::NalFormat::LengthPrefixed(4));
148 e.set_extradata(child(body, b"avcC").unwrap_or_default());
149 Ex::H264(e)
150 }
151 b"hvc1" | b"hev1" => {
152 let mut e = ec_cc::HevcExtractor::new(ec_cc::extract::NalFormat::LengthPrefixed(4));
153 e.set_extradata(child(body, b"hvcC").unwrap_or_default());
154 Ex::Hevc(e)
155 }
156 _ => return Ok(Vec::new()),
157 };
158 for i in 0..count {
159 let cts = us(reader.samples(stream)[i].cts);
160 if limit_us.is_some_and(|l| cts > l) {
161 break;
162 }
163 let packet = match reader.read_sample(stream, i) {
164 Ok(p) => p,
165 Err(ec_core::Error::Eof) => break,
166 Err(e) => return Err(mp4_error(e)),
167 };
168 match &mut ex {
169 Ex::H264(e) => e.push(packet.data.as_ref(), Some(cts)),
170 Ex::Hevc(e) => e.push(packet.data.as_ref(), Some(cts)),
171 }
172 }
173 Ok(match ex {
174 Ex::H264(e) => e.finish(rate),
175 Ex::Hevc(e) => e.finish(rate),
176 })
177}
178
179/// The caption tracks of `path` with all their cues: the full scan, once per file. Empty when the
180/// picture carries no captions (or is a codec whose captions are not read); never an error for a
181/// file the scan cannot walk -- a file's own subtitle tracks must still list.
182pub fn tracks(path: &Path) -> Arc<Vec<CaptionTrack>> {
183 let k = key(path);
184 if let Some(hit) = cache(true).lock().ok().and_then(|c| c.get(&k).cloned()) {
185 return hit;
186 }
187 let found = Arc::new(scan(path, None).map(|t| decode(&t)).unwrap_or_default());
188 if let Ok(mut c) = cache(true).lock() {
189 c.insert(k, found.clone());
190 }
191 found
192}
193
194fn decode(timed: &[ec_cc::TimedCc]) -> Vec<CaptionTrack> {
195 let dec = ec_cc::decode_all(timed);
196 let mut out: Vec<CaptionTrack> = Vec::new();
197 let all = dec.cea608.into_iter().map(|c| (u64::from(c.channel), c)).chain(dec.cea708.into_iter().map(|c| (5, c)));
198 for (channel, c) in all {
199 let number = TRACK_BASE + channel;
200 match out.iter_mut().find(|t| t.number == number) {
201 Some(t) => t.cues.push(c),
202 None => out.push(CaptionTrack { number, name: track_name(number), cues: vec![c] }),
203 }
204 }
205 out.sort_by_key(|t| t.number);
206 out
207}
208
209/// The caption tracks `path` appears to carry, from the first seconds of picture only: number and
210/// name, no cues. Cached. A listing aid -- a file whose captions start later lists none here, and
211/// the import's full scan ([`tracks`]) is the truth.
212pub fn present(path: &Path) -> Arc<Vec<CaptionTrack>> {
213 let k = key(path);
214 if let Some(hit) = cache(true).lock().ok().and_then(|c| c.get(&k).cloned()) {
215 return hit;
216 }
217 if let Some(hit) = cache(false).lock().ok().and_then(|c| c.get(&k).cloned()) {
218 return hit;
219 }
220 let timed = scan(path, Some(PROBE_SECS * 1_000_000)).unwrap_or_default();
221 let mut found: Vec<u64> = decode(&timed).iter().map(|t| t.number).collect();
222 // Captions are on the wire but no cue has closed yet: name the channel the pairs are on.
223 for t in timed.iter().flat_map(|t| &t.triplets).filter(|t| t.valid && (t.data[0] & 0x7f) != 0) {
224 let n = match t.cc_type {
225 0 => 1,
226 1 => 3,
227 2 | 3 => 5,
228 _ => continue,
229 } + TRACK_BASE;
230 if !found.contains(&n) {
231 found.push(n);
232 }
233 }
234 found.sort_unstable();
235 let out = Arc::new(found.into_iter().map(|number| CaptionTrack { number, name: track_name(number), cues: Vec::new() }).collect());
236 if let Ok(mut c) = cache(false).lock() {
237 c.insert(k, Arc::clone(&out));
238 }
239 out
240}