forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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