forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

ts.rs1409 lines, 56.1 KiBHistoryRawDownload
1//! MPEG transport streams -- `.ts`, `.mts`, `.m2ts`, `.m2t` -- over the family's own
2//! demuxer, `ec-mpegts`. The file the AVCHD camcorders, the broadcast recorders and the
3//! Blu-ray rippers write, and the one container edith could not open at all before.
4//!
5//! Three readers live here, all of them over one [`ec_mpegts::TsDemuxer`]:
6//!
7//! - [`TsDemuxer`], the picture: H.264 and HEVC access units in Annex-B (MPEG-1/2 video
8//! as the pictures with their sequence header), the parameter
9//! sets re-injected ahead of a keyframe that lacks them, the same four calls the
10//! mp4 and Matroska doors answer ([`Demuxer`]).
11//! - [`TsAudio`], one sound track, with its own demuxer so a seek on the sound alone
12//! lands where the sound is and not at the picture's keyframe, and [`TsDecoder`], the
13//! codec behind it (AAC in ADTS, AC-3, E-AC-3, TrueHD, MP3, HDMV LPCM, DTS).
14//! - [`subtitles`], the PGS tracks, as the same display sets Matroska carries.
15//!
16//! **Time.** A transport stream's first timestamp is not 0 (a camcorder starts at
17//! seconds, a broadcast anywhere, a long recording near the 33-bit wrap), and its
18//! picture and its sound do not start together. Source time 0 is the first *picture*
19//! (its earliest presentation timestamp); a file with no picture counts from its
20//! first sound. Everything else is placed against that origin, so the sound that
21//! starts 80 ms after the picture starts 80 ms into the clip -- the offset a player
22//! honours -- and sound that starts before the picture is trimmed to the clip.
23//!
24//! **Refusals.** DTS and TrueHD decode ([`TsDecoder`]); LATM and the other kinds
25//! `ec-mpegts` has no demux path for are named, with the ffmpeg command that makes
26//! the file usable ([`refusal_text_for`]).
27
28use std::collections::VecDeque;
29
30use ec_core::registry::{Decoder as _, SeekMode};
31use ec_core::timebase::{TimeBase, Timestamp};
32use ec_core::{CodecId, Frame, MediaParameters, MediaType};
33use ec_mpegts::{StreamKind as TsKind, VideoFraming};
34
35use super::*;
36
37/// The 90 kHz clock every packet of the demuxer is stamped in.
38const TICKS: i64 = 90_000;
39
40fn tb() -> TimeBase {
41 TimeBase::new(1, TICKS)
42}
43
44/// Whether `path` is a transport stream: its extension, or -- for a name that says
45/// nothing -- its bytes. A container whose magic is Matroska's or an mp4's is never
46/// one, whatever the file is called, and a standalone sound file or a still is not
47/// sniffed at all.
48pub fn is_mpegts(path: &Path) -> bool {
49 if sniff_container(path).is_some() {
50 return false;
51 }
52 let ext = path
53 .extension()
54 .and_then(|e| e.to_str())
55 .map(str::to_ascii_lowercase);
56 if matches!(ext.as_deref(), Some("ts" | "mts" | "m2ts" | "m2t" | "tp" | "trp")) {
57 return true;
58 }
59 if crate::is_audio(path) || crate::is_image(path) {
60 return false;
61 }
62 let mut head = vec![0u8; 8 * 1024];
63 let read = File::open(path)
64 .and_then(|mut f| f.read(&mut head))
65 .unwrap_or(0);
66 ec_mpegts::is_mpegts(&head[..read])
67}
68
69pub(crate) fn ts_error(e: ec_core::Error) -> crate::Error {
70 format!("MPEG transport stream: {e}").into()
71}
72
73/// The words for a track this build does not read: what `ec-mpegts` names it, and the
74/// ffmpeg line that turns the file into one edith opens.
75/// The refusal wording for a transport stream (`ps` false) or a program stream.
76pub(crate) fn refusal_text_for(why: &str, video: bool, flavor: Flavor) -> String {
77 let input = flavor.input_name();
78 let fix = match (video, flavor) {
79 // An AVI's picture is rarely one an mp4 takes as it is.
80 (true, _) | (false, Flavor::Avi | Flavor::Dv) => format!("ffmpeg -i {input} -c:v libx264 -c:a aac out.mp4"),
81 (false, _) => format!("ffmpeg -i {input} -c:v copy -c:a aac out.mp4"),
82 };
83 format!("{why} — convert it with {fix}")
84}
85
86/// The ffmpeg line that turns a file of this container into one edith opens.
87pub(crate) fn convert_line(flavor: Flavor) -> String {
88 format!("ffmpeg -i {} -c:v libx264 -c:a aac out.mp4", flavor.input_name())
89}
90
91/// The kind name of a picture stream this build refuses, in an AVI.
92pub(crate) const REFUSED_VIDEO: &str = "refused_video";
93
94/// Which container a [`Src`] reads.
95#[derive(Clone, Copy, PartialEq, Eq, Debug)]
96pub(crate) enum Flavor {
97 Ts,
98 Ps,
99 Avi,
100 Dv,
101}
102
103impl Flavor {
104 pub(crate) fn of(path: &Path) -> Self {
105 if super::avi::is_avi(path) {
106 Self::Avi
107 } else if super::dv::is_dv(path) {
108 Self::Dv
109 } else if super::ps::is_mpegps(path) {
110 Self::Ps
111 } else {
112 Self::Ts
113 }
114 }
115
116 fn input_name(self) -> &'static str {
117 match self {
118 Self::Ts => "in.ts",
119 Self::Ps => "in.mpg",
120 Self::Avi => "in.avi",
121 Self::Dv => "in.dv",
122 }
123 }
124}
125
126/// Whether a track kind is a picture this reads (or, in an AVI, a refused one).
127fn is_picture_kind(kind: &TsKind) -> bool {
128 kind.is_video()
129 || matches!(kind, TsKind::Other(n) if matches!(n.as_str(), "mjpeg" | "prores" | "dnxhd" | "dvvideo") || n.starts_with("mpeg4") || n.starts_with("msmpeg4") || n == "rawvideo" || n.starts_with(REFUSED_VIDEO))
130}
131
132type Reader = BufReader<File>;
133
134/// The one demuxer behind every reader here: a transport stream, or -- for `.mpg`, `.vob`,
135/// `.m2v` and the rest ([`super::ps`]) -- a program stream. Both speak the same packets and
136/// the same track list, so the pictures, the sound and the probe are written once.
137pub(crate) enum Src {
138 Ts(ec_mpegts::TsDemuxer<Reader>),
139 Ps(ec_mpegts::PsDemuxer<Reader>),
140 Avi(Box<super::avi::AviSrc>),
141 Dv(Box<super::dv::DvSrc>),
142}
143
144impl Src {
145 pub(crate) fn open(path: &Path, flavor: Flavor) -> crate::Result<Self> {
146 if flavor == Flavor::Avi {
147 return super::avi::AviSrc::open(path).map(|d| Self::Avi(Box::new(d)));
148 }
149 if flavor == Flavor::Dv {
150 return super::dv::DvSrc::open(path).map(|d| Self::Dv(Box::new(d)));
151 }
152 let file = File::open(path)?;
153 let reader = BufReader::with_capacity(256 << 10, file);
154 match flavor {
155 Flavor::Ps => ec_mpegts::PsDemuxer::new(reader).map(Self::Ps).map_err(super::ps::ps_error),
156 _ => ec_mpegts::TsDemuxer::new(reader).map(Self::Ts).map_err(ts_error),
157 }
158 }
159
160 pub(crate) fn streams(&self) -> &[ec_core::StreamInfo] {
161 match self {
162 Self::Ts(d) => d.streams(),
163 Self::Ps(d) => d.streams(),
164 Self::Avi(d) => d.streams(),
165 Self::Dv(d) => d.streams(),
166 }
167 }
168
169 pub(crate) fn tracks(&self) -> Vec<ec_mpegts::TrackInfo> {
170 match self {
171 Self::Ts(d) => d.tracks(),
172 Self::Ps(d) => d.tracks(),
173 Self::Avi(d) => d.tracks(),
174 Self::Dv(d) => d.tracks(),
175 }
176 }
177
178 pub(crate) fn next_packet(&mut self) -> ec_core::Result<ec_core::Packet> {
179 match self {
180 Self::Ts(d) => d.next_packet(),
181 Self::Ps(d) => d.next_packet(),
182 Self::Avi(d) => d.next_packet(),
183 Self::Dv(d) => d.next_packet(),
184 }
185 }
186
187 pub(crate) fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> ec_core::Result<()> {
188 match self {
189 Self::Ts(d) => d.seek(stream, to, mode),
190 Self::Ps(d) => d.seek(stream, to, mode),
191 Self::Avi(d) => d.seek(stream, to, mode),
192 Self::Dv(d) => d.seek(stream, to, mode),
193 }
194 }
195
196 pub(crate) fn set_video_framing(&mut self, framing: VideoFraming) {
197 match self {
198 Self::Ts(d) => d.set_video_framing(framing),
199 Self::Ps(d) => d.set_video_framing(framing),
200 // An AVI's H.264 is Annex B already.
201 Self::Avi(_) | Self::Dv(_) => {}
202 }
203 }
204
205 pub(crate) fn duration_secs(&self) -> Option<f64> {
206 match self {
207 Self::Ts(d) => d.duration_secs(),
208 Self::Ps(d) => d.duration_secs(),
209 Self::Avi(d) => d.duration_secs(),
210 Self::Dv(d) => d.duration_secs(),
211 }
212 }
213}
214
215fn open_demuxer(path: &Path, flavor: Flavor) -> crate::Result<Src> {
216 Src::open(path, flavor)
217}
218
219/// What the header of a transport stream says, from one open.
220pub(crate) struct TsFile {
221 /// The picture stream's index, if the file has a picture this reads.
222 pub video: Option<u32>,
223 /// Source time 0, in ticks: the first picture's first presentation time, or the
224 /// earliest sound/subtitle start where there is no picture.
225 pub origin: i64,
226 /// Every audio track of the program, in PMT order, the refused ones too.
227 pub audio: Vec<TsAudioInfo>,
228 /// Every PGS track, in PMT order.
229 pub subtitles: Vec<TsSubInfo>,
230 /// The refusal of the first picture track this build does not read, if any.
231 pub refused_video: Option<String>,
232 /// ffprobe's name of that refused picture (`rawvideo`, `dvvideo`, `mpeg4`, ...).
233 pub refused_codec: Option<String>,
234}
235
236pub(crate) struct TsAudioInfo {
237 /// The demuxer's stream index; `None` for a refused track.
238 pub stream: Option<u32>,
239 /// ffprobe's name: `aac`, `ac3`, `eac3`, `mp3`, `pcm_bluray`, `mp2`, `dts`, ...
240 pub codec: String,
241 pub codec_id: Option<CodecId>,
242 pub language: Option<String>,
243 pub channels: u16,
244 pub sample_rate: u32,
245 pub start: Option<i64>,
246 pub duration: Option<i64>,
247 pub refusal: Option<String>,
248}
249
250pub(crate) struct TsSubInfo {
251 pub stream: u32,
252 /// The Matroska codec id the track's packets are read as: PGS, VobSub or DVB.
253 pub codec: &'static str,
254 /// ffprobe's name of it.
255 pub probe_name: &'static str,
256 pub language: Option<String>,
257}
258
259fn ffprobe_audio_name(kind: &TsKind, params: Option<CodecId>) -> String {
260 match (kind, params) {
261 (TsKind::MpegAudio, Some(CodecId::Mp3)) => "mp3".into(),
262 (TsKind::MpegAudio, Some(CodecId::Mp1)) => "mp1".into(),
263 (TsKind::MpegAudio, _) => "mp2".into(),
264 (TsKind::Lpcm, _) => "pcm_bluray".into(),
265 (TsKind::DvdLpcm, _) => "pcm_dvd".into(),
266 (k, _) => k.name(),
267 }
268}
269
270/// Opens `path` and describes it. Cheap -- the demuxer stops reading as soon as every
271/// stream has its parameters.
272pub(crate) fn describe(path: &Path) -> crate::Result<TsFile> {
273 let d = open_demuxer(path, Flavor::of(path))?;
274 Ok(describe_open(&d))
275}
276
277fn describe_open(d: &Src) -> TsFile {
278 let streams = d.streams();
279 let info = |i: u32| streams.iter().find(|s| s.index == i);
280 let mut video = None;
281 let mut refused_video = None;
282 let mut refused_codec = None;
283 let mut audio = Vec::new();
284 let mut subtitles = Vec::new();
285 for t in d.tracks() {
286 match (&t.kind, t.stream) {
287 (k, Some(i)) if is_picture_kind(k) => {
288 video.get_or_insert(i);
289 }
290 (k, None) if is_picture_kind(k) => {
291 refused_video.get_or_insert_with(|| t.refusal.clone().unwrap_or_else(|| k.name()));
292 refused_codec.get_or_insert_with(|| {
293 k.name().strip_prefix(REFUSED_VIDEO).unwrap_or_default().trim_start_matches(':').to_string()
294 });
295 }
296 (TsKind::Pgs | TsKind::DvdSub | TsKind::DvbSub, Some(stream)) => {
297 let (codec, probe_name) = match t.kind {
298 TsKind::DvdSub => (VOBSUB, "dvd_subtitle"),
299 TsKind::DvbSub => (DVBSUB, "dvb_subtitle"),
300 _ => (PGS, "hdmv_pgs_subtitle"),
301 };
302 subtitles.push(TsSubInfo {
303 stream,
304 codec,
305 probe_name,
306 language: t.language.clone(),
307 })
308 }
309 (TsKind::Pgs | TsKind::DvdSub | TsKind::DvbSub, None) => {}
310 (kind, _) if is_audio_kind(kind, t.stream_type) => {
311 let s = t.stream.and_then(info);
312 let (channels, sample_rate) = match s.map(|s| &s.params.media) {
313 Some(MediaParameters::Audio(a)) => (a.layout.channel_count() as u16, a.sample_rate),
314 _ => (0, 0),
315 };
316 audio.push(TsAudioInfo {
317 stream: t.stream,
318 codec: ffprobe_audio_name(&t.kind, s.map(|s| s.params.codec)),
319 codec_id: s.map(|s| s.params.codec),
320 language: t.language.clone(),
321 channels,
322 sample_rate,
323 start: s.and_then(|s| s.start_time),
324 duration: s.and_then(|s| s.duration),
325 refusal: t.refusal.clone(),
326 });
327 }
328 _ => {}
329 }
330 }
331 let starts = |pred: &dyn Fn(&ec_core::StreamInfo) -> bool| {
332 streams
333 .iter()
334 .filter(|s| pred(s))
335 .filter_map(|s| s.start_time)
336 .min()
337 };
338 let origin = video
339 .and_then(info)
340 .and_then(|s| s.start_time)
341 .or_else(|| starts(&|s| s.params.codec.media_type() == MediaType::Audio))
342 .or_else(|| starts(&|_| true))
343 .unwrap_or(0);
344 TsFile {
345 video,
346 origin,
347 audio,
348 subtitles,
349 refused_video,
350 refused_codec,
351 }
352}
353
354/// Whether a PMT entry is sound: the known audio kinds (TrueHD included), and the `Other`
355/// types that are DTS-HD or an AVI's refused audio, listed by name.
356fn is_audio_kind(kind: &TsKind, stream_type: u8) -> bool {
357 match kind {
358 TsKind::AacAdts
359 | TsKind::AacLatm
360 | TsKind::Ac3
361 | TsKind::Eac3
362 | TsKind::TrueHd
363 | TsKind::MpegAudio
364 | TsKind::Lpcm
365 | TsKind::Dts
366 | TsKind::DvdLpcm => true,
367 TsKind::Other(name) => {
368 // The last two rows are an AVI's: its PCM by ffprobe's name, and the tags it refuses.
369 matches!(name.as_str(), "dts" | "dts_hd" | "aac_raw")
370 || name.starts_with("pcm_")
371 || name.starts_with("wav_")
372 || matches!(name.as_str(), "wmav1" | "wmav2" | "wmapro" | "adpcm_ms" | "adpcm_ima_wav" | "mp3" | "aac")
373 || matches!(stream_type, 0x82 | 0x83 | 0x85 | 0x86 | 0xA2)
374 }
375 _ => false,
376 }
377}
378
379// ----------------------------------------------------------------------------------
380// The picture
381// ----------------------------------------------------------------------------------
382
383/// H.264 or HEVC out of a transport stream, one access unit at a time.
384pub struct TsDemuxer {
385 inner: Src,
386 flavor: Flavor,
387 stream: u32,
388 pub(crate) codec: Codec,
389 /// The first picture's presentation time, in ticks: frame 0.
390 start: i64,
391 /// Ticks per frame.
392 tpf: f64,
393 /// Annex-B VPS/SPS/PPS (SPS/PPS for H.264), re-injected ahead of a keyframe that
394 /// does not carry its own.
395 pub(crate) config: Vec<u8>,
396 pub(crate) profile: Option<&'static str>,
397 pub(crate) bit_depth: u8,
398 pub(crate) chroma: Option<Chroma>,
399 pub(crate) hevc_profile: Option<u8>,
400 pub(crate) light: ContentLight,
401 /// The access unit [`Self::seek_to_sync_at_or_before`] read to learn where it
402 /// landed, handed out by the next [`Self::next_access_unit`].
403 pending: VecDeque<Vec<u8>>,
404 /// An AVI's field order for its MJPEG, from the demuxer ([`Self::field_order`]).
405 field_order: Option<ec_core::frame::Interlace>,
406 /// An AVI's FourCC for its MPEG-4 Part 2 picture (`XVID`, `DIVX`...); see [`Demuxer::fourcc`].
407 pub(crate) fourcc: Option<[u8; 4]>,
408 /// The picture stream's codec id (MS-MPEG4 version 2 or 3 share one `Codec`) and its stated size.
409 pub(crate) codec_id: CodecId,
410 pub(crate) size: (u32, u32),
411 /// An AVI's raw video `BITMAPINFOHEADER`; empty for every other codec.
412 pub(crate) header: Vec<u8>,
413 /// What a DV picture states (interlace and field order), read off its first frame at open
414 /// ([`Demuxer::fill_intra`]); the default (progressive) for every other codec here.
415 pub(crate) intra: crate::decode::intra::IntraFacts,
416 /// Bytes of picture and of sound over the file, for the bitrate card.
417 path: PathBuf,
418 /// The stream asks for 3:2 field repeats: its pictures are 23.976p film frames
419 /// and [`VideoMeta::frame_rate`] says so ([`crate::ivtc::Repeats`]).
420 pub(crate) soft_pulldown: bool,
421}
422
423impl TsDemuxer {
424 pub(crate) fn colour_tags(&self) -> Tags {
425 bitstream_tags(self.codec, &self.config)
426 }
427
428 pub(crate) fn path(&self) -> &Path {
429 &self.path
430 }
431
432 pub(crate) fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
433 let flavor = Flavor::of(path);
434 let mut inner = open_demuxer(path, flavor)?;
435 let file = describe_open(&inner);
436 let Some(stream) = file.video else {
437 return Err(match (file.refused_video, flavor) {
438 (Some(why), _) => refusal_text_for(&why, true, flavor).into(),
439 (None, Flavor::Avi) => {
440 crate::Error::from(NoVideoTrack("this AVI file has no video track".into()))
441 }
442 (None, Flavor::Dv) => {
443 crate::Error::from(NoVideoTrack("this DV file has no video track".into()))
444 }
445 (None, flavor) => crate::Error::from(NoVideoTrack(format!(
446 "this MPEG {} stream has no video track",
447 if flavor == Flavor::Ps { "program" } else { "transport" }
448 ))),
449 });
450 };
451 let info = inner
452 .streams()
453 .iter()
454 .find(|s| s.index == stream)
455 .ok_or("MPEG transport stream: the picture stream vanished")?
456 .clone();
457 let MediaParameters::Video(video) = info.params.media.clone() else {
458 return Err("MPEG transport stream: the picture stream has no picture parameters".into());
459 };
460 let codec = match info.params.codec {
461 CodecId::H264 => Codec::H264,
462 CodecId::H265 => Codec::Hevc,
463 CodecId::Mpeg2Video => Codec::Mpeg2,
464 CodecId::Mjpeg => Codec::Mjpeg,
465 CodecId::ProRes => Codec::ProRes,
466 CodecId::Dnxhd => Codec::Dnxhd,
467 CodecId::DvVideo => Codec::Dv,
468 CodecId::Mpeg4Part2 => Codec::Mpeg4,
469 CodecId::MsMpeg4V2 | CodecId::MsMpeg4V3 => Codec::MsMpeg4,
470 CodecId::RawVideo => Codec::Raw,
471 other => return Err(format!("MPEG transport stream: {other:?} video is not supported").into()),
472 };
473 for stated in [video.width, video.height] {
474 if stated > crate::MAX_RESOLUTION {
475 return Err(unsupported_display_size(u64::from(stated)));
476 }
477 }
478 let extradata = info
479 .params
480 .extradata
481 .as_ref()
482 .map(|b| b.as_ref().to_vec())
483 .unwrap_or_default();
484 let (mut config, mut bit_depth, mut hevc_profile, mut profile) = (Vec::new(), 8, None, None);
485 let mut header = Vec::new();
486 match codec {
487 Codec::H264 => {
488 config = parse_avcc(&extradata)?.1;
489 bit_depth = avc_bit_depth(&config)?;
490 profile = video_profile::h264(&config);
491 }
492 Codec::Hevc => {
493 let (_, sets, depth) = parse_hvcc(&extradata)?;
494 config = sets;
495 bit_depth = depth;
496 hevc_profile = extradata.get(1).map(|b| b & 0x1f);
497 profile = video_profile::hevc_record(&extradata);
498 }
499 // The sequence header (and its extension) the decoder starts from, in front of
500 // every keyframe that lacks one.
501 Codec::Mpeg2 => {
502 config = extradata.clone();
503 profile = mpeg2_profile(&config);
504 }
505 // The raw layout is stated by the BITMAPINFOHEADER alone.
506 // The BITMAPINFOHEADER states the layout; it is not a parameter set to put in front
507 // of the pictures.
508 Codec::Raw => {
509 header = extradata.clone();
510 profile = Some(video_profile::raw(&header));
511 }
512 Codec::MsMpeg4 => profile = Some(if info.params.codec == CodecId::MsMpeg4V2 { "v2" } else { "v3" }),
513 _ => {}
514 }
515 let chroma = bitstream_chroma(codec, &config);
516 // A stream states its rate by its timestamps; an estimate that is missing (a
517 // single picture) falls back to the broadcast rate nothing else could be.
518 let fps = video
519 .frame_rate
520 .map(|r| r.num() as f64 / r.den() as f64)
521 .filter(|f| *f > 0.0)
522 .unwrap_or(25.0);
523 let tpf = TICKS as f64 / fps;
524 let start = info.start_time.unwrap_or(file.origin);
525 // Frames: the picture's span over its rate. The demuxer's duration runs from the
526 // first presentation time to the end of the last picture, found by a tail scan.
527 let frames = match info.duration {
528 Some(d) if d > 0 => ((d as f64 / tpf).round() as u32).max(1),
529 _ => 1,
530 };
531 let pixel_aspect = video
532 .sample_aspect_ratio
533 .and_then(|r| PixelAspect::stated(r.num() as u32, r.den() as u32))
534 .unwrap_or(PixelAspect::SQUARE);
535 let (width, height) = (pixel_aspect.width_factor(video.width), video.height);
536 let tags = bitstream_tags(codec, &config);
537 let mut meta = VideoMeta {
538 width,
539 height,
540 coded_width: video.width,
541 coded_height: video.height,
542 pixel_aspect,
543 frame_rate: fps,
544 frame_count: frames,
545 codec,
546 color: ColorDescription::resolve_sized(Tags::default(), tags, width, height),
547 matrix_assumed: ColorDescription::matrix_assumed(Tags::default(), tags),
548 rotation: Rotation::None,
549 };
550 inner.set_video_framing(VideoFraming::AnnexB);
551 // An AVI's MPEG-4 picture carries its FourCC in the track's kind (`mpeg4:XVID`).
552 let fourcc = inner.tracks().iter().find(|t| t.stream == Some(stream)).and_then(|t| match &t.kind {
553 TsKind::Other(n) => n.strip_prefix("mpeg4:").and_then(|f| f.as_bytes().try_into().ok()),
554 _ => None,
555 });
556 let field_order = match &inner {
557 Src::Avi(a) => a.field_order(stream),
558 _ => None,
559 };
560 let mut demuxer = Self {
561 inner,
562 flavor,
563 stream,
564 codec,
565 start,
566 tpf,
567 config,
568 profile,
569 bit_depth,
570 chroma,
571 hevc_profile,
572 light: ContentLight::default(),
573 pending: VecDeque::new(),
574 field_order,
575 fourcc,
576 codec_id: info.params.codec,
577 size: (video.width, video.height),
578 header,
579 intra: Default::default(),
580 path: path.to_path_buf(),
581 soft_pulldown: false,
582 };
583 demuxer.seek_to_sync_at_or_before(0);
584 // Soft pulldown: the coded pictures are the 23.976p film frames and the stream
585 // asks the player to repeat fields, so its pictures arrive 2 and 3 fields
586 // apart and the shortest gap, which the rate was estimated from, is the
587 // 29.97 of the repeated display. The pictures' own rate is four fifths of it
588 // ([`crate::ivtc::Repeats`]).
589 if matches!(codec, Codec::Mpeg2 | Codec::H264) && flavor != Flavor::Avi && fps > 25.0 {
590 let mut repeats = crate::ivtc::Repeats::default();
591 for _ in 0..crate::ivtc::SAMPLE {
592 match demuxer.next_access_unit() {
593 Ok(Some(au)) if codec == Codec::Mpeg2 => repeats.mpeg2(&au),
594 Ok(Some(au)) => repeats.h264(&demuxer.config, &au),
595 _ => break,
596 }
597 }
598 if repeats.soft() {
599 let film = fps * 0.8;
600 demuxer.soft_pulldown = true;
601 demuxer.tpf = TICKS as f64 / film;
602 meta.frame_rate = film;
603 meta.frame_count = match info.duration {
604 Some(d) if d > 0 => ((d as f64 / demuxer.tpf).round() as u32).max(1),
605 _ => 1,
606 };
607 }
608 demuxer.seek_to_sync_at_or_before(0);
609 }
610 Ok((meta, demuxer))
611 }
612
613 /// The next picture's bytes in decode order, `None` at the end of the file.
614 pub(crate) fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
615 if let Some(au) = self.pending.pop_front() {
616 return Ok(Some(au));
617 }
618 Ok(self.read_picture()?.map(|(_, au)| au))
619 }
620
621 /// One picture and its time, with the parameter sets in front of a keyframe that
622 /// carries none (a recovery-point frame in a stream that repeats them only now
623 /// and then).
624 fn read_picture(&mut self) -> crate::Result<Option<(i64, Vec<u8>)>> {
625 loop {
626 let packet = match self.inner.next_packet() {
627 Ok(p) => p,
628 Err(ec_core::Error::Eof) => return Ok(None),
629 Err(e) => return Err(ts_error(e)),
630 };
631 if packet.stream != self.stream {
632 continue;
633 }
634 let pts = packet.pts.or(packet.dts).unwrap_or(self.start);
635 let bytes: &[u8] = &packet.data;
636 let present = match self.codec {
637 Codec::Mpeg2 => has_sequence_header(bytes),
638 codec => has_parameter_sets(codec, bytes),
639 };
640 if !packet.flags.keyframe || self.config.is_empty() || present {
641 return Ok(Some((pts, bytes.to_vec())));
642 }
643 let mut au = Vec::with_capacity(self.config.len() + bytes.len());
644 au.extend_from_slice(&self.config);
645 au.extend_from_slice(bytes);
646 return Ok(Some((pts, au)));
647 }
648 }
649
650 /// Puts the cursor on the latest keyframe whose presentation time is at or before
651 /// display frame `frame`, and returns the display index of that keyframe.
652 pub(crate) fn seek_to_sync_at_or_before(&mut self, frame: u32) -> i64 {
653 let mut slot_target = frame;
654 loop {
655 let (slot, lead) = self.seek_slot(slot_target);
656 let shown = slot + lead;
657 // An AVI's keyframe is placed by its slot in the file; its leading B pictures put
658 // its display index later, possibly past the frame asked for. Go back a keyframe.
659 if shown > i64::from(frame) && slot > 0 && self.flavor == Flavor::Avi {
660 slot_target = (slot - 1) as u32;
661 continue;
662 }
663 return shown;
664 }
665 }
666
667 /// Puts the cursor on the keyframe at or before decode slot / display frame `frame` and
668 /// returns its slot and the number of pictures displayed before it that follow it in the file.
669 fn seek_slot(&mut self, frame: u32) -> (i64, i64) {
670 self.pending.clear();
671 let target = self.start + (f64::from(frame) * self.tpf).round() as i64;
672 let target = target.max(self.start);
673 let landed = self
674 .inner
675 .seek(self.stream, Timestamp::new(target, tb()), SeekMode::SyncBefore)
676 .is_ok();
677 if !landed {
678 // A seek the file refuses (damage ahead of the target) starts over from the
679 // top rather than leaving the cursor where it was.
680 if let Ok(fresh) = open_demuxer(&self.path, self.flavor) {
681 self.inner = fresh;
682 self.inner.set_video_framing(VideoFraming::AnnexB);
683 }
684 }
685 match self.read_picture() {
686 Ok(Some((pts, au))) => {
687 self.pending.push_back(au);
688 let slot = (((pts - self.start) as f64) / self.tpf).round() as i64;
689 (slot, self.leading_b_pictures())
690 }
691 _ => (0, 0),
692 }
693 }
694
695 /// In an AVI, which has no timestamps, the keyframe just read ([`Self::pending`]) sits at its
696 /// decode slot; the B pictures that follow it at once are displayed *before* it, so its
697 /// display index is that many later. They are read ahead into `pending`.
698 fn leading_b_pictures(&mut self) -> i64 {
699 if self.flavor != Flavor::Avi || !matches!(self.codec, Codec::Mpeg2 | Codec::H264 | Codec::Mpeg4) {
700 return 0;
701 }
702 let (mut ahead, mut leading) = (Vec::new(), 0);
703 while ahead.len() < 16 {
704 let Ok(Some((_, au))) = self.read_picture() else { break };
705 let b = super::avi::is_b_picture(self.codec, &au);
706 ahead.push(au);
707 if !b {
708 break;
709 }
710 leading += 1;
711 }
712 self.pending.extend(ahead);
713 leading
714 }
715
716 /// The scan order of the fields of an AVI's interlaced MJPEG, where the file states one.
717 pub(crate) fn field_order(&self) -> Option<ec_core::frame::Interlace> {
718 self.field_order
719 }
720
721 /// Bytes of the picture stream, for the bitrate card: a walk of the file.
722 pub(crate) fn stream_bytes(&self) -> (Option<u64>, Option<u64>) {
723 let Ok(mut d) = open_demuxer(&self.path, self.flavor) else {
724 return (None, None);
725 };
726 let (mut video, mut audio) = (0u64, 0u64);
727 let first_audio = d
728 .tracks()
729 .into_iter()
730 .find(|t| matches!(
731 t.kind,
732 TsKind::AacAdts | TsKind::Ac3 | TsKind::Eac3 | TsKind::TrueHd | TsKind::MpegAudio | TsKind::Lpcm | TsKind::DvdLpcm
733 ) && t.stream.is_some())
734 .and_then(|t| t.stream);
735 while let Ok(p) = d.next_packet() {
736 if p.stream == self.stream {
737 video += p.data.len() as u64;
738 } else if Some(p.stream) == first_audio {
739 audio += p.data.len() as u64;
740 }
741 }
742 (Some(video), Some(audio))
743 }
744
745 /// The length the container's streams span, in seconds: the longest of them.
746 pub(crate) fn container_secs(&self) -> Option<f64> {
747 self.inner.duration_secs()
748 }
749}
750
751/// Whether an Annex-B access unit already carries the sets a decoder starts from.
752fn has_parameter_sets(codec: Codec, au: &[u8]) -> bool {
753 ec_mpegts::nal_units(au).any(|nal| match codec {
754 Codec::H264 => nal.first().is_some_and(|b| b & 0x1f == 7),
755 Codec::Hevc => nal.first().is_some_and(|b| (b >> 1) & 0x3f == 33),
756 _ => true,
757 })
758}
759
760/// ffprobe's name for the profile of an MPEG-2 sequence extension.
761fn mpeg2_profile(config: &[u8]) -> Option<&'static str> {
762 let b = crate::colorspace::mpeg2_extension(config, 1)?;
763 let code = (b.first()? & 0x0f) << 4 | b.get(1)? >> 4;
764 Some(match (code >> 4) & 7 {
765 5 => "Simple",
766 4 => "Main",
767 3 => "SNR Scalable",
768 2 => "Spatial Scalable",
769 1 => "High",
770 0 if code & 0x80 != 0 => "4:2:2",
771 _ => return None,
772 })
773}
774
775/// Whether an MPEG-1/2 picture packet leads with (or holds) a sequence header.
776fn has_sequence_header(au: &[u8]) -> bool {
777 au.windows(4).any(|w| w == [0, 0, 1, 0xB3])
778}
779
780// ----------------------------------------------------------------------------------
781// The sound
782// ----------------------------------------------------------------------------------
783
784/// What a decoded run of sound is: interleaved f32, the width it was decoded at, and the
785/// frames per channel it holds.
786pub(crate) struct Decoded {
787 pub samples: Vec<f32>,
788 pub channels: usize,
789 pub frames: u64,
790}
791
792/// A codec of a transport stream's sound, fed one packet at a time.
793pub(crate) enum TsDecoder {
794 Aac(Box<ec_aac::AacDecoder>),
795 Ac3(Box<ec_ac3::Ac3Decoder>),
796 /// Dolby TrueHD, one access unit per packet, as the Matroska path feeds it.
797 TrueHd(Box<ec_truehd::TrueHdDecoder>),
798 Mp3(Box<ec_mp3::Mp3Decoder>),
799 /// HDMV LPCM: the width of a sample in bytes, big-endian 16 bit or the little-endian
800 /// 24 bit the demuxer hands over, and the channel count.
801 Pcm { bytes: usize, big_endian: bool, channels: usize },
802 /// An AVI's little-endian PCM (8, 16, 24, 32 bit integer or 32 bit float).
803 PcmLe { codec: CodecId, channels: usize },
804 /// DTS, and an AVI's IMA / MS ADPCM, A-law and mu-law ([`crate::extaudio`]).
805 Ext(Box<crate::extaudio::ExtDecoder>),
806}
807
808/// Bits per sample of a PCM track, `None` for anything coded.
809pub(crate) fn pcm_depth<T: From<u8>>(codec: Option<CodecId>) -> Option<T> {
810 Some(T::from(match codec? {
811 CodecId::PcmU8 => 8,
812 CodecId::PcmS16Be | CodecId::PcmS16Le => 16,
813 CodecId::PcmS24Le => 24,
814 CodecId::PcmS32Le | CodecId::PcmF32Le => 32,
815 _ => return None,
816 }))
817}
818
819/// The little-endian PCM an AVI carries.
820fn is_pcm_le(codec: CodecId) -> bool {
821 matches!(
822 codec,
823 CodecId::PcmU8 | CodecId::PcmS16Le | CodecId::PcmS24Le | CodecId::PcmS32Le | CodecId::PcmF32Le
824 )
825}
826
827impl TsDecoder {
828 fn new(
829 codec: CodecId,
830 channels: usize,
831 sample_rate: u32,
832 stereo_downmix: bool,
833 asc: &[u8],
834 params: Option<&ec_core::CodecParameters>,
835 ) -> crate::Result<Self> {
836 Ok(match codec {
837 c if crate::extaudio::is_ext_codec(c) => {
838 let params = params.ok_or("the sound track states no codec parameters")?;
839 Self::Ext(Box::new(crate::extaudio::ExtDecoder::new(params)?))
840 }
841 CodecId::Aac => Self::Aac(Box::new(match asc.is_empty() {
842 true => ec_aac::AacDecoder::new(),
843 false => ec_aac::AacDecoder::with_config_bytes(asc)
844 .map_err(|e| format!("AAC configuration: {e}"))?,
845 })),
846 CodecId::Ac3 | CodecId::EAc3 => Self::Ac3(Box::new(ec_ac3::Ac3Decoder::with_options(ec_ac3::Options {
847 downmix: match stereo_downmix {
848 true => ec_ac3::Downmix::Stereo,
849 false => ec_ac3::Downmix::Native,
850 },
851 ..ec_ac3::Options::default()
852 }))),
853 CodecId::TrueHd => Self::TrueHd(Box::new(ec_truehd::TrueHdDecoder::new())),
854 CodecId::Mp3 | CodecId::Mp2 | CodecId::Mp1 => Self::Mp3(Box::new(
855 ec_mp3::Mp3Decoder::new(ec_mp3::layer_codec_parameters(
856 match codec {
857 CodecId::Mp1 => 1,
858 CodecId::Mp2 => 2,
859 _ => 3,
860 },
861 sample_rate,
862 channels.max(1),
863 ))
864 .map_err(ts_error)?,
865 )),
866 CodecId::PcmS16Be => Self::Pcm { bytes: 2, big_endian: true, channels: channels.max(1) },
867 CodecId::PcmS24Le => Self::Pcm { bytes: 3, big_endian: false, channels: channels.max(1) },
868 c if is_pcm_le(c) => Self::PcmLe { codec: c, channels: channels.max(1) },
869 other => return Err(format!("MPEG transport stream: {other:?} sound is not supported").into()),
870 })
871 }
872
873 /// One packet in. `Ok(None)` when the codec wants more before it answers.
874 pub(crate) fn decode(&mut self, data: &[u8]) -> crate::Result<Option<Decoded>> {
875 match self {
876 Self::Aac(d) => {
877 let pcm = d
878 .decode(data, None)
879 .map_err(|e| format!("AAC decode failed: {e}"))?;
880 let channels = usize::from(pcm.channels).max(1);
881 let frames = (pcm.samples.len() / channels) as u64;
882 Ok((frames > 0).then_some(Decoded { samples: pcm.samples, channels, frames }))
883 }
884 Self::Ac3(d) => match d.decode_frame(data) {
885 Ok(frame) => {
886 let samples: Vec<f32> = frame.data[0]
887 .as_chunks::<4>()
888 .0
889 .iter()
890 .map(|s| f32::from_le_bytes(*s))
891 .collect();
892 let frames = frame.samples as u64;
893 let channels = (samples.len() as u64 / frames.max(1)).max(1) as usize;
894 Ok(Some(Decoded { samples, channels, frames }))
895 }
896 Err(ec_ac3::Error::NeedMore) => Ok(None),
897 Err(e) => Err(format!("AC-3 decode failed: {e}").into()),
898 },
899 Self::TrueHd(d) => match d.decode_access_unit(data) {
900 Ok(Some(frame)) => {
901 let channels = frame.layout.channel_count().max(1);
902 let frames = frame.samples as u64;
903 let samples = crate::audio::truehd_f32(&frame);
904 Ok(Some(Decoded { samples, channels, frames }))
905 }
906 // No restart header seen yet: nothing to emit for this unit.
907 Ok(None) | Err(ec_core::Error::NeedMore) => Ok(None),
908 Err(e) => Err(format!("TrueHD decode failed: {e}").into()),
909 },
910 Self::Mp3(d) => {
911 let packet = ec_core::Packet::new(0, tb(), data.to_vec());
912 d.send_packet(&packet).map_err(ts_error)?;
913 let mut samples = Vec::new();
914 let mut channels = 0usize;
915 loop {
916 match d.receive_frame() {
917 Ok(Frame::Audio(a)) => {
918 channels = a.layout.channel_count().max(1);
919 samples.extend(
920 a.data[0]
921 .as_ref()
922 .as_chunks::<4>()
923 .0
924 .iter()
925 .map(|s| f32::from_ne_bytes(*s)),
926 );
927 }
928 Ok(_) => {}
929 Err(ec_core::Error::NeedMore | ec_core::Error::Eof) => break,
930 Err(e) => return Err(ts_error(e)),
931 }
932 }
933 let frames = (samples.len() / channels.max(1)) as u64;
934 Ok((frames > 0).then_some(Decoded { samples, channels, frames }))
935 }
936 Self::Ext(d) => Ok(d.decode(data)?.map(|(samples, channels)| {
937 let frames = (samples.len() / channels.max(1)) as u64;
938 Decoded { samples, channels, frames }
939 })),
940 Self::PcmLe { codec, channels } => {
941 let bytes = match codec {
942 CodecId::PcmU8 => 1,
943 CodecId::PcmS16Le => 2,
944 CodecId::PcmS24Le => 3,
945 _ => 4,
946 };
947 let frames = data.len() / (bytes * *channels);
948 let samples = data[..frames * bytes * *channels]
949 .chunks_exact(bytes)
950 .map(|s| match codec {
951 CodecId::PcmU8 => (f32::from(s[0]) - 128.0) / 128.0,
952 CodecId::PcmS16Le => f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0,
953 CodecId::PcmS24Le => (i32::from_le_bytes([0, s[0], s[1], s[2]]) >> 8) as f32 / 8_388_608.0,
954 CodecId::PcmS32Le => i32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f32 / 2_147_483_648.0,
955 _ => f32::from_le_bytes([s[0], s[1], s[2], s[3]]),
956 })
957 .collect();
958 Ok(Some(Decoded { samples, channels: *channels, frames: frames as u64 }))
959 }
960 Self::Pcm { bytes, big_endian, channels } => {
961 let step = *bytes * *channels;
962 let frames = data.len() / step.max(1);
963 let mut samples = Vec::with_capacity(frames * *channels);
964 for s in data[..frames * step].chunks_exact(*bytes) {
965 let v = match (*bytes, *big_endian) {
966 (2, true) => f32::from(i16::from_be_bytes([s[0], s[1]])) / 32768.0,
967 _ => {
968 let raw = i32::from_le_bytes([0, s[0], s[1], s[2]]) >> 8;
969 raw as f32 / 8_388_608.0
970 }
971 };
972 samples.push(v);
973 }
974 Ok(Some(Decoded { samples, channels: *channels, frames: frames as u64 }))
975 }
976 }
977 }
978}
979
980/// One sound track of a transport stream, with a demuxer of its own.
981pub(crate) struct TsAudio {
982 path: PathBuf,
983 d: Src,
984 flavor: Flavor,
985 stream: u32,
986 pub(crate) codec: CodecId,
987 /// The `AudioSpecificConfig` of raw AAC (an AVI's), empty for ADTS.
988 asc: Vec<u8>,
989 /// The stream's codec parameters, for the codecs built from them
990 /// ([`crate::extaudio`]).
991 params: Option<ec_core::CodecParameters>,
992 /// Source time 0 in ticks, and this track's first timestamp.
993 origin: i64,
994 start: i64,
995 /// The earliest timestamp of any stream: a seek this close to it starts over.
996 file_start: i64,
997 /// The packet a seek read to learn where it landed.
998 pending: VecDeque<(i64, Vec<u8>)>,
999 /// What the decoder is built from: source channels, rate, and whether the AC-3
1000 /// decoder folds to a pair.
1001 pub(crate) src_channels: usize,
1002 pub(crate) sample_rate: u32,
1003 pub(crate) stereo_downmix: bool,
1004 pub(crate) total_samples: Option<u64>,
1005}
1006
1007impl TsAudio {
1008 /// Opens audio track `index` (PMT order, refused tracks counted). `Ok(None)` for a
1009 /// track the build cannot decode, `Err` for an index the file does not have.
1010 pub(crate) fn open(path: &Path, index: usize) -> crate::Result<Option<Self>> {
1011 let flavor = Flavor::of(path);
1012 let d = open_demuxer(path, flavor)?;
1013 let file = describe_open(&d);
1014 if file.audio.is_empty() {
1015 return Ok(None);
1016 }
1017 let Some(info) = file.audio.get(index) else {
1018 return Err(format!(
1019 "{}: audio stream {index} of {} stream{}",
1020 path.display(),
1021 file.audio.len(),
1022 if file.audio.len() == 1 { "" } else { "s" }
1023 )
1024 .into());
1025 };
1026 let (Some(stream), Some(codec)) = (info.stream, info.codec_id) else {
1027 return Ok(None);
1028 };
1029 let asc = d
1030 .streams()
1031 .iter()
1032 .find(|s| s.index == stream)
1033 .and_then(|s| s.params.extradata.as_ref())
1034 .filter(|_| codec == CodecId::Aac)
1035 .map(|b| b.as_ref().to_vec())
1036 .unwrap_or_default();
1037 let d_params = d
1038 .streams()
1039 .iter()
1040 .find(|s| s.index == stream)
1041 .map(|s| s.params.clone());
1042 let start = info.start.unwrap_or(file.origin);
1043 let file_start = d
1044 .streams()
1045 .iter()
1046 .filter_map(|s| s.start_time)
1047 .min()
1048 .unwrap_or(start);
1049 let mut track = Self {
1050 path: path.to_path_buf(),
1051 d,
1052 flavor,
1053 stream,
1054 codec,
1055 asc,
1056 params: d_params,
1057 origin: file.origin,
1058 start,
1059 file_start,
1060 pending: VecDeque::new(),
1061 src_channels: usize::from(info.channels).max(1),
1062 sample_rate: info.sample_rate,
1063 stereo_downmix: false,
1064 total_samples: None,
1065 };
1066 track.measure()?;
1067 let end = start + info.duration.unwrap_or(0);
1068 // The track plays from `start - origin` to its end on the clip's clock; a track
1069 // that begins before the picture is trimmed to the picture.
1070 let rel_end = (end - file.origin).max(0);
1071 track.total_samples = Some((rel_end as i128 * i128::from(track.sample_rate) / i128::from(TICKS)) as u64);
1072 Ok(Some(track))
1073 }
1074
1075 /// Decodes the first packets to learn what the headers do not say: the rate and
1076 /// width a decoder really emits (HE-AAC doubles its core rate), and whether an
1077 /// AC-3 track has more than one front channel to fold.
1078 fn measure(&mut self) -> crate::Result<()> {
1079 if self.codec == CodecId::Ac3 || self.codec == CodecId::EAc3 {
1080 if let Some((_, first)) = self.read_audio()? {
1081 let nfchans = match self.codec {
1082 CodecId::EAc3 => ec_ac3::eac3::parse(first.get(2..).unwrap_or_default())
1083 .map(|b| b.nfchans)
1084 .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?,
1085 _ => ec_ac3::bsi::parse(first.get(5..).unwrap_or_default())
1086 .map(|b| b.nfchans)
1087 .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?,
1088 };
1089 self.stereo_downmix = nfchans > 1;
1090 }
1091 self.reopen()?;
1092 }
1093 let mut decoder = self.decoder()?;
1094 for _ in 0..16 {
1095 let Some((_, bytes)) = self.read_audio()? else { break };
1096 if let Some(out) = decoder.decode(&bytes)? {
1097 self.src_channels = out.channels;
1098 // The rate of an AAC stream is what the decoder emits, not what the ADTS
1099 // header of its core says.
1100 if self.codec == CodecId::Aac
1101 && let Ok(aac) = self.aac_decoder().and_then(|mut d| {
1102 d.decode(&bytes, None).map_err(|e| format!("AAC decode failed: {e}").into())
1103 })
1104 && aac.sample_rate > 0
1105 {
1106 self.sample_rate = aac.sample_rate;
1107 }
1108 break;
1109 }
1110 }
1111 self.reopen()?;
1112 if self.sample_rate == 0 {
1113 return Err("MPEG transport stream: the sound track states no sample rate".into());
1114 }
1115 Ok(())
1116 }
1117
1118 /// The width the timeline gets: mono stays mono, anything wider is folded to a pair.
1119 pub(crate) fn channels(&self) -> u16 {
1120 match (self.stereo_downmix, self.src_channels) {
1121 (_, 1) => 1,
1122 _ => 2,
1123 }
1124 }
1125
1126 pub(crate) fn decoder(&self) -> crate::Result<TsDecoder> {
1127 TsDecoder::new(
1128 self.codec,
1129 self.src_channels,
1130 self.sample_rate,
1131 self.stereo_downmix,
1132 &self.asc,
1133 self.params.as_ref(),
1134 )
1135 }
1136
1137 fn aac_decoder(&self) -> crate::Result<ec_aac::AacDecoder> {
1138 match self.asc.is_empty() {
1139 true => Ok(ec_aac::AacDecoder::new()),
1140 false => ec_aac::AacDecoder::with_config_bytes(&self.asc)
1141 .map_err(|e| format!("AAC configuration: {e}").into()),
1142 }
1143 }
1144
1145 fn reopen(&mut self) -> crate::Result<()> {
1146 self.d = open_demuxer(&self.path, self.flavor)?;
1147 self.pending.clear();
1148 Ok(())
1149 }
1150
1151 /// Seconds a decoder is run ahead of the first sample it is asked for.
1152 pub(crate) fn pre_roll_secs(&self) -> f64 {
1153 match self.codec {
1154 CodecId::PcmS16Be | CodecId::PcmS24Le => 0.0,
1155 c if is_pcm_le(c) => 0.0,
1156 CodecId::ImaAdpcmWav | CodecId::MsAdpcm | CodecId::PcmAlaw | CodecId::PcmMulaw => 0.0,
1157 _ => 0.35,
1158 }
1159 }
1160
1161 fn read_audio(&mut self) -> crate::Result<Option<(i64, Vec<u8>)>> {
1162 if let Some(p) = self.pending.pop_front() {
1163 return Ok(Some(p));
1164 }
1165 loop {
1166 match self.d.next_packet() {
1167 Ok(p) if p.stream == self.stream => {
1168 let pts = p.pts.or(p.dts).unwrap_or(self.start);
1169 return Ok(Some((pts, p.data.as_ref().to_vec())));
1170 }
1171 Ok(_) => {}
1172 Err(ec_core::Error::Eof) => return Ok(None),
1173 Err(e) => return Err(ts_error(e)),
1174 }
1175 }
1176 }
1177
1178 /// The next packet of this track: its time in samples on the clip's clock (negative
1179 /// before the picture) and its bytes.
1180 pub(crate) fn next_packet(&mut self) -> crate::Result<Option<(i128, Vec<u8>)>> {
1181 Ok(self.read_audio()?.map(|(pts, bytes)| {
1182 let rel = i128::from(pts - self.origin) * i128::from(self.sample_rate);
1183 // Rounded to the nearest sample.
1184 let samples = (rel * 2 + i128::from(TICKS)).div_euclid(2 * i128::from(TICKS));
1185 (samples, bytes)
1186 }))
1187 }
1188
1189 /// Positions the track so the next packet starts at or before `secs` of the clip
1190 /// (or at the top of the file, if nothing earlier exists).
1191 pub(crate) fn seek(&mut self, secs: f64) -> crate::Result<()> {
1192 let want = self.origin + (secs.max(0.0) * TICKS as f64) as i64;
1193 if want <= self.file_start + TICKS {
1194 return self.reopen();
1195 }
1196 // DVD LPCM at 20 and 24 bits packs two frames to a group that can straddle two packets;
1197 // a read that begins in the middle of a packet cannot tell where a group begins and
1198 // decodes noise from there on. It is read from the top instead (the sound is only
1199 // copied, so this is a walk of the file, not a decode).
1200 if self.flavor == Flavor::Ps && self.codec == CodecId::PcmS24Le {
1201 return self.reopen();
1202 }
1203 let mut slack = TICKS;
1204 loop {
1205 let at = want - slack;
1206 if at <= self.file_start {
1207 return self.reopen();
1208 }
1209 self.pending.clear();
1210 match self.d.seek(self.stream, Timestamp::new(at, tb()), SeekMode::Exact) {
1211 Ok(()) => {}
1212 Err(_) => return self.reopen(),
1213 }
1214 match self.read_audio()? {
1215 Some((pts, bytes)) if pts <= want => {
1216 self.pending.push_front((pts, bytes));
1217 return Ok(());
1218 }
1219 Some((pts, bytes)) => {
1220 // Landed after what was wanted: look further back.
1221 self.pending.push_front((pts, bytes));
1222 slack *= 4;
1223 if slack > 600 * TICKS {
1224 return self.reopen();
1225 }
1226 }
1227 None => return self.reopen(),
1228 }
1229 }
1230 }
1231}
1232
1233// ----------------------------------------------------------------------------------
1234// The subtitles
1235// ----------------------------------------------------------------------------------
1236
1237/// The PGS tracks of a transport stream, one [`MkvSubtitle`] each so the Matroska reader
1238/// of display sets ([`crate::subtitle`]) takes them as they are. `number` is the demuxer's
1239/// stream index, which is what a project saves.
1240pub(crate) fn subtitles(path: &Path) -> crate::Result<Vec<MkvSubtitle>> {
1241 let mut d = open_demuxer(path, Flavor::of(path))?;
1242 let file = describe_open(&d);
1243 let mut tracks: Vec<MkvSubtitle> = file
1244 .subtitles
1245 .iter()
1246 .map(|s| MkvSubtitle {
1247 number: u64::from(s.stream),
1248 codec: s.codec.to_string(),
1249 language: s.language.clone().unwrap_or_else(|| "und".into()),
1250 name: String::new(),
1251 private: Vec::new(),
1252 cues: Vec::new(),
1253 unsupported: None,
1254 unpack: Unpack::None,
1255 })
1256 .collect();
1257 if tracks.is_empty() {
1258 return Ok(tracks);
1259 }
1260 loop {
1261 match d.next_packet() {
1262 Ok(p) => {
1263 if let Some(t) = tracks.iter_mut().find(|t| t.number == u64::from(p.stream)) {
1264 let pts = p.pts.or(p.dts).unwrap_or(file.origin);
1265 t.cues.push(MkvCue {
1266 start_us: (pts - file.origin) * 1_000_000 / TICKS,
1267 duration_us: None,
1268 payload: p.data.as_ref().to_vec(),
1269 });
1270 }
1271 }
1272 Err(ec_core::Error::Eof) => break,
1273 Err(e) => return Err(ts_error(e)),
1274 }
1275 }
1276 Ok(tracks)
1277}
1278
1279// ----------------------------------------------------------------------------------
1280// The probe
1281// ----------------------------------------------------------------------------------
1282
1283/// Every stream of a transport stream as [`StreamFacts`] lists it: the picture, each sound
1284/// track in PMT order (the refused ones too, by their ffprobe name), each PGS track.
1285pub(crate) fn header_streams(path: &Path) -> crate::Result<Vec<StreamFacts>> {
1286 let d = open_demuxer(path, Flavor::of(path))?;
1287 let file = describe_open(&d);
1288 let secs = |ticks: Option<i64>| ticks.filter(|t| *t > 0).map(|t| t as f64 / TICKS as f64);
1289 let mut out = Vec::new();
1290 if let Some(info) = file.video.and_then(|v| d.streams().iter().find(|s| s.index == v)) {
1291 out.push(StreamFacts {
1292 kind: StreamKind::Video,
1293 index: 0,
1294 codec_id: Some(
1295 match info.params.codec {
1296 CodecId::H265 => "hevc",
1297 CodecId::Mpeg2Video => "mpeg2video",
1298 CodecId::Mjpeg => "mjpeg",
1299 CodecId::ProRes => "prores",
1300 CodecId::Dnxhd => "dnxhd",
1301 CodecId::DvVideo => "dvvideo",
1302 CodecId::Mpeg4Part2 => "mpeg4",
1303 CodecId::MsMpeg4V2 => "msmpeg4v2",
1304 CodecId::MsMpeg4V3 => "msmpeg4v3",
1305 CodecId::RawVideo => "rawvideo",
1306 _ => "h264",
1307 }
1308 .to_string(),
1309 ),
1310 language: None,
1311 channels: None,
1312 sample_rate: None,
1313 duration_secs: secs(info.duration),
1314 profile: None,
1315 bit_depth: None,
1316 });
1317 }
1318 if let (None, Some(name)) = (file.video, &file.refused_codec) {
1319 out.push(StreamFacts {
1320 kind: StreamKind::Video,
1321 index: 0,
1322 codec_id: Some(name.clone()).filter(|n| !n.is_empty()),
1323 language: None,
1324 channels: None,
1325 sample_rate: None,
1326 duration_secs: None,
1327 profile: None,
1328 bit_depth: None,
1329 });
1330 }
1331 for (index, a) in file.audio.iter().enumerate() {
1332 out.push(StreamFacts {
1333 kind: StreamKind::Audio,
1334 index,
1335 codec_id: Some(a.codec.clone()),
1336 language: a.language.clone(),
1337 channels: Some(a.channels).filter(|c| *c > 0),
1338 sample_rate: Some(a.sample_rate).filter(|r| *r > 0),
1339 duration_secs: secs(a.duration),
1340 profile: None,
1341 bit_depth: pcm_depth(a.codec_id),
1342 });
1343 }
1344 for (index, s) in file.subtitles.iter().enumerate() {
1345 out.push(StreamFacts {
1346 kind: StreamKind::Subtitle,
1347 index,
1348 codec_id: Some(s.probe_name.to_string()),
1349 language: s.language.clone(),
1350 channels: None,
1351 sample_rate: None,
1352 duration_secs: None,
1353 profile: None,
1354 bit_depth: None,
1355 });
1356 }
1357 Ok(out)
1358}
1359
1360/// Every picture of a transport or program stream through ec-cc's extractor for its codec, for
1361/// the embedded closed captions ([`super::captions`]). Times are microseconds from source time 0
1362/// (the first picture), the clock every other cue of this file is on. `limit_us` stops the walk
1363/// once a picture is past it (the cheap presence probe). Empty for a stream whose picture is
1364/// neither H.264, HEVC nor MPEG-1/2.
1365pub(crate) fn caption_triplets(path: &Path, limit_us: Option<i64>) -> crate::Result<Vec<ec_cc::TimedCc>> {
1366 let mut d = open_demuxer(path, Flavor::of(path))?;
1367 let file = describe_open(&d);
1368 let Some(video) = file.video else {
1369 return Ok(Vec::new());
1370 };
1371 let kind = d.tracks().into_iter().find(|t| t.stream == Some(video)).map(|t| t.kind);
1372 enum Ex {
1373 H264(ec_cc::H264Extractor),
1374 Hevc(ec_cc::HevcExtractor),
1375 Mpeg2(ec_cc::Mpeg2Extractor),
1376 }
1377 let mut ex = match kind {
1378 Some(TsKind::H264) => Ex::H264(ec_cc::H264Extractor::new(ec_cc::extract::NalFormat::AnnexB)),
1379 Some(TsKind::Hevc) => Ex::Hevc(ec_cc::HevcExtractor::new(ec_cc::extract::NalFormat::AnnexB)),
1380 Some(TsKind::Mpeg1Video | TsKind::Mpeg2Video) => Ex::Mpeg2(ec_cc::Mpeg2Extractor::new()),
1381 _ => return Ok(Vec::new()),
1382 };
1383 d.set_video_framing(VideoFraming::AnnexB);
1384 loop {
1385 let p = match d.next_packet() {
1386 Ok(p) => p,
1387 Err(ec_core::Error::Eof) => break,
1388 Err(e) => return Err(ts_error(e)),
1389 };
1390 if p.stream != video {
1391 continue;
1392 }
1393 let us = p.pts.or(p.dts).map(|t| (t - file.origin) * 1_000_000 / TICKS);
1394 if limit_us.is_some_and(|l| us.is_some_and(|u| u > l)) {
1395 break;
1396 }
1397 match &mut ex {
1398 Ex::H264(e) => e.push(p.data.as_ref(), us),
1399 Ex::Hevc(e) => e.push(p.data.as_ref(), us),
1400 Ex::Mpeg2(e) => e.push(p.data.as_ref(), us),
1401 }
1402 }
1403 let rate = (25, 1);
1404 Ok(match ex {
1405 Ex::H264(e) => e.finish(rate),
1406 Ex::Hevc(e) => e.finish(rate),
1407 Ex::Mpeg2(e) => e.finish(rate),
1408 })
1409}