forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB3d2e08fTahinli7 days ago3929 commits

decoder.rs277 lines, 9.7 KiBHistoryRawDownload
1//! The public decoder: DTS core frames (any stream word order, with or
2//! without DTS-HD substreams behind them) in, interleaved `f32` frames out.
3
4use ec_core::{
5 AudioFrame, AudioParameters, Buf, ChannelLayout, ChannelPosition, CodecId, CodecParameters,
6 Decoder, Error, Frame, MediaParameters, Packet, Result, SampleFormat, Timestamp,
7};
8
9use crate::core::{Core, Extensions, SPK_C, SPK_CS, SPK_L, SPK_LFE, SPK_LS, SPK_R, SPK_RS};
10use crate::exss::{parse_exss, ExssInfo, EXSS_LBR, EXSS_X96, EXSS_XBR, EXSS_XXCH};
11use crate::header::{
12 find_sync, parse_canonical, to_canonical, FrameHeader, StreamFormat, SYNC_EXSS,
13};
14
15/// Decoder knobs.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub struct Options {
18 /// Refuse a frame whose DTS-HD substream carries XLL (lossless) data
19 /// instead of decoding its backward compatible core. Off by default: the
20 /// core is always the output, and [`FrameInfo::xll`] says that a lossless
21 /// layer was present and not decoded.
22 pub refuse_xll: bool,
23}
24
25/// What a decoded frame said about itself.
26#[derive(Debug, Clone, PartialEq)]
27pub struct FrameInfo {
28 /// The core frame header.
29 pub header: FrameHeader,
30 /// Core extensions that were decoded.
31 pub extensions: Extensions,
32 /// A DTS-HD extension substream followed the core.
33 pub hd_substream: bool,
34 /// The substream carried XLL (lossless) data. It is not decoded: the
35 /// output is the core, a lossy rendering of the same signal.
36 pub xll: bool,
37 /// The substream carried components this decoder does not decode (XBR,
38 /// XXCH, LBR or an X96 that the core did not signal).
39 pub hd_extensions_ignored: bool,
40 /// Samples per channel in the output frame.
41 pub samples: usize,
42 /// Output sample rate (twice the core rate when X96 was decoded).
43 pub sample_rate: u32,
44}
45
46/// A DTS decoder.
47pub struct DtsDecoder {
48 core: Core,
49 params: CodecParameters,
50 options: Options,
51 pending: Option<Frame>,
52 info: Option<FrameInfo>,
53 flushed: bool,
54}
55
56
57impl Default for DtsDecoder {
58 fn default() -> Self {
59 Self::new()
60 }
61}
62
63impl DtsDecoder {
64 /// A decoder with default [`Options`].
65 pub fn new() -> DtsDecoder {
66 DtsDecoder::with_options(Options::default())
67 }
68
69 /// A decoder with explicit options.
70 pub fn with_options(options: Options) -> DtsDecoder {
71 DtsDecoder {
72 core: Core::new(),
73 params: CodecParameters::new(CodecId::Dts),
74 options,
75 pending: None,
76 info: None,
77 flushed: false,
78 }
79 }
80
81 /// The options in force; changes take effect on the next packet.
82 pub fn options_mut(&mut self) -> &mut Options {
83 &mut self.options
84 }
85
86 /// What the last decoded frame's header said.
87 pub fn frame_info(&self) -> Option<&FrameInfo> {
88 self.info.as_ref()
89 }
90
91 /// Decode one packet holding a core frame, possibly followed by a DTS-HD
92 /// extension substream, into one audio frame.
93 ///
94 /// `data` may start with padding: the first core sync word in any of the
95 /// four stream layouts is the frame start. A packet that begins with a
96 /// bare extension substream and no core is [`Error::Unsupported`].
97 pub fn decode_frame(&mut self, data: &[u8]) -> Result<AudioFrame> {
98 let Some((start, format)) = find_sync(data) else {
99 if data.len() >= 4 && u32::from_be_bytes([data[0], data[1], data[2], data[3]]) == SYNC_EXSS
100 {
101 let exss = parse_exss(data)?;
102 if exss.has_xll() && self.options.refuse_xll {
103 return Err(xll_error());
104 }
105 return Err(Error::unsupported(
106 "DTS-HD substream without a backward compatible core",
107 "only the core component is decoded and none precedes this substream",
108 ));
109 }
110 return Err(if data.len() < 4 {
111 Error::NeedMore
112 } else {
113 Error::corrupt("DTS: no core sync word in the packet")
114 });
115 };
116 let data = &data[start..];
117 let hdr0 = crate::header::parse_frame_header(data)?;
118 let take = hdr0.stream_frame_size.min(data.len());
119 let mut canon = Vec::with_capacity(hdr0.frame_size + 4);
120 to_canonical(format, &data[..take], &mut canon);
121 let hdr = parse_canonical(format, &canon)?;
122 if canon.len() < hdr.frame_size && matches!(format, StreamFormat::Be16 | StreamFormat::Le16) {
123 return Err(Error::NeedMore);
124 }
125
126 // DTS-HD substream behind the core (4-byte aligned).
127 let mut exss: Option<ExssInfo> = None;
128 let mut exss_bytes: Option<Vec<u8>> = None;
129 if matches!(format, StreamFormat::Be16 | StreamFormat::Le16) {
130 let after = hdr.frame_size.next_multiple_of(4);
131 if data.len() >= after + 4 {
132 let tail = &data[after..];
133 // The substream is stored in the stream's own byte order only
134 // for BE data; an LE stream's substream is swapped as well.
135 let sw;
136 let tail = if format == StreamFormat::Le16 {
137 let mut v = Vec::new();
138 to_canonical(StreamFormat::Le16, tail, &mut v);
139 sw = v;
140 &sw[..]
141 } else {
142 tail
143 };
144 if tail.len() >= 4
145 && u32::from_be_bytes([tail[0], tail[1], tail[2], tail[3]]) == SYNC_EXSS
146 {
147 exss = parse_exss(tail).ok();
148 if exss.is_some() {
149 exss_bytes = Some(tail.to_vec());
150 }
151 }
152 }
153 }
154 let xll = exss.as_ref().is_some_and(|e| e.has_xll());
155 if xll && self.options.refuse_xll {
156 return Err(xll_error());
157 }
158 let mut ignored = false;
159 if let Some(e) = &exss {
160 for a in &e.assets {
161 if a.extension_mask & (EXSS_XBR | EXSS_XXCH | EXSS_LBR) != 0 {
162 ignored = true;
163 }
164 }
165 }
166
167 let x96: Option<&[u8]> = exss_bytes.as_deref().zip(exss.as_ref()).and_then(|(b, e)| {
168 let a = e.assets.first()?;
169 if a.extension_mask & EXSS_X96 != 0 {
170 b.get(a.x96_offset..a.x96_offset + a.x96_size)
171 } else {
172 None
173 }
174 });
175 let dec = self.core.decode(&canon, &hdr, x96)?;
176 // Interleave in the family's order.
177 const ORDER: [(usize, ChannelPosition); 7] = [
178 (SPK_L, ChannelPosition::FrontLeft),
179 (SPK_R, ChannelPosition::FrontRight),
180 (SPK_C, ChannelPosition::FrontCenter),
181 (SPK_LFE, ChannelPosition::Lfe),
182 (SPK_LS, ChannelPosition::BackLeft),
183 (SPK_RS, ChannelPosition::BackRight),
184 (SPK_CS, ChannelPosition::BackCenter),
185 ];
186 let mut chans: Vec<usize> = Vec::new();
187 let mut positions: Vec<ChannelPosition> = Vec::new();
188 for (spk, pos) in ORDER {
189 if dec.ch_mask & (1 << spk) != 0 {
190 chans.push(spk);
191 positions.push(pos);
192 }
193 }
194 let layout = layout_of(&positions);
195 let n = dec.nsamples;
196 let nch = chans.len();
197 let mut bytes = Vec::with_capacity(n * nch * 4);
198 const SCALE: f32 = 1.0 / 8_388_608.0;
199 for i in 0..n {
200 for &c in &chans {
201 bytes.extend_from_slice(&(dec.out[c][i] as f32 * SCALE).to_le_bytes());
202 }
203 }
204 self.params.media = MediaParameters::Audio(AudioParameters {
205 sample_rate: dec.sample_rate,
206 layout: layout.clone(),
207 format: Some(SampleFormat::F32),
208 bits_per_sample: None,
209 });
210 self.info = Some(FrameInfo {
211 header: hdr,
212 extensions: dec.ext,
213 hd_substream: exss.is_some(),
214 xll,
215 hd_extensions_ignored: ignored,
216 samples: n,
217 sample_rate: dec.sample_rate,
218 });
219 AudioFrame::try_new(
220 SampleFormat::F32,
221 false,
222 layout,
223 dec.sample_rate,
224 n,
225 vec![Buf::from_vec(bytes)],
226 )
227 }
228}
229
230fn xll_error() -> Error {
231 Error::unsupported(
232 "DTS-HD XLL (lossless) extension",
233 "only the backward compatible core is decoded; clear Options::refuse_xll to output it",
234 )
235}
236
237fn layout_of(positions: &[ChannelPosition]) -> ChannelLayout {
238 match positions {
239 [ChannelPosition::FrontCenter] => ChannelLayout::Mono,
240 [ChannelPosition::FrontLeft, ChannelPosition::FrontRight] => ChannelLayout::Stereo,
241 _ if positions == ChannelLayout::Surround5_1.positions() => ChannelLayout::Surround5_1,
242 _ if positions == ChannelLayout::Surround7_1.positions() => ChannelLayout::Surround7_1,
243 _ => ChannelLayout::Custom(positions.to_vec()),
244 }
245}
246
247impl Decoder for DtsDecoder {
248 fn codec_parameters(&self) -> &CodecParameters {
249 &self.params
250 }
251
252 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
253 let mut frame = self.decode_frame(&packet.data)?;
254 frame.pts = packet.pts.map(|ts| Timestamp::new(ts, packet.time_base));
255 self.pending = Some(Frame::Audio(frame));
256 Ok(())
257 }
258
259 fn receive_frame(&mut self) -> Result<Frame> {
260 match self.pending.take() {
261 Some(frame) => Ok(frame),
262 None if self.flushed => Err(Error::Eof),
263 None => Err(Error::NeedMore),
264 }
265 }
266
267 fn flush(&mut self) -> Result<()> {
268 self.flushed = true;
269 Ok(())
270 }
271
272 fn reset(&mut self) {
273 self.core.reset();
274 self.pending = None;
275 self.flushed = false;
276 }
277}