forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

adts.rs213 lines, 7.3 KiBHistoryRawDownload
1//! A standalone ADTS file (`.aac`: AAC frames, each behind its own header) as a
2//! symphonia format reader.
3//!
4//! symphonia ships this reader inside its `aac` feature, and that feature is
5//! the codec crate this project no longer links. So the reader is here, and it
6//! is small: a frame is a 7- or 9-byte header and a payload, and the header
7//! says how long the frame is. What it hands on is the whole frame, header
8//! included, because `ec-aac` decodes ADTS from its own headers and needs no
9//! config of its own to do so.
10//!
11//! Frames are counted when the file is opened, so the track has its length
12//! the way an mp4 does and a seek can land on an exact frame.
13
14use std::io::{Read, Seek, SeekFrom};
15use std::num::NonZeroU32;
16
17use symphonia_core::audio::Channels;
18use symphonia_core::codecs::CodecParameters;
19use symphonia_core::codecs::audio::AudioCodecParameters;
20use symphonia_core::codecs::audio::well_known::CODEC_ID_AAC;
21use symphonia_core::errors::{Error, Result, SeekErrorKind, decode_error};
22use symphonia_core::formats::well_known::FORMAT_ID_ADTS;
23use symphonia_core::formats::{
24 FormatInfo, FormatReader, MediaInfo, SeekMode, SeekTo, SeekedTo, Track,
25};
26use symphonia_core::io::MediaSourceStream;
27use symphonia_core::meta::{Metadata, MetadataLog};
28use symphonia_core::packet::Packet;
29use symphonia_core::units::{Duration, TimeBase, Timestamp};
30
31/// Samples per channel in one AAC-LC raw data block, which is what an ADTS
32/// frame carries per block. Fixed by the codec.
33const SAMPLES_PER_BLOCK: i64 = 1024;
34
35/// Longest ADTS header there is: seven bytes, or nine with the CRC.
36const MAX_HEADER: usize = 9;
37
38const ADTS_FORMAT_INFO: FormatInfo = FormatInfo {
39 format: FORMAT_ID_ADTS,
40 short_name: "aac",
41 long_name: "Audio Data Transport Stream (native AAC)",
42};
43
44/// An ADTS file, read from its first frame to its last.
45pub(crate) struct AdtsReader<'s> {
46 reader: MediaSourceStream<'s>,
47 media_info: MediaInfo,
48 tracks: Vec<Track>,
49 metadata: MetadataLog,
50 /// Byte offset of the first frame, the place a seek back to the start goes.
51 first_frame_pos: u64,
52 /// Timestamp, in samples, of the frame the reader is positioned at.
53 next_ts: i64,
54}
55
56impl<'s> AdtsReader<'s> {
57 /// The reader over `mss`, which must be seekable: a file, not a pipe. The
58 /// first frame's header says what the track is, and the whole file is
59 /// walked once to count its frames.
60 pub(crate) fn try_new(mut mss: MediaSourceStream<'s>) -> Result<Self> {
61 let first_frame_pos = mss.stream_position()?;
62 let Some(first) = next_header(&mut mss)? else {
63 return decode_error("adts: no frame header");
64 };
65 let rate = NonZeroU32::new(first.sample_rate)
66 .ok_or(Error::DecodeError("adts: zero sample rate"))?;
67
68 let mut params = AudioCodecParameters::new();
69 params
70 .for_codec(CODEC_ID_AAC)
71 .with_sample_rate(first.sample_rate);
72 if first.channels > 0 {
73 params.with_channels(Channels::Discrete(first.channels));
74 }
75
76 let mut track = Track::new(0);
77 track
78 .with_codec_params(CodecParameters::Audio(params))
79 .with_time_base(TimeBase::new(NonZeroU32::MIN, rate));
80
81 let frames = count_frames(&mut mss)?;
82 track.with_num_frames(frames);
83 track.with_duration(Duration::new(frames));
84
85 Ok(AdtsReader {
86 media_info: MediaInfo::from_track(&track),
87 tracks: vec![track],
88 reader: mss,
89 metadata: MetadataLog::default(),
90 first_frame_pos,
91 next_ts: 0,
92 })
93 }
94}
95
96/// The header of the frame at the reader's position, which is left where it
97/// was. `None` at the end of the stream, or on a tail too short to be a header.
98fn next_header(reader: &mut MediaSourceStream<'_>) -> Result<Option<ec_aac::AdtsHeader>> {
99 let at = reader.stream_position()?;
100 let mut buf = [0u8; MAX_HEADER];
101 let mut got = 0;
102 while got < MAX_HEADER {
103 match reader.read(&mut buf[got..])? {
104 0 => break,
105 n => got += n,
106 }
107 }
108 if got < 7 {
109 return Ok(None);
110 }
111 let header = ec_aac::parse_adts(&buf[..got])
112 .map_err(|_| Error::DecodeError("adts: invalid frame header"))?;
113 if header.frame_length < header.header_len {
114 return decode_error("adts: frame shorter than its header");
115 }
116 reader.seek(SeekFrom::Start(at))?;
117 Ok(Some(header))
118}
119
120/// Samples per channel an ADTS frame carries: one block of 1024 per raw data
121/// block it holds.
122fn frame_samples(header: &ec_aac::AdtsHeader) -> i64 {
123 SAMPLES_PER_BLOCK * i64::from(header.raw_blocks.max(1))
124}
125
126/// Every frame in the file, counted by walking the headers alone, as its length
127/// in samples per channel. The reader is left where it was.
128fn count_frames(reader: &mut MediaSourceStream<'_>) -> Result<u64> {
129 let start = reader.stream_position()?;
130 let mut total = 0u64;
131 while let Some(header) = next_header(reader)? {
132 total += frame_samples(&header) as u64;
133 reader.seek(SeekFrom::Current(header.frame_length as i64))?;
134 }
135 reader.seek(SeekFrom::Start(start))?;
136 Ok(total)
137}
138
139impl FormatReader for AdtsReader<'_> {
140 fn format_info(&self) -> &FormatInfo {
141 &ADTS_FORMAT_INFO
142 }
143
144 fn media_info(&self) -> &MediaInfo {
145 &self.media_info
146 }
147
148 fn metadata(&mut self) -> Metadata<'_> {
149 self.metadata.metadata()
150 }
151
152 fn seek(&mut self, _mode: SeekMode, to: SeekTo) -> Result<SeekedTo> {
153 let required = match to {
154 SeekTo::Timestamp { ts, .. } => ts,
155 SeekTo::Time { time, .. } => self.tracks[0]
156 .time_base
157 .and_then(|tb| tb.calc_timestamp(time))
158 .ok_or(Error::SeekError(SeekErrorKind::Unseekable))?,
159 };
160 let required_ts = required.get();
161
162 // Behind the reader: go back to the first frame and walk from there.
163 if required_ts < self.next_ts {
164 self.reader.seek(SeekFrom::Start(self.first_frame_pos))?;
165 self.next_ts = 0;
166 }
167
168 // Skip whole frames while the next one still starts at or before the
169 // target, then stand on the frame that contains it.
170 while let Some(header) = next_header(&mut self.reader)? {
171 let samples = frame_samples(&header);
172 if self.next_ts + samples > required_ts {
173 break;
174 }
175 self.reader.seek(SeekFrom::Current(header.frame_length as i64))?;
176 self.next_ts += samples;
177 }
178
179 Ok(SeekedTo {
180 track_id: 0,
181 required_ts: required,
182 actual_ts: Timestamp::new(self.next_ts),
183 })
184 }
185
186 fn tracks(&self) -> &[Track] {
187 &self.tracks
188 }
189
190 fn next_packet(&mut self) -> Result<Option<Packet>> {
191 let Some(header) = next_header(&mut self.reader)? else {
192 return Ok(None);
193 };
194 let mut frame = vec![0u8; header.frame_length];
195 self.reader.read_exact(&mut frame)?;
196 let samples = frame_samples(&header);
197 let ts = self.next_ts;
198 self.next_ts += samples;
199 Ok(Some(Packet::new(
200 0,
201 Timestamp::new(ts),
202 Duration::new(samples as u64),
203 frame,
204 )))
205 }
206
207 fn into_inner<'s>(self: Box<Self>) -> MediaSourceStream<'s>
208 where
209 Self: 's,
210 {
211 self.reader
212 }
213}