forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB3d2e08fTahinli6 days ago3929 commits

codec.rs1056 lines, 32.8 KiBHistoryRawDownload
1//! What a stream type means, and everything derivable from the bytes of the
2//! elementary stream itself: NAL scanning, avcC/hvcC records, AudioSpecificConfig,
3//! audio frame headers.
4
5use ec_core::CodecId;
6
7use crate::psi::EsEntry;
8
9/// What an elementary stream carries, as far as this crate can tell.
10#[derive(Debug, Clone, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum StreamKind {
13 /// H.264 / AVC (stream type 0x1B), Annex B.
14 H264,
15 /// H.265 / HEVC (0x24), Annex B.
16 Hevc,
17 /// MPEG-1 video (0x01), exposed as `CodecId::Mpeg2Video`.
18 Mpeg1Video,
19 /// MPEG-2 video (0x02), exposed as `CodecId::Mpeg2Video`.
20 Mpeg2Video,
21 /// AAC in ADTS (0x0F).
22 AacAdts,
23 /// AAC in LATM/LOAS (0x11). Always refused.
24 AacLatm,
25 /// AC-3 (0x81, or private data with the AC-3 registration / DVB descriptor 0x6A).
26 Ac3,
27 /// E-AC-3 (0x87, 0x84, 0xA1, or DVB descriptor 0x7A).
28 Eac3,
29 /// Dolby TrueHD (0x83, the Blu-ray stream type). The AC-3 core that Blu-ray
30 /// interleaves in the same PID is dropped; see `track.rs`.
31 TrueHd,
32 /// DTS core (0x82, DTS-HD 0x85/0x86/0xA2, or private data with a DTS registration / descriptor 0x7B).
33 Dts,
34 /// MPEG-1/2 audio, layer I/II/III (0x03, 0x04). The layer, read from the first
35 /// frame, picks `Mp1`, `Mp2` or `Mp3`.
36 MpegAudio,
37 /// HDMV LPCM (0x80).
38 Lpcm,
39 /// DVD-Video LPCM (private_stream_1 substream 0xA0-0xA7 in a program stream).
40 DvdLpcm,
41 /// HDMV presentation graphics (0x90).
42 Pgs,
43 /// DVD-Video subpictures (private_stream_1 substream 0x20-0x3F in a program stream).
44 DvdSub,
45 /// DVB subtitles (private data with the subtitling descriptor 0x59).
46 DvbSub,
47 /// Anything else, by a descriptive name.
48 Other(String),
49}
50
51impl StreamKind {
52 /// Classifies a PMT entry.
53 pub fn classify(es: &EsEntry) -> StreamKind {
54 match es.stream_type {
55 0x01 => StreamKind::Mpeg1Video,
56 0x02 => StreamKind::Mpeg2Video,
57 0x03 | 0x04 => StreamKind::MpegAudio,
58 0x0F => StreamKind::AacAdts,
59 0x11 => StreamKind::AacLatm,
60 0x1B => StreamKind::H264,
61 0x24 => StreamKind::Hevc,
62 0x06 | 0x05 => {
63 let reg = es.registration();
64 if reg == Some(*b"AC-3") || es.descriptor(0x6A).is_some() {
65 StreamKind::Ac3
66 } else if reg == Some(*b"EAC3") || es.descriptor(0x7A).is_some() {
67 StreamKind::Eac3
68 } else if reg == Some(*b"HEVC") {
69 StreamKind::Hevc
70 } else if reg == Some(*b"DTS1")
71 || reg == Some(*b"DTS2")
72 || reg == Some(*b"DTS3")
73 || es.descriptor(0x7B).is_some()
74 {
75 StreamKind::Dts
76 } else if es.descriptor(0x56).is_some() {
77 StreamKind::Other("dvb_teletext".into())
78 } else if es.descriptor(0x59).is_some() {
79 StreamKind::DvbSub
80 } else if reg == Some(*b"Opus") {
81 StreamKind::Other("opus".into())
82 } else {
83 StreamKind::Other("private_data".into())
84 }
85 }
86 0x80 => StreamKind::Lpcm,
87 0x81 => StreamKind::Ac3,
88 0x82 => StreamKind::Dts,
89 0x83 => StreamKind::TrueHd,
90 0x84 | 0x87 | 0xA1 => StreamKind::Eac3,
91 0x85 | 0x86 | 0xA2 => StreamKind::Dts,
92 0x90 => StreamKind::Pgs,
93 0x91 => StreamKind::Other("hdmv_igs".into()),
94 0x92 => StreamKind::Other("hdmv_textst".into()),
95 0xEA => StreamKind::Other("vc1".into()),
96 0x10 => StreamKind::Other("mpeg4_visual".into()),
97 0x1C => StreamKind::Other("aac_raw".into()),
98 0x42 => StreamKind::Other("avs".into()),
99 t => StreamKind::Other(format!("stream_type_0x{t:02x}")),
100 }
101 }
102
103 /// Short lowercase name, usable in a refusal message.
104 pub fn name(&self) -> String {
105 match self {
106 StreamKind::H264 => "h264".into(),
107 StreamKind::Hevc => "hevc".into(),
108 StreamKind::Mpeg1Video => "mpeg1video".into(),
109 StreamKind::Mpeg2Video => "mpeg2video".into(),
110 StreamKind::AacAdts => "aac".into(),
111 StreamKind::AacLatm => "aac_latm".into(),
112 StreamKind::Ac3 => "ac3".into(),
113 StreamKind::Eac3 => "eac3".into(),
114 StreamKind::TrueHd => "truehd".into(),
115 StreamKind::Dts => "dts".into(),
116 StreamKind::MpegAudio => "mpeg_audio".into(),
117 StreamKind::Lpcm => "pcm_bluray".into(),
118 StreamKind::DvdLpcm => "pcm_dvd".into(),
119 StreamKind::Pgs => "hdmv_pgs_subtitle".into(),
120 StreamKind::DvdSub => "dvd_subtitle".into(),
121 StreamKind::DvbSub => "dvb_subtitle".into(),
122 StreamKind::Other(n) => n.clone(),
123 }
124 }
125
126 /// The family codec this maps to without looking at the stream. MPEG audio and
127 /// LPCM depend on their first frame and answer `None` here.
128 pub fn codec_id(&self) -> Option<CodecId> {
129 match self {
130 StreamKind::H264 => Some(CodecId::H264),
131 StreamKind::Hevc => Some(CodecId::H265),
132 StreamKind::Mpeg1Video | StreamKind::Mpeg2Video => Some(CodecId::Mpeg2Video),
133 StreamKind::AacAdts => Some(CodecId::Aac),
134 StreamKind::Ac3 => Some(CodecId::Ac3),
135 StreamKind::Eac3 => Some(CodecId::EAc3),
136 StreamKind::TrueHd => Some(CodecId::TrueHd),
137 StreamKind::Dts => Some(CodecId::Dts),
138 StreamKind::Pgs => Some(CodecId::Pgs),
139 StreamKind::DvdSub => Some(CodecId::DvdSub),
140 StreamKind::DvbSub => Some(CodecId::DvbSub),
141 _ => None,
142 }
143 }
144
145 /// True for the sparse bitmap subtitle streams (PGS, DVD, DVB): few packets, no timing
146 /// facts to wait for.
147 pub fn is_bitmap_sub(&self) -> bool {
148 matches!(self, StreamKind::Pgs | StreamKind::DvdSub | StreamKind::DvbSub)
149 }
150
151 /// True for the two codecs delivered as Annex-B access units.
152 pub fn is_annexb_video(&self) -> bool {
153 matches!(self, StreamKind::H264 | StreamKind::Hevc)
154 }
155
156 /// True for MPEG-1 and MPEG-2 video.
157 pub fn is_mpeg_video(&self) -> bool {
158 matches!(self, StreamKind::Mpeg1Video | StreamKind::Mpeg2Video)
159 }
160
161 /// True for a picture stream of any codec.
162 pub fn is_video(&self) -> bool {
163 matches!(
164 self,
165 StreamKind::H264 | StreamKind::Hevc | StreamKind::Mpeg1Video | StreamKind::Mpeg2Video
166 )
167 }
168}
169
170// ---------------------------------------------------------------------------
171// Annex B
172// ---------------------------------------------------------------------------
173
174/// Iterator over the NAL units of an Annex-B buffer: each item is the NAL with its
175/// header byte(s), without start code or trailing zero bytes.
176pub struct NalIter<'a> {
177 data: &'a [u8],
178 pos: usize,
179}
180
181/// NAL units of an Annex-B byte stream.
182pub fn nal_units(data: &[u8]) -> NalIter<'_> {
183 NalIter {
184 data,
185 pos: find_start(data, 0).map_or(data.len(), |p| p + 3),
186 }
187}
188
189/// Offset of the next `00 00 01` at or after `from`.
190fn find_start(data: &[u8], from: usize) -> Option<usize> {
191 let mut i = from;
192 while i + 3 <= data.len() {
193 match data[i + 2] {
194 1 if data[i] == 0 && data[i + 1] == 0 => return Some(i),
195 0 | 1 => i += 1,
196 _ => i += 3,
197 }
198 }
199 None
200}
201
202impl<'a> Iterator for NalIter<'a> {
203 type Item = &'a [u8];
204
205 fn next(&mut self) -> Option<&'a [u8]> {
206 if self.pos >= self.data.len() {
207 return None;
208 }
209 let start = self.pos;
210 let (end, next) = match find_start(self.data, start) {
211 Some(p) => (p, p + 3),
212 None => (self.data.len(), self.data.len()),
213 };
214 self.pos = next;
215 let mut e = end;
216 while e > start && self.data[e - 1] == 0 {
217 e -= 1;
218 }
219 if e == start {
220 return self.next();
221 }
222 Some(&self.data[start..e])
223 }
224}
225
226/// H.264 `nal_unit_type`.
227pub(crate) fn h264_type(nal: &[u8]) -> u8 {
228 nal.first().map_or(0, |b| b & 0x1f)
229}
230
231/// HEVC `nal_unit_type`.
232pub(crate) fn hevc_type(nal: &[u8]) -> u8 {
233 nal.first().map_or(0, |b| (b >> 1) & 0x3f)
234}
235
236/// Facts an access-unit scan collects.
237#[derive(Debug, Default, Clone, PartialEq, Eq)]
238pub(crate) struct AuScan {
239 /// IDR (H.264) or IRAP (HEVC) slice present, or an H.264 recovery-point SEI.
240 pub key: bool,
241 /// Number of access unit delimiters.
242 pub aud: u32,
243 /// Offsets (into the scanned buffer) of each AUD NAL's start code.
244 pub aud_at: Vec<usize>,
245 pub sps: Vec<Vec<u8>>,
246 pub pps: Vec<Vec<u8>>,
247 pub vps: Vec<Vec<u8>>,
248}
249
250const MAX_SETS: usize = 8;
251const MAX_SET_LEN: usize = 1024;
252
253fn add_set(list: &mut Vec<Vec<u8>>, nal: &[u8]) {
254 if nal.len() <= MAX_SET_LEN && list.len() < MAX_SETS && !list.iter().any(|s| s == nal) {
255 list.push(nal.to_vec());
256 }
257}
258
259/// Scans an Annex-B access unit.
260pub(crate) fn scan_au(data: &[u8], hevc: bool) -> AuScan {
261 let mut s = AuScan::default();
262 for nal in nal_units(data) {
263 let off = nal.as_ptr() as usize - data.as_ptr() as usize;
264 if hevc {
265 match hevc_type(nal) {
266 16..=23 => s.key = true,
267 35 => {
268 s.aud += 1;
269 s.aud_at.push(off.saturating_sub(3));
270 }
271 32 => add_set(&mut s.vps, nal),
272 33 => add_set(&mut s.sps, nal),
273 34 => add_set(&mut s.pps, nal),
274 _ => {}
275 }
276 } else {
277 match h264_type(nal) {
278 5 => s.key = true,
279 6 => {
280 if sei_has_recovery_point(nal) {
281 s.key = true;
282 }
283 }
284 9 => {
285 s.aud += 1;
286 s.aud_at.push(off.saturating_sub(3));
287 }
288 7 => add_set(&mut s.sps, nal),
289 8 => add_set(&mut s.pps, nal),
290 _ => {}
291 }
292 }
293 }
294 s
295}
296
297/// True when an H.264 SEI NAL carries a recovery point message (payload type 6).
298fn sei_has_recovery_point(nal: &[u8]) -> bool {
299 let mut i = 1;
300 while i < nal.len() {
301 let mut ty = 0usize;
302 while nal.get(i) == Some(&0xFF) {
303 ty += 255;
304 i += 1;
305 }
306 let Some(&b) = nal.get(i) else {
307 return false;
308 };
309 ty += usize::from(b);
310 i += 1;
311 let mut size = 0usize;
312 while nal.get(i) == Some(&0xFF) {
313 size += 255;
314 i += 1;
315 }
316 let Some(&b) = nal.get(i) else {
317 return false;
318 };
319 size += usize::from(b);
320 i += 1;
321 if ty == 6 {
322 return true;
323 }
324 i = i.saturating_add(size);
325 if nal.get(i).is_none_or(|&b| b == 0x80) {
326 return false;
327 }
328 }
329 false
330}
331
332/// Converts an Annex-B buffer to NAL units each preceded by a big-endian length of
333/// `length_size` bytes (1, 2 or 4).
334pub fn annexb_to_length_prefixed(data: &[u8], length_size: usize) -> Vec<u8> {
335 let n = length_size.clamp(1, 4);
336 let mut out = Vec::with_capacity(data.len() + 16);
337 for nal in nal_units(data) {
338 let len = nal.len() as u64;
339 if n < 4 && len >= 1u64 << (8 * n) {
340 continue;
341 }
342 out.extend_from_slice(&(len as u32).to_be_bytes()[4 - n..]);
343 out.extend_from_slice(nal);
344 }
345 out
346}
347
348/// Removes emulation-prevention bytes.
349fn unescape(nal: &[u8]) -> Vec<u8> {
350 let mut out = Vec::with_capacity(nal.len());
351 let mut zeros = 0;
352 for &b in nal {
353 if zeros >= 2 && b == 3 {
354 zeros = 0;
355 continue;
356 }
357 zeros = if b == 0 { zeros + 1 } else { 0 };
358 out.push(b);
359 }
360 out
361}
362
363/// Parsed H.264 facts.
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub(crate) struct H264Facts {
366 pub width: u32,
367 pub height: u32,
368 pub chroma: u8,
369 pub depth_luma: u8,
370 pub depth_chroma: u8,
371 pub frame_mbs_only: bool,
372 pub profile: u8,
373}
374
375pub(crate) fn h264_facts(sps_nal: &[u8]) -> Option<H264Facts> {
376 let rbsp = unescape(sps_nal.get(1..)?);
377 let s = ec_h264_syntax::Sps::parse(&rbsp).ok()?;
378 Some(H264Facts {
379 width: s.width,
380 height: s.height,
381 chroma: s.chroma_format_idc,
382 depth_luma: s.bit_depth_luma,
383 depth_chroma: s.bit_depth_chroma,
384 frame_mbs_only: s.frame_mbs_only,
385 profile: s.profile_idc,
386 })
387}
388
389/// An `AVCDecoderConfigurationRecord` (ISO 14496-15) from in-band SPS and PPS NAL
390/// units (no start codes, header byte included). `None` without both.
391pub fn build_avcc(sps: &[Vec<u8>], pps: &[Vec<u8>]) -> Option<Vec<u8>> {
392 let first = sps.first()?;
393 if first.len() < 4 || pps.is_empty() {
394 return None;
395 }
396 let mut out = vec![1, first[1], first[2], first[3], 0xFF];
397 out.push(0xE0 | sps.len().min(31) as u8);
398 for s in sps.iter().take(31) {
399 out.extend_from_slice(&(s.len() as u16).to_be_bytes());
400 out.extend_from_slice(s);
401 }
402 out.push(pps.len().min(255) as u8);
403 for p in pps.iter().take(255) {
404 out.extend_from_slice(&(p.len() as u16).to_be_bytes());
405 out.extend_from_slice(p);
406 }
407 if matches!(first[1], 100 | 110 | 122 | 144) {
408 let f = h264_facts(first)?;
409 out.push(0xFC | f.chroma);
410 out.push(0xF8 | (f.depth_luma - 8));
411 out.push(0xF8 | (f.depth_chroma - 8));
412 out.push(0);
413 }
414 Some(out)
415}
416
417/// Parsed HEVC facts.
418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub(crate) struct HevcFacts {
420 pub width: u32,
421 pub height: u32,
422 pub chroma: u8,
423 pub depth_luma: u8,
424 pub depth_chroma: u8,
425 pub interlaced_source: bool,
426}
427
428fn hevc_sps(sps_nal: &[u8]) -> Option<ec_h265_syntax::ps::Sps> {
429 let rbsp = unescape(sps_nal.get(2..)?);
430 ec_h265_syntax::ps::Sps::parse(&rbsp).ok()
431}
432
433pub(crate) fn hevc_facts(sps_nal: &[u8]) -> Option<HevcFacts> {
434 let s = hevc_sps(sps_nal)?;
435 let (width, height) = s.display_size();
436 Some(HevcFacts {
437 width,
438 height,
439 chroma: s.chroma_format_idc as u8,
440 depth_luma: (s.bit_depth_luma_minus8 + 8) as u8,
441 depth_chroma: (s.bit_depth_chroma_minus8 + 8) as u8,
442 interlaced_source: s.ptl.interlaced_source,
443 })
444}
445
446/// An `HEVCDecoderConfigurationRecord` from in-band VPS, SPS and PPS NAL units.
447/// `None` without an SPS that parses.
448pub fn build_hvcc(vps: &[Vec<u8>], sps: &[Vec<u8>], pps: &[Vec<u8>]) -> Option<Vec<u8>> {
449 let first = sps.first()?;
450 let s = hevc_sps(first)?;
451 let p = &s.ptl;
452 let mut out = vec![1];
453 out.push((p.profile_space << 6) | (u8::from(p.tier_flag) << 5) | (p.profile_idc & 0x1f));
454 out.extend_from_slice(&p.profile_compatibility.to_be_bytes());
455 let flags = (u64::from(p.progressive_source) << 47)
456 | (u64::from(p.interlaced_source) << 46)
457 | (u64::from(p.non_packed_constraint) << 45)
458 | (u64::from(p.frame_only_constraint) << 44)
459 | (p.constraint_bits & ((1 << 44) - 1));
460 out.extend_from_slice(&flags.to_be_bytes()[2..]);
461 out.push(p.level_idc);
462 out.extend_from_slice(&[0xF0, 0x00]); // min_spatial_segmentation_idc
463 out.push(0xFC); // parallelismType
464 out.push(0xFC | (s.chroma_format_idc as u8 & 3));
465 out.push(0xF8 | (s.bit_depth_luma_minus8 as u8 & 7));
466 out.push(0xF8 | (s.bit_depth_chroma_minus8 as u8 & 7));
467 out.extend_from_slice(&[0, 0]); // avgFrameRate
468 out.push((1 << 3) | (1 << 2) | 3); // 1 temporal layer, nested, 4-byte lengths
469 let arrays: Vec<(u8, &[Vec<u8>])> = [(32u8, vps), (33, sps), (34, pps)]
470 .into_iter()
471 .filter(|(_, l)| !l.is_empty())
472 .collect();
473 out.push(arrays.len() as u8);
474 for (ty, list) in arrays {
475 out.push(0x80 | ty);
476 out.extend_from_slice(&(list.len().min(MAX_SETS) as u16).to_be_bytes());
477 for n in list.iter().take(MAX_SETS) {
478 out.extend_from_slice(&(n.len() as u16).to_be_bytes());
479 out.extend_from_slice(n);
480 }
481 }
482 Some(out)
483}
484
485// ---------------------------------------------------------------------------
486// Audio frame headers
487// ---------------------------------------------------------------------------
488
489/// What a frame header states.
490#[derive(Debug, Clone, Copy, PartialEq, Eq)]
491pub(crate) struct FrameHdr {
492 /// Whole frame in bytes, header included.
493 pub len: usize,
494 /// PCM samples per channel the frame decodes to.
495 pub samples: u32,
496 pub rate: u32,
497 /// Channel count including LFE.
498 pub channels: u8,
499 /// Dependent E-AC-3 substream: belongs to the previous frame.
500 pub join: bool,
501 /// ADTS object type minus one / MPEG audio layer (1..3), for building configs.
502 pub aux: u8,
503 /// ADTS sampling frequency index / MPEG audio unused.
504 pub sr_idx: u8,
505 /// ADTS channel configuration.
506 pub ch_cfg: u8,
507}
508
509pub(crate) const AAC_RATES: [u32; 13] = [
510 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
511];
512
513/// ADTS header at the start of `b`.
514pub(crate) fn adts_header(b: &[u8]) -> Option<FrameHdr> {
515 let h = b.get(..7)?;
516 if h[0] != 0xFF || h[1] & 0xF6 != 0xF0 {
517 return None;
518 }
519 let sr_idx = (h[2] >> 2) & 15;
520 let rate = *AAC_RATES.get(usize::from(sr_idx))?;
521 let ch_cfg = ((h[2] & 1) << 2) | (h[3] >> 6);
522 let len = (usize::from(h[3] & 3) << 11) | (usize::from(h[4]) << 3) | usize::from(h[5] >> 5);
523 let hdr = if h[1] & 1 == 0 { 9 } else { 7 };
524 if len < hdr {
525 return None;
526 }
527 let blocks = u32::from(h[6] & 3) + 1;
528 let channels = match ch_cfg {
529 0 => 0,
530 7 => 8,
531 n => n,
532 };
533 Some(FrameHdr {
534 len,
535 samples: 1024 * blocks,
536 rate,
537 channels,
538 join: false,
539 aux: h[2] >> 6,
540 sr_idx,
541 ch_cfg,
542 })
543}
544
545/// A two-byte AudioSpecificConfig for AAC with object type `aot` (1 = Main, 2 = LC,
546/// 3 = SSR, 4 = LTP), sampling-frequency index and channel configuration.
547pub fn audio_specific_config(aot: u8, sr_idx: u8, ch_cfg: u8) -> Vec<u8> {
548 let v =
549 (u16::from(aot & 31) << 11) | (u16::from(sr_idx & 15) << 7) | (u16::from(ch_cfg & 15) << 3);
550 v.to_be_bytes().to_vec()
551}
552
553const AC3_SIZES: [[u16; 38]; 3] = [
554 [
555 64, 64, 80, 80, 96, 96, 112, 112, 128, 128, 160, 160, 192, 192, 224, 224, 256, 256, 320,
556 320, 384, 384, 448, 448, 512, 512, 640, 640, 768, 768, 896, 896, 1024, 1024, 1152, 1152,
557 1280, 1280,
558 ],
559 [
560 69, 70, 87, 88, 104, 105, 121, 122, 139, 140, 174, 175, 208, 209, 243, 244, 278, 279, 348,
561 349, 417, 418, 487, 488, 557, 558, 696, 697, 835, 836, 975, 976, 1114, 1115, 1253, 1254,
562 1393, 1394,
563 ],
564 [
565 96, 96, 120, 120, 144, 144, 168, 168, 192, 192, 240, 240, 288, 288, 336, 336, 384, 384,
566 480, 480, 576, 576, 672, 672, 768, 768, 960, 960, 1152, 1152, 1344, 1344, 1536, 1536, 1728,
567 1728, 1920, 1920,
568 ],
569];
570
571fn ac3_channels(acmod: u8, lfe: bool) -> u8 {
572 let base = [2, 1, 2, 3, 3, 4, 4, 5][usize::from(acmod & 7)];
573 base + u8::from(lfe)
574}
575
576/// AC-3 or E-AC-3 syncframe header at the start of `b`. Returns the header and
577/// whether it is E-AC-3.
578pub(crate) fn ac3_header(b: &[u8]) -> Option<(FrameHdr, bool)> {
579 let h = b.get(..8)?;
580 if h[0] != 0x0B || h[1] != 0x77 {
581 return None;
582 }
583 let bsid = h[5] >> 3;
584 if bsid <= 10 {
585 let fscod = h[4] >> 6;
586 let frmsizecod = usize::from(h[4] & 0x3f);
587 if fscod == 3 || frmsizecod >= 38 {
588 return None;
589 }
590 let words = AC3_SIZES[usize::from(fscod)][frmsizecod];
591 let rate = [48000, 44100, 32000][usize::from(fscod)];
592 let acmod = h[6] >> 5;
593 let mut bit = 3;
594 if acmod & 1 != 0 && acmod != 1 {
595 bit += 2;
596 }
597 if acmod & 4 != 0 {
598 bit += 2;
599 }
600 if acmod == 2 {
601 bit += 2;
602 }
603 let lfe = (u16::from_be_bytes([h[6], h[7]]) >> (15 - bit)) & 1 != 0;
604 Some((
605 FrameHdr {
606 len: usize::from(words) * 2,
607 samples: 1536,
608 rate,
609 channels: ac3_channels(acmod, lfe),
610 join: false,
611 aux: 0,
612 sr_idx: 0,
613 ch_cfg: 0,
614 },
615 false,
616 ))
617 } else if (11..=16).contains(&bsid) {
618 let strmtyp = h[2] >> 6;
619 let substream = (h[2] >> 3) & 7;
620 let frmsiz = (usize::from(h[2] & 7) << 8) | usize::from(h[3]);
621 let fscod = h[4] >> 6;
622 let (rate, blocks) = if fscod == 3 {
623 let fscod2 = (h[4] >> 4) & 3;
624 if fscod2 == 3 {
625 return None;
626 }
627 ([24000, 22050, 16000][usize::from(fscod2)], 6)
628 } else {
629 (
630 [48000, 44100, 32000][usize::from(fscod)],
631 [1u32, 2, 3, 6][usize::from((h[4] >> 4) & 3)],
632 )
633 };
634 let acmod = (h[4] >> 1) & 7;
635 let lfe = h[4] & 1 != 0;
636 if strmtyp == 3 {
637 return None;
638 }
639 Some((
640 FrameHdr {
641 len: (frmsiz + 1) * 2,
642 samples: blocks * 256,
643 rate,
644 channels: ac3_channels(acmod, lfe),
645 join: strmtyp == 1 || substream != 0,
646 aux: 0,
647 sr_idx: 0,
648 ch_cfg: 0,
649 },
650 true,
651 ))
652 } else {
653 None
654 }
655}
656
657const MPA_BITRATES: [[[u16; 15]; 3]; 2] = [
658 // MPEG-1: layer I, II, III
659 [
660 [
661 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,
662 ],
663 [
664 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,
665 ],
666 [
667 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
668 ],
669 ],
670 // MPEG-2 / 2.5
671 [
672 [
673 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,
674 ],
675 [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
676 [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
677 ],
678];
679
680/// MPEG audio frame header at the start of `b`; `aux` is the layer (1..=3).
681pub(crate) fn mpa_header(b: &[u8]) -> Option<FrameHdr> {
682 let h = b.get(..4)?;
683 if h[0] != 0xFF || h[1] & 0xE0 != 0xE0 {
684 return None;
685 }
686 let version = (h[1] >> 3) & 3; // 3 = MPEG-1, 2 = MPEG-2, 0 = 2.5
687 let layer = match (h[1] >> 1) & 3 {
688 3 => 1u8,
689 2 => 2,
690 1 => 3,
691 _ => return None,
692 };
693 if version == 1 {
694 return None;
695 }
696 let br_idx = usize::from(h[2] >> 4);
697 let sr_idx = usize::from((h[2] >> 2) & 3);
698 if br_idx == 0 || br_idx == 15 || sr_idx == 3 {
699 return None;
700 }
701 let mpeg1 = version == 3;
702 let rate = [44100u32, 48000, 32000][sr_idx]
703 >> (if mpeg1 {
704 0
705 } else if version == 2 {
706 1
707 } else {
708 2
709 });
710 let kbps = u32::from(MPA_BITRATES[usize::from(!mpeg1)][usize::from(layer - 1)][br_idx]);
711 let pad = u32::from((h[2] >> 1) & 1);
712 let (len, samples) = match layer {
713 1 => ((12 * kbps * 1000 / rate + pad) * 4, 384),
714 2 => (144 * kbps * 1000 / rate + pad, 1152),
715 _ if mpeg1 => (144 * kbps * 1000 / rate + pad, 1152),
716 _ => (72 * kbps * 1000 / rate + pad, 576),
717 };
718 Some(FrameHdr {
719 len: len as usize,
720 samples,
721 rate,
722 channels: if (h[3] >> 6) == 3 { 1 } else { 2 },
723 join: false,
724 aux: layer,
725 sr_idx: 0,
726 ch_cfg: 0,
727 })
728}
729
730/// Which framing an audio stream uses.
731#[derive(Debug, Clone, Copy, PartialEq, Eq)]
732pub(crate) enum Framing {
733 Adts,
734 Ac3,
735 Mpa,
736 Dts,
737}
738
739/// Header of the frame starting at `b[0]`, whichever the framing.
740pub(crate) fn frame_header(f: Framing, b: &[u8]) -> Option<FrameHdr> {
741 match f {
742 Framing::Adts => adts_header(b),
743 Framing::Ac3 => ac3_header(b).map(|(h, _)| h),
744 Framing::Mpa => mpa_header(b),
745 Framing::Dts => crate::dts::access_unit(b).map(|(c, len)| FrameHdr {
746 len,
747 samples: c.samples,
748 rate: c.rate,
749 channels: c.channels,
750 join: false,
751 aux: 0,
752 sr_idx: 0,
753 ch_cfg: 0,
754 }),
755 }
756}
757
758/// HDMV LPCM header.
759#[derive(Debug, Clone, Copy, PartialEq, Eq)]
760pub struct LpcmHeader {
761 /// `audio_data_payload_size`.
762 pub payload_size: usize,
763 /// Channels of the layout (without the padding channel of odd layouts).
764 pub channels: u8,
765 /// Sample rate in Hz.
766 pub rate: u32,
767 /// 16, 20 or 24.
768 pub bits: u8,
769 /// True when the layout has an odd number of channels; BD LPCM then stores one
770 /// extra zero channel at the end of every frame, which the demuxer drops.
771 pub padded: bool,
772}
773
774/// Parses the 4-byte header of an HDMV LPCM PES payload.
775pub fn parse_lpcm_header(b: &[u8]) -> Option<LpcmHeader> {
776 let h = b.get(..4)?;
777 let payload_size = usize::from(u16::from_be_bytes([h[0], h[1]]));
778 let assignment = h[2] >> 4;
779 let channels = match assignment {
780 1 => 1,
781 3 => 2,
782 4 | 5 => 3,
783 6 | 7 => 4,
784 8 => 5,
785 9 => 6,
786 10 => 7,
787 11 => 8,
788 _ => return None,
789 };
790 let rate = match h[2] & 15 {
791 1 => 48000,
792 4 => 96000,
793 5 => 192000,
794 _ => return None,
795 };
796 let bits = match h[3] >> 6 {
797 1 => 16,
798 2 => 20,
799 3 => 24,
800 _ => return None,
801 };
802 Some(LpcmHeader {
803 payload_size,
804 channels,
805 rate,
806 bits,
807 padded: channels % 2 == 1,
808 })
809}
810
811/// Parses the 3-byte audio header that follows the substream header of DVD-Video LPCM.
812pub(crate) fn parse_dvd_lpcm_header(b: &[u8]) -> Option<LpcmHeader> {
813 let h = b.get(..3)?;
814 let bits = match h[1] >> 6 {
815 0 => 16,
816 1 => 20,
817 2 => 24,
818 _ => return None,
819 };
820 let rate = match (h[1] >> 4) & 3 {
821 0 => 48000,
822 1 => 96000,
823 _ => return None,
824 };
825 Some(LpcmHeader {
826 payload_size: 0,
827 channels: (h[1] & 7) + 1,
828 rate,
829 bits,
830 padded: false,
831 })
832}
833
834#[cfg(test)]
835mod tests {
836 use super::*;
837
838 #[test]
839 fn nal_iteration() {
840 let d = [0, 0, 0, 1, 9, 0xF0, 0, 0, 1, 0x65, 1, 2, 0, 0, 0, 1, 6, 5];
841 let n: Vec<&[u8]> = nal_units(&d).collect();
842 assert_eq!(n, vec![&[9u8, 0xF0][..], &[0x65, 1, 2][..], &[6, 5][..]]);
843 assert!(scan_au(&d, false).key);
844 let lp = annexb_to_length_prefixed(&d, 4);
845 assert_eq!(&lp[..6], &[0, 0, 0, 2, 9, 0xF0]);
846 }
847
848 #[test]
849 fn adts_and_asc() {
850 // AAC-LC, 48 kHz, stereo, frame length 100.
851 let mut h = [0xFF, 0xF1, 0x4C, 0x80, 0, 0, 0xFC];
852 let len = 100usize;
853 h[3] |= (len >> 11) as u8 & 3;
854 h[4] = (len >> 3) as u8;
855 h[5] = ((len & 7) << 5) as u8 | 0x1F;
856 let hdr = adts_header(&h).unwrap();
857 assert_eq!(
858 (hdr.len, hdr.rate, hdr.channels, hdr.samples),
859 (100, 48000, 2, 1024)
860 );
861 assert_eq!(
862 audio_specific_config(hdr.aux + 1, hdr.sr_idx, hdr.ch_cfg),
863 vec![0x11, 0x90]
864 );
865 }
866
867 #[test]
868 fn lpcm_header() {
869 let h = parse_lpcm_header(&[0x07, 0x80, 0x31, 0x40]).unwrap();
870 assert_eq!(
871 (h.channels, h.rate, h.bits, h.payload_size),
872 (2, 48000, 16, 0x780)
873 );
874 }
875}
876
877// ---------------------------------------------------------------------------
878// MPEG-1/2 video (ISO 11172-2 / 13818-2)
879// ---------------------------------------------------------------------------
880
881/// What a sequence header (+ sequence_extension) says.
882#[derive(Debug, Clone, PartialEq, Eq)]
883pub struct Mpeg2Facts {
884 pub width: u32,
885 pub height: u32,
886 /// Frame rate as `(num, den)`.
887 pub rate: (u32, u32),
888 /// Sample aspect ratio when derivable and not square.
889 pub sar: Option<(u32, u32)>,
890 /// `chroma_format` of the sequence_extension (1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4).
891 pub chroma: u8,
892 /// True when a sequence_extension follows the header (MPEG-2 proper).
893 pub has_ext: bool,
894 /// Sequence header (and extension) bytes, start codes included.
895 pub extradata: Vec<u8>,
896}
897
898/// What one scan over an MPEG-1/2 video access unit found.
899#[derive(Debug, Default)]
900pub struct Mpeg2Scan {
901 /// Offsets of every `00 00 01 00` picture start code.
902 pub pictures: Vec<usize>,
903 /// Offsets of the start of each picture's header run (preceding sequence, GOP,
904 /// extension and user-data headers included); parallel to `pictures`.
905 pub starts: Vec<usize>,
906 /// A sequence header or an I picture is present.
907 pub key: bool,
908 pub facts: Option<Mpeg2Facts>,
909}
910
911/// Start codes of the headers that may precede a picture and belong to it.
912fn mpeg2_lead(code: u8) -> bool {
913 matches!(code, 0xB2 | 0xB3 | 0xB5 | 0xB8)
914}
915
916/// Scans an access unit for pictures, the keyframe property and the sequence header.
917pub fn mpeg2_scan(data: &[u8]) -> Mpeg2Scan {
918 let mut sc = Mpeg2Scan::default();
919 // (offset, code) of every start code.
920 let mut codes: Vec<(usize, u8)> = Vec::new();
921 let mut i = 0usize;
922 while i + 4 <= data.len() {
923 if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
924 codes.push((i, data[i + 3]));
925 i += 3;
926 } else {
927 i += 1;
928 }
929 }
930 for (k, &(off, code)) in codes.iter().enumerate() {
931 match code {
932 0x00 => {
933 if data.get(off + 5).is_some_and(|b| (b >> 3) & 7 == 1) {
934 sc.key = true;
935 }
936 let mut j = k;
937 while j > 0 && mpeg2_lead(codes[j - 1].1) {
938 j -= 1;
939 }
940 sc.pictures.push(off);
941 sc.starts.push(codes[j].0);
942 }
943 0xB3 => {
944 sc.key = true;
945 if sc.facts.is_none() {
946 sc.facts = parse_mpeg2_seq(&data[off..], &codes[k + 1..], off);
947 }
948 }
949 _ => {}
950 }
951 }
952 sc
953}
954
955/// Parses the sequence header at `d[0..]` and the extension if it directly follows.
956fn parse_mpeg2_seq(d: &[u8], later: &[(usize, u8)], base: usize) -> Option<Mpeg2Facts> {
957 if d.len() < 12 {
958 return None;
959 }
960 let h = &d[4..];
961 let mut width = (u32::from(h[0]) << 4) | u32::from(h[1] >> 4);
962 let mut height = (u32::from(h[1] & 15) << 8) | u32::from(h[2]);
963 let aspect = h[3] >> 4;
964 let rate_code = usize::from(h[3] & 15);
965 // 12 bytes up to and including the load_intra flag byte (h[7] bit 1).
966 let mut len = 12usize;
967 if h[7] & 2 != 0 {
968 len += 64;
969 }
970 let nonintra_byte = len - 1;
971 if d.len() <= nonintra_byte {
972 return None;
973 }
974 if d[nonintra_byte] & 1 != 0 {
975 len += 64;
976 }
977 if d.len() < len || width == 0 || height == 0 {
978 return None;
979 }
980 const RATES: [(u32, u32); 9] = [
981 (0, 0),
982 (24000, 1001),
983 (24, 1),
984 (25, 1),
985 (30000, 1001),
986 (30, 1),
987 (50, 1),
988 (60000, 1001),
989 (60, 1),
990 ];
991 let (mut n, mut dn) = *RATES.get(rate_code)?;
992 if n == 0 {
993 return None;
994 }
995 let mut extradata = d[..len].to_vec();
996 let mut chroma = 1u8;
997 let mut has_ext = false;
998 if let Some(&(eoff, 0xB5)) = later.first()
999 && eoff - base == len
1000 && d.len() >= len + 10
1001 && d[len + 4] >> 4 == 1
1002 {
1003 let e = &d[len + 4..len + 10];
1004 has_ext = true;
1005 chroma = (e[1] >> 1) & 3;
1006 width |= u32::from(((e[1] & 1) << 1) | (e[2] >> 7)) << 12;
1007 height |= u32::from((e[2] >> 5) & 3) << 12;
1008 n *= u32::from((e[4] >> 5) & 3) + 1;
1009 dn *= u32::from(e[5] & 31) + 1;
1010 extradata.extend_from_slice(&d[len..len + 10]);
1011 }
1012 let g = gcd(n, dn);
1013 let (w, hh) = (u64::from(width), u64::from(height));
1014 // MPEG-1 codes are sample aspect ratios (only square is exact enough to use);
1015 // MPEG-2 codes are display aspect ratios, converted with the coded size.
1016 let sar = if has_ext {
1017 let dar = match aspect {
1018 2 => Some((4u64, 3u64)),
1019 3 => Some((16, 9)),
1020 4 => Some((221, 100)),
1021 _ => None,
1022 };
1023 dar.and_then(|(dn_, dd)| {
1024 let (a, b) = (dn_ * hh, dd * w);
1025 let g = gcd64(a, b);
1026 (a != b).then_some(((a / g) as u32, (b / g) as u32))
1027 })
1028 } else {
1029 None
1030 };
1031 Some(Mpeg2Facts {
1032 width,
1033 height,
1034 rate: (n / g, dn / g),
1035 sar,
1036 chroma,
1037 has_ext,
1038 extradata,
1039 })
1040}
1041
1042fn gcd(a: u32, b: u32) -> u32 {
1043 gcd64(u64::from(a), u64::from(b)) as u32
1044}
1045
1046fn gcd64(mut a: u64, mut b: u64) -> u64 {
1047 while b != 0 {
1048 (a, b) = (b, a % b);
1049 }
1050 a.max(1)
1051}
1052
1053/// Bytes a frame header needs before [`frame_header`] can judge it.
1054pub(crate) fn header_lookahead(f: Framing) -> usize {
1055 if f == Framing::Dts { 16 } else { 8 }
1056}