| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::collections::HashMap; |
| 15 | use std::sync::{Arc, Mutex}; |
| 16 | use std::time::SystemTime; |
| 17 | |
| 18 | use super::*; |
| 19 | |
| 20 | |
| 21 | |
| 22 | pub const TRACK_BASE: u64 = 1 << 32; |
| 23 | |
| 24 | |
| 25 | const PROBE_SECS: i64 = 10; |
| 26 | |
| 27 | |
| 28 | pub fn is_caption_track(number: u64) -> bool { |
| 29 | number > TRACK_BASE && number <= TRACK_BASE + 5 |
| 30 | } |
| 31 | |
| 32 | |
| 33 | pub 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 | |
| 42 | #[derive(Clone, Debug)] |
| 43 | pub struct CaptionTrack { |
| 44 | pub number: u64, |
| 45 | pub name: String, |
| 46 | pub cues: Vec<ec_cc::CaptionCue>, |
| 47 | } |
| 48 | |
| 49 | type Key = (std::path::PathBuf, u64, Option<SystemTime>); |
| 50 | type Cache = Mutex<HashMap<Key, Arc<Vec<CaptionTrack>>>>; |
| 51 | |
| 52 | fn 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 | |
| 61 | fn 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 | |
| 68 | fn 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 | |
| 78 | fn 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 | |
| 117 | fn 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 | |
| 180 | |
| 181 | |
| 182 | pub 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 | |
| 194 | fn 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 | |
| 210 | |
| 211 | |
| 212 | pub 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 | |
| 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 | } |