forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe12d32fTahinli6 days ago3982 commits

header.rs318 lines, 11.3 KiBHistoryRawDownload
1//! DTS core sync words, stream word order conversion and the core frame
2//! header (ETSI TS 102 114 section 5.3.1).
3//!
4//! [`parse_frame_header`] is the stable entry point for raw `.dts` sniffing:
5//! it accepts any of the four stream layouts (16-bit big or little endian,
6//! 14-bit big or little endian) and states the frame size, sample rate,
7//! channel count and samples per frame without decoding any audio.
8
9use crate::bits::Bits;
10use ec_core::{Error, Result};
11
12/// Core sync word as it reads in canonical (16-bit, big-endian) order.
13pub const SYNC_CORE: u32 = 0x7FFE_8001;
14/// Core sync word in 16-bit little-endian word order.
15pub const SYNC_CORE_LE: u32 = 0xFE7F_0180;
16/// Core sync word in 14-bit-in-16, big-endian word order.
17pub const SYNC_CORE_14_BE: u32 = 0x1FFF_E800;
18/// Core sync word in 14-bit-in-16, little-endian word order.
19pub const SYNC_CORE_14_LE: u32 = 0xFF1F_00E8;
20/// DTS-HD extension substream sync word.
21pub const SYNC_EXSS: u32 = 0x6458_2025;
22
23/// How the stream stores the canonical bit string.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum StreamFormat {
26 /// 16-bit words, big endian (the canonical order).
27 Be16,
28 /// 16-bit words, little endian.
29 Le16,
30 /// 14 significant bits per 16-bit word, big endian.
31 Be14,
32 /// 14 significant bits per 16-bit word, little endian.
33 Le14,
34}
35
36impl StreamFormat {
37 /// Classify the four-byte sync word at the start of `data`.
38 pub fn from_sync(data: &[u8]) -> Option<StreamFormat> {
39 let w = u32::from_be_bytes(data.get(..4)?.try_into().ok()?);
40 match w {
41 SYNC_CORE => Some(StreamFormat::Be16),
42 SYNC_CORE_LE => Some(StreamFormat::Le16),
43 SYNC_CORE_14_BE => Some(StreamFormat::Be14),
44 SYNC_CORE_14_LE => Some(StreamFormat::Le14),
45 _ => None,
46 }
47 }
48}
49
50/// Convert stream words to the canonical big-endian packed bit string.
51///
52/// `data` starts at a core sync word. The output is appended to `out`.
53pub fn to_canonical(format: StreamFormat, data: &[u8], out: &mut Vec<u8>) {
54 match format {
55 StreamFormat::Be16 => out.extend_from_slice(data),
56 StreamFormat::Le16 => {
57 for c in data.chunks(2) {
58 if c.len() == 2 {
59 out.push(c[1]);
60 out.push(c[0]);
61 } else {
62 out.push(c[0]);
63 }
64 }
65 }
66 StreamFormat::Be14 | StreamFormat::Le14 => {
67 let mut acc: u32 = 0;
68 let mut nbits: u32 = 0;
69 for c in data.chunks(2) {
70 let w = if c.len() == 2 {
71 if format == StreamFormat::Be14 {
72 u16::from_be_bytes([c[0], c[1]])
73 } else {
74 u16::from_le_bytes([c[0], c[1]])
75 }
76 } else {
77 (c[0] as u16) << 8
78 };
79 acc = (acc << 14) | (w & 0x3FFF) as u32;
80 nbits += 14;
81 while nbits >= 8 {
82 out.push((acc >> (nbits - 8)) as u8);
83 nbits -= 8;
84 }
85 acc &= (1 << nbits) - 1;
86 }
87 if nbits > 0 {
88 out.push((acc << (8 - nbits)) as u8);
89 }
90 }
91 }
92}
93
94/// Sample rate by `SFREQ` (Table 5-5); 0 marks a code the core does not use.
95pub const SAMPLE_RATES: [u32; 16] = [
96 0, 8000, 16000, 32000, 0, 0, 11025, 22050, 44100, 0, 0, 12000, 24000, 48000, 0, 0,
97];
98
99/// Transmission bit rate by `RATE` (Table 5-7). The last three codes are
100/// open (1), variable (2) and lossless (3) and carry no nominal rate.
101pub const BIT_RATES: [u32; 32] = [
102 32000, 56000, 64000, 96000, 112000, 128000, 192000, 224000, 256000, 320000, 384000, 448000,
103 512000, 576000, 640000, 768000, 896000, 1024000, 1152000, 1280000, 1344000, 1408000, 1411200,
104 1472000, 1536000, 1920000, 2048000, 3072000, 3840000, 1, 2, 3,
105];
106
107/// Primary channels by `AMODE` (Table 5-4).
108pub const CHANNELS: [u8; 16] = [1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8];
109
110/// Source PCM resolution by `PCMR` (Table 5-10); 0 marks a reserved code.
111pub const PCM_RESOLUTION: [u8; 8] = [16, 16, 20, 20, 0, 24, 24, 0];
112
113/// Everything the core frame header states.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct FrameHeader {
116 /// How the stream stores the bit string.
117 pub format: StreamFormat,
118 /// Normal frame flag (false for a termination frame).
119 pub normal_frame: bool,
120 /// Header and side-information CRCs are present.
121 pub crc_present: bool,
122 /// PCM sample blocks of 32 samples in the frame.
123 pub npcmblocks: u32,
124 /// Frame size in bytes of the canonical (packed) bit string.
125 pub frame_size: usize,
126 /// Frame size in bytes as stored in the stream, which is larger for the
127 /// 14-bit formats.
128 pub stream_frame_size: usize,
129 /// Audio channel arrangement code (`AMODE`).
130 pub amode: u8,
131 /// Core sample rate in Hz.
132 pub sample_rate: u32,
133 /// Transmission bit rate code (`RATE`).
134 pub bit_rate_code: u8,
135 /// Nominal bit rate in bit/s, `None` for open, variable and lossless.
136 pub bit_rate: Option<u32>,
137 /// Embedded dynamic range coefficients present.
138 pub drc_present: bool,
139 /// Embedded time stamp present.
140 pub ts_present: bool,
141 /// Auxiliary data present.
142 pub aux_present: bool,
143 /// Extension audio descriptor (`EXT_AUDIO_ID`): 0 XCH, 2 X96, 6 XXCH.
144 pub ext_audio_type: u8,
145 /// An extension is present in the core frame.
146 pub ext_audio_present: bool,
147 /// Audio sync word inserted after every subsubframe.
148 pub sync_ssf: bool,
149 /// LFE flag: 0 none, 1 with 128x decimation, 2 with 64x decimation.
150 pub lfe: u8,
151 /// ADPCM predictor history carries over from the previous frame.
152 pub predictor_history: bool,
153 /// Perfect-reconstruction QMF bank.
154 pub filter_perfect: bool,
155 /// Encoder software revision.
156 pub encoder_rev: u8,
157 /// Source PCM resolution in bits (16, 20 or 24).
158 pub source_pcm_res: u8,
159 /// Source was ES mastered (`PCMR` bit 0).
160 pub es_format: bool,
161 /// Front channels are sum/difference coded.
162 pub sumdiff_front: bool,
163 /// Surround channels are sum/difference coded.
164 pub sumdiff_surround: bool,
165 /// Dialogue normalisation parameter (`DIALNORM`), surfaced, never applied.
166 pub dialnorm_code: u8,
167 /// Total channels the core carries: primary channels plus the LFE.
168 pub channels: u8,
169 /// PCM samples per channel in the frame (`npcmblocks * 32`).
170 pub samples_per_frame: u32,
171}
172
173impl FrameHeader {
174 /// True when the arrangement code is one the decoder handles (0..=9).
175 pub fn amode_supported(&self) -> bool {
176 self.amode <= 9
177 }
178}
179
180/// Parse the core frame header at the start of `data`.
181///
182/// `data` starts at a core sync word in any of the four stream layouts. A
183/// short buffer is [`Error::NeedMore`]; anything that is not a valid core
184/// frame header is [`Error::Corrupt`], which makes this usable as an "is this
185/// DTS?" probe. Only the header is read, so a frame does not have to be
186/// complete: the frame size is a statement about the frame to come.
187pub fn parse_frame_header(data: &[u8]) -> Result<FrameHeader> {
188 if data.len() < 4 {
189 return Err(Error::NeedMore);
190 }
191 let Some(format) = StreamFormat::from_sync(data) else {
192 return Err(Error::corrupt("DTS: no core sync word"));
193 };
194 let need = match format {
195 StreamFormat::Be16 | StreamFormat::Le16 => 18,
196 _ => 21,
197 };
198 if data.len() < need {
199 return Err(Error::NeedMore);
200 }
201 let mut canon = Vec::with_capacity(24);
202 to_canonical(format, &data[..need], &mut canon);
203 parse_canonical(format, &canon)
204}
205
206pub(crate) fn parse_canonical(format: StreamFormat, canon: &[u8]) -> Result<FrameHeader> {
207 let mut r = Bits::new(canon);
208 if r.get(32) != SYNC_CORE {
209 return Err(Error::corrupt("DTS: no core sync word"));
210 }
211 let normal_frame = r.get1() != 0;
212 let deficit = r.get(5) + 1;
213 if deficit != 32 {
214 return Err(Error::unsupported(
215 "DTS deficit samples",
216 "only frames of whole 32-sample blocks are decoded",
217 ));
218 }
219 let crc_present = r.get1() != 0;
220 let npcmblocks = r.get(7) + 1;
221 if npcmblocks & 7 != 0 {
222 return Err(Error::corrupt("DTS: PCM block count not a multiple of 8"));
223 }
224 let frame_size = r.get(14) as usize + 1;
225 if frame_size < 96 {
226 return Err(Error::corrupt("DTS: core frame size below 96 bytes"));
227 }
228 let amode = r.get(6) as u8;
229 if amode > 9 {
230 return Err(Error::unsupported(
231 format!("DTS audio channel arrangement {amode}"),
232 "only the ten core arrangements (AMODE 0-9) are decoded",
233 ));
234 }
235 let sfreq = r.get(4) as usize;
236 let sample_rate = SAMPLE_RATES[sfreq];
237 if sample_rate == 0 {
238 return Err(Error::corrupt("DTS: invalid core sampling frequency"));
239 }
240 let bit_rate_code = r.get(5) as u8;
241 if r.get1() != 0 {
242 return Err(Error::corrupt("DTS: reserved header bit set"));
243 }
244 let drc_present = r.get1() != 0;
245 let ts_present = r.get1() != 0;
246 let aux_present = r.get1() != 0;
247 let _hdcd = r.get1();
248 let ext_audio_type = r.get(3) as u8;
249 let ext_audio_present = r.get1() != 0;
250 let sync_ssf = r.get1() != 0;
251 let lfe = r.get(2) as u8;
252 if lfe == 3 {
253 return Err(Error::corrupt("DTS: invalid LFE flag"));
254 }
255 let predictor_history = r.get1() != 0;
256 if crc_present {
257 r.skip(16);
258 }
259 let filter_perfect = r.get1() != 0;
260 let encoder_rev = r.get(4) as u8;
261 let _copy_hist = r.get(2);
262 let pcmr = r.get(3) as usize;
263 let source_pcm_res = PCM_RESOLUTION[pcmr];
264 if source_pcm_res == 0 {
265 return Err(Error::corrupt("DTS: invalid source PCM resolution"));
266 }
267 let sumdiff_front = r.get1() != 0;
268 let sumdiff_surround = r.get1() != 0;
269 let dialnorm_code = r.get(4) as u8;
270 if r.over {
271 return Err(Error::NeedMore);
272 }
273 let rate = BIT_RATES[bit_rate_code as usize];
274 let stream_frame_size = match format {
275 StreamFormat::Be16 | StreamFormat::Le16 => frame_size,
276 StreamFormat::Be14 | StreamFormat::Le14 => (frame_size * 8).div_ceil(14) * 2,
277 };
278 Ok(FrameHeader {
279 format,
280 normal_frame,
281 crc_present,
282 npcmblocks,
283 frame_size,
284 stream_frame_size,
285 amode,
286 sample_rate,
287 bit_rate_code,
288 bit_rate: if rate > 3 { Some(rate) } else { None },
289 drc_present,
290 ts_present,
291 aux_present,
292 ext_audio_type,
293 ext_audio_present,
294 sync_ssf,
295 lfe,
296 predictor_history,
297 filter_perfect,
298 encoder_rev,
299 source_pcm_res,
300 es_format: pcmr & 1 != 0,
301 sumdiff_front,
302 sumdiff_surround,
303 dialnorm_code,
304 channels: CHANNELS[amode as usize] + u8::from(lfe != 0),
305 samples_per_frame: npcmblocks * 32,
306 })
307}
308
309/// Length in bytes of the core frame starting at `data[0]`, as stored in the
310/// stream (so 14-bit streams answer with the larger stored size).
311pub fn frame_size(data: &[u8]) -> Result<usize> {
312 Ok(parse_frame_header(data)?.stream_frame_size)
313}
314
315/// Find the first core sync word in `data` and its stream layout.
316pub fn find_sync(data: &[u8]) -> Option<(usize, StreamFormat)> {
317 (0..data.len().saturating_sub(3)).find_map(|i| StreamFormat::from_sync(&data[i..]).map(|f| (i, f)))
318}