forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.5 MiBcdccbc2Tahinli12 hours ago4263 commits

track.rs974 lines, 33.9 KiBHistoryRawDownload
1//! One elementary stream under the selected program: PES reassembly state and the
2//! per-codec packetisers that turn PES payloads into access units and frames.
3
4use std::collections::VecDeque;
5
6use ec_core::{
7 AudioParameters, ChannelLayout, CodecId, CodecParameters, MediaParameters, PixelFormat,
8 SampleFormat, StreamInfo, TimeBase, registry::VideoParameters,
9};
10
11use crate::codec::{
12 self, FrameHdr, Framing, LpcmHeader, StreamKind, build_avcc, build_hvcc, frame_header,
13 header_lookahead, scan_au,
14};
15use crate::psi::EsEntry;
16use ec_truehd::{AccessUnitHeader, frame_length};
17
18/// 90 kHz, the clock of PTS and DTS.
19pub(crate) const TICKS: i64 = 90_000;
20
21/// Largest access unit or PES this crate buffers.
22pub(crate) const MAX_PES: usize = 32 << 20;
23
24/// Longest audio frame any supported framing allows, with margin.
25const MAX_FRAME: usize = 16 * 1024;
26
27/// Bytes a TrueHD packetiser needs before it can judge a position: an AC-3 sync
28/// header is 8 bytes, a TrueHD access unit's length word is 2.
29const TRUEHD_LOOKAHEAD: usize = 8;
30
31/// A finished packet on its way out of the engine.
32#[derive(Debug)]
33pub(crate) struct Queued {
34 pub track: usize,
35 /// File offset of the transport packet that began the PES.
36 pub off: u64,
37 pub pts: Option<i64>,
38 pub dts: Option<i64>,
39 pub dur: Option<i64>,
40 pub key: bool,
41 pub corrupt: bool,
42 /// The timestamps were derived from neighbouring pictures, not read from a packet.
43 pub derived: bool,
44 pub data: Vec<u8>,
45}
46
47/// A PES payload with the facts its header and transport packets gave.
48pub(crate) struct PesIn<'a> {
49 pub payload: &'a [u8],
50 pub pts: Option<i64>,
51 pub dts: Option<i64>,
52 pub off: u64,
53 pub rai: bool,
54 pub bad: bool,
55}
56
57pub(crate) struct Au {
58 pub data: Vec<u8>,
59 pub pts: Option<i64>,
60 pub dts: Option<i64>,
61 pub off: u64,
62 pub rai: bool,
63 pub bad: bool,
64}
65
66struct Frame {
67 data: Vec<u8>,
68 pts: Option<i64>,
69 dur: i64,
70 off: u64,
71 bad: bool,
72}
73
74/// Facts collected from the stream itself.
75#[derive(Default, Clone)]
76pub(crate) struct Cfg {
77 pub sps: Vec<Vec<u8>>,
78 pub pps: Vec<Vec<u8>>,
79 pub vps: Vec<Vec<u8>>,
80 pub hdr: Option<FrameHdr>,
81 pub lpcm: Option<LpcmHeader>,
82 pub mpeg2: Option<codec::Mpeg2Facts>,
83 pub truehd: Option<TrueHdFacts>,
84}
85
86/// What a TrueHD stream's major syncs say: the sample rate, the channel layout of
87/// the highest PCM presentation, and the samples one access unit holds.
88#[derive(Clone)]
89pub(crate) struct TrueHdFacts {
90 pub rate: u32,
91 pub layout: ChannelLayout,
92 pub samples: u32,
93 pub substreams: usize,
94}
95
96/// How the program-stream front end hands pictures over (see `psvideo`).
97#[derive(Default)]
98pub(crate) struct PsVideo {
99 /// The track belongs to a program stream.
100 pub ps: bool,
101 pub on: bool,
102 pub buf: crate::psvideo::VBuf,
103}
104
105/// One elementary stream.
106pub(crate) struct Track {
107 pub es: EsEntry,
108 pub kind: StreamKind,
109 pub refusal: Option<String>,
110 pub stream: Option<u32>,
111 pub active: bool,
112 pub cfg: Cfg,
113 pub psv: PsVideo,
114 // PES reassembly.
115 pub pes: Vec<u8>,
116 pub pes_on: bool,
117 pub pes_off: u64,
118 pub pes_rai: bool,
119 pub pes_bad: bool,
120 pub pes_expect: Option<usize>,
121 pub last_pts: Option<i64>,
122 // Packetiser state.
123 au: Option<Au>,
124 carry: Vec<u8>,
125 carry_off: u64,
126 /// Timestamp the next audio frame gets.
127 anchor: Option<i64>,
128 pending: Option<Frame>,
129 // Timing facts.
130 pub min_pts: Option<i64>,
131 pub max_end: Option<i64>,
132 pub dts_seen: Vec<i64>,
133 pub start_time: Option<i64>,
134 pub packets: u64,
135 /// DVD subpicture units are split over PES packets.
136 spu: ec_dvdsub::SpuAssembler,
137}
138
139impl Track {
140 pub(crate) fn new(es: EsEntry) -> Track {
141 let kind = StreamKind::classify(&es);
142 let refusal = match &kind {
143 StreamKind::AacLatm => Some(
144 "aac_latm (stream type 0x11): LATM/LOAS framing is not implemented, only ADTS"
145 .to_string(),
146 ),
147 StreamKind::Other(n) => Some(format!(
148 "{n} (stream type 0x{:02x}): no demux path for this stream type",
149 es.stream_type
150 )),
151 _ => None,
152 };
153 Track {
154 es,
155 kind,
156 refusal,
157 stream: None,
158 active: true,
159 cfg: Cfg::default(),
160 psv: PsVideo::default(),
161 pes: Vec::new(),
162 pes_on: false,
163 pes_off: 0,
164 pes_rai: false,
165 pes_bad: false,
166 pes_expect: None,
167 last_pts: None,
168 au: None,
169 carry: Vec::new(),
170 carry_off: 0,
171 anchor: None,
172 pending: None,
173 min_pts: None,
174 max_end: None,
175 dts_seen: Vec::new(),
176 start_time: None,
177 packets: 0,
178 spu: ec_dvdsub::SpuAssembler::default(),
179 }
180 }
181
182 /// True when packets of this track are produced at all.
183 pub(crate) fn wanted(&self) -> bool {
184 self.active && self.refusal.is_none()
185 }
186
187 /// Drops all in-flight data; the configuration found so far stays.
188 pub(crate) fn reset(&mut self, seed: Option<i64>) {
189 self.pes.clear();
190 self.pes_on = false;
191 self.pes_bad = false;
192 self.pes_expect = None;
193 self.au = None;
194 self.carry.clear();
195 self.anchor = None;
196 self.pending = None;
197 self.last_pts = seed;
198 self.psv.buf.clear();
199 self.spu.reset();
200 }
201
202 /// True once the stream's parameters are known well enough to describe it.
203 pub(crate) fn ready(&self) -> bool {
204 if !self.wanted() {
205 return false;
206 }
207 match self.kind {
208 StreamKind::H264 => {
209 !self.cfg.sps.is_empty()
210 && !self.cfg.pps.is_empty()
211 && codec::h264_facts(&self.cfg.sps[0]).is_some()
212 }
213 StreamKind::Hevc => {
214 !self.cfg.sps.is_empty()
215 && !self.cfg.pps.is_empty()
216 && !self.cfg.vps.is_empty()
217 && codec::hevc_facts(&self.cfg.sps[0]).is_some()
218 }
219 StreamKind::AacAdts
220 | StreamKind::Ac3
221 | StreamKind::Eac3
222 | StreamKind::Dts
223 | StreamKind::MpegAudio => self.cfg.hdr.is_some(),
224 StreamKind::Mpeg1Video | StreamKind::Mpeg2Video => self.cfg.mpeg2.is_some(),
225 StreamKind::Lpcm | StreamKind::DvdLpcm => self.cfg.lpcm.is_some(),
226 StreamKind::Pgs | StreamKind::DvdSub | StreamKind::DvbSub => true,
227 StreamKind::TrueHd => self.cfg.truehd.is_some(),
228 _ => false,
229 }
230 }
231
232 /// The value one video frame lasts, estimated from decode timestamps.
233 pub(crate) fn frame_ticks(&self) -> Option<i64> {
234 let mut deltas: Vec<i64> = self
235 .dts_seen
236 .windows(2)
237 .map(|w| w[1] - w[0])
238 .filter(|&d| d > 0)
239 .collect();
240 if deltas.is_empty() {
241 return None;
242 }
243 deltas.sort_unstable();
244 // The most common delta: with B-frames the decode times are even.
245 let mut best = (0usize, deltas[0]);
246 let mut run = 0usize;
247 for i in 0..deltas.len() {
248 run = if i > 0 && deltas[i] == deltas[i - 1] {
249 run + 1
250 } else {
251 1
252 };
253 if run > best.0 {
254 best = (run, deltas[i]);
255 }
256 }
257 Some(best.1)
258 }
259
260 /// The `StreamInfo` for this track, when it is ready. `index` is the stream index.
261 pub(crate) fn stream_info(&self, index: u32) -> Option<StreamInfo> {
262 if !self.ready() {
263 return None;
264 }
265 let tb = TimeBase::new(1, TICKS);
266 let params = match self.kind {
267 StreamKind::H264 => {
268 let f = codec::h264_facts(&self.cfg.sps[0])?;
269 let mut p = CodecParameters::new(CodecId::H264);
270 p.extradata = build_avcc(&self.cfg.sps, &self.cfg.pps).map(Into::into);
271 let fr = self.frame_rate();
272 p.media = MediaParameters::Video(VideoParameters {
273 width: f.width,
274 height: f.height,
275 format: pixel_format(f.chroma, f.depth_luma),
276 frame_rate: fr,
277 ..VideoParameters::default()
278 });
279 p
280 }
281 StreamKind::Hevc => {
282 let f = codec::hevc_facts(&self.cfg.sps[0])?;
283 let mut p = CodecParameters::new(CodecId::H265);
284 p.extradata =
285 build_hvcc(&self.cfg.vps, &self.cfg.sps, &self.cfg.pps).map(Into::into);
286 let fr = self.frame_rate();
287 p.media = MediaParameters::Video(VideoParameters {
288 width: f.width,
289 height: f.height,
290 format: pixel_format(f.chroma, f.depth_luma),
291 frame_rate: fr,
292 ..VideoParameters::default()
293 });
294 p
295 }
296 StreamKind::Mpeg1Video | StreamKind::Mpeg2Video => {
297 let f = self.cfg.mpeg2.as_ref()?;
298 let mut p = CodecParameters::new(CodecId::Mpeg2Video);
299 p.extradata = Some(f.extradata.clone().into());
300 p.media = MediaParameters::Video(VideoParameters {
301 width: f.width,
302 height: f.height,
303 format: pixel_format(if f.has_ext { f.chroma } else { 1 }, 8),
304 frame_rate: TimeBase::try_new(i64::from(f.rate.0), i64::from(f.rate.1)).ok(),
305 sample_aspect_ratio: f
306 .sar
307 .and_then(|(n, d)| TimeBase::try_new(i64::from(n), i64::from(d)).ok()),
308 ..VideoParameters::default()
309 });
310 p
311 }
312 StreamKind::AacAdts => {
313 let h = self.cfg.hdr?;
314 let mut p = CodecParameters::new(CodecId::Aac);
315 p.extradata =
316 Some(codec::audio_specific_config(h.aux + 1, h.sr_idx, h.ch_cfg).into());
317 p.media = MediaParameters::Audio(AudioParameters {
318 sample_rate: h.rate,
319 layout: ChannelLayout::from_count(usize::from(h.channels.max(1))),
320 format: None,
321 bits_per_sample: None,
322 });
323 p
324 }
325 StreamKind::Ac3 | StreamKind::Eac3 => {
326 let h = self.cfg.hdr?;
327 let id = if self.kind == StreamKind::Ac3 {
328 CodecId::Ac3
329 } else {
330 CodecId::EAc3
331 };
332 let mut p = CodecParameters::new(id);
333 p.media = MediaParameters::Audio(AudioParameters {
334 sample_rate: h.rate,
335 layout: ChannelLayout::from_count(usize::from(h.channels.max(1))),
336 format: None,
337 bits_per_sample: None,
338 });
339 p
340 }
341 StreamKind::Dts => {
342 let h = self.cfg.hdr?;
343 let mut p = CodecParameters::new(CodecId::Dts);
344 p.media = MediaParameters::Audio(AudioParameters {
345 sample_rate: h.rate,
346 layout: ChannelLayout::from_count(usize::from(h.channels.max(1))),
347 format: None,
348 bits_per_sample: None,
349 });
350 p
351 }
352 StreamKind::MpegAudio => {
353 let h = self.cfg.hdr?;
354 let id = match h.aux {
355 1 => CodecId::Mp1,
356 2 => CodecId::Mp2,
357 _ => CodecId::Mp3,
358 };
359 let mut p = CodecParameters::new(id);
360 p.media = MediaParameters::Audio(AudioParameters {
361 sample_rate: h.rate,
362 layout: ChannelLayout::from_count(usize::from(h.channels.max(1))),
363 format: None,
364 bits_per_sample: None,
365 });
366 p
367 }
368 StreamKind::Lpcm | StreamKind::DvdLpcm => {
369 let l = self.cfg.lpcm?;
370 let id = if l.bits == 16 {
371 CodecId::PcmS16Be
372 } else {
373 CodecId::PcmS24Le
374 };
375 let mut p = CodecParameters::new(id);
376 p.media = MediaParameters::Audio(AudioParameters {
377 sample_rate: l.rate,
378 layout: ChannelLayout::from_count(usize::from(l.channels)),
379 format: (l.bits == 16).then_some(SampleFormat::S16),
380 bits_per_sample: Some(if l.bits == 16 { 16 } else { 24 }),
381 });
382 p
383 }
384 StreamKind::Pgs => CodecParameters::new(CodecId::Pgs),
385 StreamKind::DvdSub => CodecParameters::new(CodecId::DvdSub),
386 StreamKind::DvbSub => CodecParameters::new(CodecId::DvbSub),
387 StreamKind::TrueHd => {
388 let t = self.cfg.truehd.as_ref()?;
389 let mut p = CodecParameters::new(CodecId::TrueHd);
390 p.media = MediaParameters::Audio(AudioParameters {
391 sample_rate: t.rate,
392 layout: t.layout.clone(),
393 format: None,
394 bits_per_sample: None,
395 });
396 p
397 }
398 _ => return None,
399 };
400 let mut info = StreamInfo::new(index, tb, params);
401 info.start_time = self.start_time.or(self.min_pts);
402 info.language = self.es.language();
403 Some(info)
404 }
405
406 fn frame_rate(&self) -> Option<TimeBase> {
407 let d = self.frame_ticks()?;
408 TimeBase::try_new(TICKS, d).ok()
409 }
410
411 // -----------------------------------------------------------------------
412 // PES in
413 // -----------------------------------------------------------------------
414
415 pub(crate) fn push_pes(&mut self, ti: usize, p: &PesIn<'_>, q: &mut VecDeque<Queued>) {
416 match self.kind {
417 StreamKind::H264
418 | StreamKind::Hevc
419 | StreamKind::Mpeg1Video
420 | StreamKind::Mpeg2Video => self.video_push(ti, p, q),
421 StreamKind::AacAdts => self.audio_push(ti, p, Framing::Adts, q),
422 StreamKind::Ac3 | StreamKind::Eac3 => self.audio_push(ti, p, Framing::Ac3, q),
423 StreamKind::MpegAudio => self.audio_push(ti, p, Framing::Mpa, q),
424 StreamKind::Dts => self.audio_push(ti, p, Framing::Dts, q),
425 StreamKind::TrueHd => self.truehd_push(ti, p, q),
426 StreamKind::Lpcm => self.lpcm_push(ti, p, q),
427 StreamKind::DvdLpcm => self.dvd_lpcm_push(ti, p, q),
428 StreamKind::DvdSub if !p.payload.is_empty() => {
429 for (unit, pts) in self.spu.push(p.payload, p.pts) {
430 self.emit(
431 q,
432 Queued {
433 track: ti,
434 off: p.off,
435 pts,
436 dts: pts,
437 dur: None,
438 key: true,
439 corrupt: p.bad,
440 derived: false,
441 data: unit,
442 },
443 );
444 }
445 }
446 StreamKind::Pgs | StreamKind::DvbSub if !p.payload.is_empty() => {
447 self.emit(
448 q,
449 Queued {
450 track: ti,
451 off: p.off,
452 pts: p.pts,
453 dts: p.dts,
454 dur: None,
455 key: true,
456 corrupt: p.bad,
457 derived: false,
458 data: p.payload.to_vec(),
459 },
460 );
461 }
462 _ => {}
463 }
464 }
465
466 /// Flushes whatever is buffered (end of stream, PMT removal).
467 pub(crate) fn flush(&mut self, ti: usize, q: &mut VecDeque<Queued>) {
468 self.ps_flush(ti, q);
469 self.flush_au(ti, q);
470 if let Some(f) = self.pending.take() {
471 self.emit_frame(ti, f, q);
472 }
473 }
474
475 pub(crate) fn emit(&mut self, q: &mut VecDeque<Queued>, item: Queued) {
476 self.packets += 1;
477 if let Some(pts) = item.pts {
478 self.min_pts = Some(self.min_pts.map_or(pts, |m| m.min(pts)));
479 let end = pts + item.dur.unwrap_or(0);
480 self.max_end = Some(self.max_end.map_or(end, |m| m.max(end)));
481 }
482 if self.kind.is_video()
483 && self.dts_seen.len() < 48
484 && let Some(d) = item.dts.or(item.pts)
485 {
486 self.dts_seen.push(d);
487 }
488 q.push_back(item);
489 }
490
491 // ---- video ------------------------------------------------------------
492
493 fn video_push(&mut self, ti: usize, p: &PesIn<'_>, q: &mut VecDeque<Queued>) {
494 if p.pts.is_some() {
495 self.flush_au(ti, q);
496 }
497 let au = self.au.get_or_insert_with(|| Au {
498 data: Vec::new(),
499 pts: p.pts,
500 dts: p.dts,
501 off: p.off,
502 rai: p.rai,
503 bad: false,
504 });
505 if au.data.len() + p.payload.len() > MAX_PES {
506 au.bad = true;
507 } else {
508 au.data.extend_from_slice(p.payload);
509 }
510 au.bad |= p.bad;
511 }
512
513 fn flush_au(&mut self, ti: usize, q: &mut VecDeque<Queued>) {
514 let Some(au) = self.au.take() else {
515 return;
516 };
517 if au.data.is_empty() {
518 return;
519 }
520 if matches!(self.kind, StreamKind::Mpeg1Video | StreamKind::Mpeg2Video) {
521 self.flush_mpeg2(ti, au, q);
522 return;
523 }
524 self.emit_annexb(ti, au, q);
525 }
526
527 /// Emits an H.264/HEVC access unit (split further on access unit delimiters when
528 /// one PES carries several progressive pictures).
529 pub(crate) fn emit_annexb(&mut self, ti: usize, au: Au, q: &mut VecDeque<Queued>) {
530 let hevc = self.kind == StreamKind::Hevc;
531 let scan = scan_au(&au.data, hevc);
532 for (dst, src) in [
533 (&mut self.cfg.sps, &scan.sps),
534 (&mut self.cfg.pps, &scan.pps),
535 (&mut self.cfg.vps, &scan.vps),
536 ] {
537 for s in src {
538 if dst.len() < 8 && !dst.contains(s) {
539 // A changed set replaces the stale ones of its kind only when the
540 // list is full; keeping the first keeps extradata stable.
541 dst.push(s.clone());
542 }
543 }
544 }
545 let split_ok = scan.aud >= 2
546 && (hevc
547 || self
548 .cfg
549 .sps
550 .first()
551 .and_then(|s| codec::h264_facts(s))
552 .is_some_and(|f| f.frame_mbs_only));
553 if !split_ok {
554 self.emit(
555 q,
556 Queued {
557 track: ti,
558 off: au.off,
559 pts: au.pts,
560 dts: au.dts,
561 dur: None,
562 key: scan.key || au.rai,
563 corrupt: au.bad,
564 derived: false,
565 data: au.data,
566 },
567 );
568 return;
569 }
570 let mut cuts: Vec<usize> = vec![0];
571 for &a in &scan.aud_at {
572 let mut s = a;
573 if s > 0 && au.data[s - 1] == 0 {
574 s -= 1;
575 }
576 if s > *cuts.last().unwrap_or(&0) {
577 cuts.push(s);
578 }
579 }
580 cuts.push(au.data.len());
581 for (i, w) in cuts.windows(2).enumerate() {
582 let piece = &au.data[w[0]..w[1]];
583 let key = if i == 0 {
584 scan_au(piece, hevc).key || au.rai
585 } else {
586 scan_au(piece, hevc).key
587 };
588 self.emit(
589 q,
590 Queued {
591 track: ti,
592 off: au.off,
593 pts: if i == 0 { au.pts } else { None },
594 dts: if i == 0 { au.dts } else { None },
595 dur: None,
596 key,
597 corrupt: au.bad,
598 derived: false,
599 data: piece.to_vec(),
600 },
601 );
602 }
603 }
604
605 /// MPEG-1/2 video: one packet per coded picture, with the sequence, GOP and
606 /// extension headers in front of it. A PES carrying several pictures is cut in
607 /// front of each later picture's header run (the later pieces carry no
608 /// timestamps); a picture spread over several PES with timestamps on the
609 /// continuation is not re-joined.
610 fn flush_mpeg2(&mut self, ti: usize, au: Au, q: &mut VecDeque<Queued>) {
611 let sc = codec::mpeg2_scan(&au.data);
612 if self.cfg.mpeg2.is_none() {
613 self.cfg.mpeg2 = sc.facts.clone();
614 }
615 let mut cuts: Vec<usize> = vec![0];
616 for &s in sc.starts.iter().skip(1) {
617 if s > *cuts.last().unwrap_or(&0) {
618 cuts.push(s);
619 }
620 }
621 cuts.push(au.data.len());
622 for (i, w) in cuts.windows(2).enumerate() {
623 let piece = &au.data[w[0]..w[1]];
624 let key = if cuts.len() == 2 {
625 sc.key
626 } else {
627 codec::mpeg2_scan(piece).key
628 };
629 self.emit(
630 q,
631 Queued {
632 track: ti,
633 off: au.off,
634 pts: if i == 0 { au.pts } else { None },
635 dts: if i == 0 { au.dts } else { None },
636 dur: None,
637 key: key || (i == 0 && au.rai),
638 corrupt: au.bad,
639 derived: false,
640 data: piece.to_vec(),
641 },
642 );
643 }
644 }
645
646 // ---- audio ------------------------------------------------------------
647
648 fn ticks(&self, samples: u64, rate: u32) -> i64 {
649 let r = u64::from(rate.max(1));
650 (samples.saturating_mul(TICKS as u64) / r) as i64
651 }
652
653 fn audio_push(&mut self, ti: usize, p: &PesIn<'_>, framing: Framing, q: &mut VecDeque<Queued>) {
654 if p.bad {
655 self.carry.clear();
656 }
657 let new_start = self.carry.len();
658 let mut data = std::mem::take(&mut self.carry);
659 if data.is_empty() {
660 self.carry_off = p.off;
661 }
662 data.extend_from_slice(p.payload);
663 let carry_off = self.carry_off;
664 let mut cur = 0usize;
665 let mut anchored = false;
666 while cur < data.len() {
667 if data.len() - cur < header_lookahead(framing) {
668 if data[cur] == 0xFF
669 || data[cur] == 0x0B
670 || (framing == Framing::Dts && matches!(data[cur], 0x7F | 0xFE | 0x1F))
671 {
672 break;
673 }
674 cur += 1;
675 continue;
676 }
677 let Some(h) = frame_header(framing, &data[cur..]) else {
678 cur += 1;
679 continue;
680 };
681 if h.len > MAX_FRAME {
682 cur += 1;
683 continue;
684 }
685 if cur + h.len > data.len() {
686 // Program streams: the packet's timestamp belongs to the first frame that
687 // starts in it, complete or not (a read that begins at this packet needs it).
688 if self.psv.ps && cur >= new_start && !anchored && p.pts.is_some() {
689 self.anchor = p.pts;
690 }
691 break;
692 }
693 let next = cur + h.len;
694 if data.len() - next >= header_lookahead(framing)
695 && frame_header(framing, &data[next..]).is_none()
696 {
697 // Not followed by another frame: a false sync inside payload.
698 cur += 1;
699 continue;
700 }
701 if self.cfg.hdr.is_none() {
702 self.cfg.hdr = Some(h);
703 }
704 if cur >= new_start && !anchored && p.pts.is_some() {
705 self.anchor = p.pts;
706 anchored = true;
707 }
708 // The first frame of a PES takes the PES timestamp; the ones after it
709 // follow at one frame duration, rounded down, each (as ffmpeg does).
710 let pts = self.anchor;
711 let dur = self.ticks(u64::from(h.samples), h.rate);
712 self.anchor = pts.map(|a| a.saturating_add(dur));
713 let frame = Frame {
714 data: data[cur..next].to_vec(),
715 pts,
716 dur,
717 off: if cur < new_start { carry_off } else { p.off },
718 bad: p.bad,
719 };
720 if framing == Framing::Ac3 && self.kind == StreamKind::Eac3 {
721 match (&mut self.pending, h.join) {
722 (Some(prev), true) => prev.data.extend_from_slice(&frame.data),
723 _ => {
724 if let Some(prev) = self.pending.replace(frame) {
725 self.emit_frame(ti, prev, q);
726 }
727 }
728 }
729 } else {
730 self.emit_frame(ti, frame, q);
731 }
732 cur = next;
733 }
734 let rest = &data[cur.min(data.len())..];
735 if rest.len() <= MAX_FRAME {
736 self.carry = rest.to_vec();
737 if cur >= new_start {
738 self.carry_off = p.off;
739 }
740 }
741 }
742
743 /// TrueHD (stream type 0x83): one packet per access unit, the length word and
744 /// everything after it, which is what `ec_truehd::TrueHdDecoder` takes. Blu-ray
745 /// interleaves AC-3 core frames (sync 0x0B77) in the same PID. They are dropped:
746 /// the TrueHD access units carry the same audio, so they take no time on the
747 /// timeline. An access unit is accepted only when its substream directory sums
748 /// to its length word; a position that fails both tests is skipped one byte at
749 /// a time, as the other audio packetisers do.
750 fn truehd_push(&mut self, ti: usize, p: &PesIn<'_>, q: &mut VecDeque<Queued>) {
751 if p.bad {
752 self.carry.clear();
753 }
754 let new_start = self.carry.len();
755 let mut data = std::mem::take(&mut self.carry);
756 if data.is_empty() {
757 self.carry_off = p.off;
758 }
759 data.extend_from_slice(p.payload);
760 let carry_off = self.carry_off;
761 let mut cur = 0usize;
762 let mut anchored = false;
763 while cur < data.len() {
764 let rest = &data[cur..];
765 if rest.len() < TRUEHD_LOOKAHEAD {
766 break;
767 }
768 if let Some(h) = codec::ac3_header(rest).map(|(h, _)| h) {
769 if h.len > rest.len() {
770 break;
771 }
772 cur += h.len;
773 continue;
774 }
775 let Some(len) = frame_length(rest).ok().filter(|&l| l <= MAX_FRAME) else {
776 cur += 1;
777 continue;
778 };
779 if len > rest.len() {
780 // The access unit goes on in the next PES.
781 break;
782 }
783 let streams = self.cfg.truehd.as_ref().map_or(0, |t| t.substreams);
784 let Ok(head) = AccessUnitHeader::parse(&rest[..len], streams) else {
785 cur += 1;
786 continue;
787 };
788 if head.substreams.is_empty() {
789 cur += 1;
790 continue;
791 }
792 if let Some(m) = head.major_sync
793 && let Ok(layout) = head.channel_layout()
794 {
795 self.cfg.truehd = Some(TrueHdFacts {
796 rate: m.sample_rate,
797 layout,
798 // A major sync's rate code sizes the access units: 40 << n samples.
799 samples: 40 << (m.rate_code & 7),
800 substreams: head.substreams.len(),
801 });
802 }
803 if cur >= new_start && !anchored && p.pts.is_some() {
804 self.anchor = p.pts;
805 anchored = true;
806 }
807 let (pts, dur) = match self.cfg.truehd.as_ref().map(|t| (t.rate, t.samples)) {
808 Some((rate, samples)) => {
809 let dur = self.ticks(u64::from(samples), rate);
810 let pts = self.anchor;
811 self.anchor = pts.map(|a| a.saturating_add(dur));
812 (pts, dur)
813 }
814 None => (self.anchor, 0),
815 };
816 let frame = Frame {
817 data: rest[..len].to_vec(),
818 pts,
819 dur,
820 off: if cur < new_start { carry_off } else { p.off },
821 bad: p.bad,
822 };
823 self.emit_frame(ti, frame, q);
824 cur += len;
825 }
826 let rest = &data[cur.min(data.len())..];
827 if rest.len() <= MAX_FRAME {
828 self.carry = rest.to_vec();
829 if cur >= new_start {
830 self.carry_off = p.off;
831 }
832 }
833 }
834
835 fn emit_frame(&mut self, ti: usize, f: Frame, q: &mut VecDeque<Queued>) {
836 if f.pts.is_none() && self.anchor.is_none() && self.packets == 0 {
837 // Frames before the first timestamp cannot be placed on the timeline.
838 return;
839 }
840 self.emit(
841 q,
842 Queued {
843 track: ti,
844 off: f.off,
845 pts: f.pts,
846 dts: None,
847 dur: Some(f.dur),
848 key: true,
849 corrupt: f.bad,
850 derived: false,
851 data: f.data,
852 },
853 );
854 }
855
856 // ---- LPCM -------------------------------------------------------------
857
858 fn lpcm_push(&mut self, ti: usize, p: &PesIn<'_>, q: &mut VecDeque<Queued>) {
859 let Some(h) = codec::parse_lpcm_header(p.payload) else {
860 return;
861 };
862 if self.cfg.lpcm.is_none() {
863 self.cfg.lpcm = Some(h);
864 }
865 let body = &p.payload[4..];
866 let body = &body[..h.payload_size.min(body.len())];
867 // Odd channel counts are stored with one zero channel at the end of each frame.
868 let width = usize::from(h.bits.div_ceil(8));
869 let kept = usize::from(h.channels) * width;
870 let stored = (usize::from(h.channels) + usize::from(h.padded)) * width;
871 let mut data = Vec::with_capacity(body.len());
872 for frame in body.chunks_exact(stored) {
873 let frame = &frame[..kept];
874 if h.bits == 16 {
875 data.extend_from_slice(frame);
876 } else {
877 // 20 and 24 bit big-endian samples sit in 3 bytes; the family's PCM id
878 // is little-endian.
879 for s in frame.as_chunks::<3>().0 {
880 data.extend_from_slice(&[s[2], s[1], s[0]]);
881 }
882 }
883 }
884 let samples = (body.len() / stored) as u64;
885 self.emit(
886 q,
887 Queued {
888 track: ti,
889 off: p.off,
890 pts: p.pts,
891 dts: None,
892 dur: Some(self.ticks(samples, h.rate)),
893 key: true,
894 corrupt: p.bad,
895 derived: false,
896 data,
897 },
898 );
899 }
900}
901
902impl Track {
903 /// DVD-Video LPCM: the payload (after the 4-byte substream header) starts with the
904 /// 3-byte audio header; samples are big-endian, 16 bit as is, 20 and 24 bit in
905 /// groups of two frames (high 16 bits of every sample, then the low bytes/nibbles).
906 fn dvd_lpcm_push(&mut self, ti: usize, p: &PesIn<'_>, q: &mut VecDeque<Queued>) {
907 let Some(h) = codec::parse_dvd_lpcm_header(p.payload) else {
908 return;
909 };
910 if self.cfg.lpcm.is_none() {
911 self.cfg.lpcm = Some(h);
912 }
913 let ch = usize::from(h.channels);
914 // A group of samples can straddle two packets: the rest waits in `carry`.
915 let mut body = std::mem::take(&mut self.carry);
916 body.extend_from_slice(&p.payload[3..]);
917 let (group_in, frames_per_group) = match h.bits {
918 16 => (2 * ch, 1usize),
919 20 => (5 * ch, 2),
920 _ => (6 * ch, 2),
921 };
922 let groups = body.len() / group_in;
923 let mut data = Vec::with_capacity(groups * frames_per_group * ch * 3);
924 for g in body.chunks_exact(group_in) {
925 if h.bits == 16 {
926 data.extend_from_slice(g);
927 continue;
928 }
929 let n = 2 * ch;
930 for i in 0..n {
931 let hi = u32::from(u16::from_be_bytes([g[2 * i], g[2 * i + 1]]));
932 let lo = if h.bits == 24 {
933 u32::from(g[4 * ch + i])
934 } else {
935 let b = u32::from(g[4 * ch + i / 2]);
936 (if i % 2 == 0 { b >> 4 } else { b & 15 }) << 4
937 };
938 let v = (hi << 8) | lo;
939 data.extend_from_slice(&[v as u8, (v >> 8) as u8, (v >> 16) as u8]);
940 }
941 }
942 self.carry = body[groups * group_in..].to_vec();
943 if data.is_empty() {
944 return;
945 }
946 let samples = (groups * frames_per_group) as u64;
947 self.emit(
948 q,
949 Queued {
950 track: ti,
951 off: p.off,
952 pts: p.pts,
953 dts: None,
954 dur: Some(self.ticks(samples, h.rate)),
955 key: true,
956 corrupt: p.bad,
957 derived: false,
958 data,
959 },
960 );
961 }
962}
963
964fn pixel_format(chroma: u8, depth: u8) -> Option<PixelFormat> {
965 match (chroma, depth) {
966 (1, 8) => Some(PixelFormat::I420),
967 (1, 10) => Some(PixelFormat::I010),
968 (2, 8) => Some(PixelFormat::I422),
969 (2, 10) => Some(PixelFormat::I210),
970 (3, 8) => Some(PixelFormat::I444),
971 (3, 10) => Some(PixelFormat::I410),
972 _ => None,
973 }
974}