forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli10 hours ago4263 commits

mapping.rs238 lines, 9.5 KiBHistoryRawDownload
1//! What a logical stream carries, and what its granule positions mean.
2//!
3//! Ogg itself says nothing about time: a granule position is an opaque integer
4//! whose meaning belongs to the *mapping* named by the first packet. Vorbis and
5//! FLAC count samples at the stream's own rate; Opus counts samples at 48 kHz
6//! whatever the input rate was, and its count includes the pre-skip a decoder
7//! throws away (RFC 7845 §4). Everything timing-related in this crate goes
8//! through this module so those three conventions live in one place.
9
10use ec_core::{ChannelLayout, CodecId, TimeBase};
11
12/// A recognised logical-stream mapping, with what its identification header
13/// stated.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Mapping {
16 /// Vorbis I: three header packets, granule counts samples at `rate`.
17 Vorbis {
18 /// Sample rate from the identification header.
19 rate: u32,
20 /// Channel count from the identification header.
21 channels: u8,
22 },
23 /// Opus (RFC 7845): `OpusHead` then `OpusTags`, granule counts 48 kHz
24 /// samples and starts `pre_skip` above the first decoded sample.
25 Opus {
26 /// Output channel count.
27 channels: u8,
28 /// Samples (at 48 kHz) a decoder discards from the head of the stream.
29 pre_skip: u16,
30 /// Rate the encoder was fed, informational only — granules stay 48 kHz.
31 input_rate: u32,
32 },
33 /// FLAC-in-Ogg: `\x7fFLAC` mapping header carrying `fLaC` + STREAMINFO,
34 /// granule counts samples at `rate`.
35 Flac {
36 /// Sample rate from STREAMINFO.
37 rate: u32,
38 /// Channel count from STREAMINFO.
39 channels: u8,
40 /// Header packets this stream declares, the identification one included.
41 headers: usize,
42 },
43}
44
45impl Mapping {
46 /// Recognise a mapping from the first packet of a logical stream, or
47 /// [`None`] when nothing in the family claims it (Theora, Speex, Skeleton,
48 /// a private mapping — all valid Ogg, none of them ours).
49 pub fn identify(bos: &[u8]) -> Option<Mapping> {
50 if bos.len() >= 16 && bos[0] == 1 && &bos[1..7] == b"vorbis" {
51 let rate = u32::from_le_bytes(bos[12..16].try_into().ok()?);
52 return (rate != 0).then_some(Mapping::Vorbis {
53 rate,
54 channels: bos[11],
55 });
56 }
57 if bos.len() >= 19 && &bos[..8] == b"OpusHead" {
58 return Some(Mapping::Opus {
59 channels: bos[9],
60 pre_skip: u16::from_le_bytes(bos[10..12].try_into().ok()?),
61 input_rate: u32::from_le_bytes(bos[12..16].try_into().ok()?),
62 });
63 }
64 if bos.len() >= 51 && bos[0] == 0x7f && &bos[1..5] == b"FLAC" && &bos[9..13] == b"fLaC" {
65 // STREAMINFO starts after the mapping header and the metadata block
66 // header; its rate is 20 bits, then 3 bits of channel count - 1.
67 let si = &bos[17..51];
68 let rate =
69 (u32::from(si[10]) << 12) | (u32::from(si[11]) << 4) | u32::from(si[12] >> 4);
70 let declared = usize::from(u16::from_be_bytes([bos[7], bos[8]]));
71 return (rate != 0).then_some(Mapping::Flac {
72 rate,
73 channels: ((si[12] >> 1) & 0x07) + 1,
74 // A zero here means "not stated"; the comment header still
75 // follows, so two is the floor.
76 headers: (declared + 1).max(2),
77 });
78 }
79 None
80 }
81
82 /// Which codec decodes this stream's packets.
83 pub fn codec(&self) -> CodecId {
84 match self {
85 Mapping::Vorbis { .. } => CodecId::Vorbis,
86 Mapping::Opus { .. } => CodecId::Opus,
87 Mapping::Flac { .. } => CodecId::Flac,
88 }
89 }
90
91 /// The clock granule positions are counted in.
92 pub fn time_base(&self) -> TimeBase {
93 match self {
94 // Opus granules are always 48 kHz, whatever the encoder was fed.
95 Mapping::Opus { .. } => TimeBase::from_rate(48_000),
96 Mapping::Vorbis { rate, .. } | Mapping::Flac { rate, .. } => TimeBase::from_rate(*rate),
97 }
98 }
99
100 /// Decoded sample rate.
101 pub fn sample_rate(&self) -> u32 {
102 match self {
103 Mapping::Opus { .. } => 48_000,
104 Mapping::Vorbis { rate, .. } | Mapping::Flac { rate, .. } => *rate,
105 }
106 }
107
108 /// Channel layout, by count — Vorbis and Opus both order channels the way
109 /// [`ChannelLayout`] does for the layouts it names.
110 pub fn layout(&self) -> ChannelLayout {
111 let channels = match self {
112 Mapping::Vorbis { channels, .. }
113 | Mapping::Opus { channels, .. }
114 | Mapping::Flac { channels, .. } => *channels,
115 };
116 ChannelLayout::from_count(usize::from(channels).max(1))
117 }
118
119 /// How many packets belong to the stream's header, the identification
120 /// packet included. Audio starts after them.
121 pub fn header_packets(&self) -> usize {
122 match self {
123 Mapping::Vorbis { .. } => 3,
124 Mapping::Opus { .. } => 2,
125 Mapping::Flac { headers, .. } => *headers,
126 }
127 }
128
129 /// Samples this packet decodes to, in granule units, when the mapping makes
130 /// that cheap to know.
131 ///
132 /// Opus states it in the first byte of every packet, so its timing is exact
133 /// packet by packet. Vorbis does not: the block size of a packet is a mode
134 /// number whose meaning lives at the end of the setup header, past the full
135 /// codebook parse, which belongs to the Vorbis decoder rather than here —
136 /// so this answers [`None`] and the demuxer re-synchronises on every page
137 /// granule instead (see [`crate::demux`]). FLAC frame headers do state a
138 /// block size, but reading it means the frame parser, same argument.
139 pub fn packet_duration(&self, data: &[u8]) -> Option<i64> {
140 match self {
141 Mapping::Opus { .. } => opus_packet_samples(data),
142 Mapping::Vorbis { .. } | Mapping::Flac { .. } => None,
143 }
144 }
145}
146
147/// Samples at 48 kHz one Opus packet decodes to, from its TOC byte
148/// (RFC 6716 §3.1): a configuration number picking the frame duration, and a
149/// code picking how many frames are packed behind it.
150pub fn opus_packet_samples(data: &[u8]) -> Option<i64> {
151 let toc = *data.first()?;
152 let config = usize::from(toc >> 3);
153 // Frame duration in 48 kHz samples, per configuration block: SILK modes
154 // step 10/20/40/60 ms, hybrid 10/20 ms, CELT 2.5/5/10/20 ms.
155 let samples = match config {
156 0..=11 => [480, 960, 1920, 2880][config % 4],
157 12..=15 => [480, 960][config % 2],
158 _ => [120, 240, 480, 960][config % 4],
159 };
160 let frames = match toc & 0x03 {
161 0 => 1,
162 1 | 2 => 2,
163 // Code 3 states the count in the low six bits of the next byte.
164 _ => i64::from(*data.get(1)? & 0x3f),
165 };
166 // RFC 6716 §3.1: a packet may not exceed 120 ms of audio.
167 match frames * samples {
168 n if n > 0 && n <= 5760 => Some(n),
169 _ => None,
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176
177 #[test]
178 fn identifies_the_three_mappings() {
179 let mut vorbis = vec![1u8];
180 vorbis.extend_from_slice(b"vorbis");
181 vorbis.extend_from_slice(&0u32.to_le_bytes()); // version
182 vorbis.push(2); // channels
183 vorbis.extend_from_slice(&44_100u32.to_le_bytes());
184 vorbis.resize(30, 0);
185 assert_eq!(
186 Mapping::identify(&vorbis),
187 Some(Mapping::Vorbis {
188 rate: 44_100,
189 channels: 2
190 })
191 );
192
193 let mut opus = Vec::from(*b"OpusHead");
194 opus.push(1); // version
195 opus.push(6); // channels
196 opus.extend_from_slice(&312u16.to_le_bytes()); // pre-skip
197 opus.extend_from_slice(&48_000u32.to_le_bytes());
198 opus.resize(19, 0);
199 let mapping = Mapping::identify(&opus).unwrap();
200 assert_eq!(
201 mapping,
202 Mapping::Opus {
203 channels: 6,
204 pre_skip: 312,
205 input_rate: 48_000
206 }
207 );
208 // Whatever the input rate said, granules count 48 kHz samples.
209 assert_eq!(mapping.time_base(), TimeBase::from_rate(48_000));
210 assert_eq!(mapping.layout(), ChannelLayout::Surround5_1);
211 assert_eq!(mapping.header_packets(), 2);
212
213 vorbis[12..16].fill(0);
214 assert_eq!(Mapping::identify(&vorbis), None);
215 assert_eq!(Mapping::identify(b"not a header at all"), None);
216 assert_eq!(Mapping::identify(&[]), None);
217 }
218
219 #[test]
220 fn opus_durations_follow_the_toc() {
221 // config 16 (CELT 2.5 ms), one frame.
222 assert_eq!(opus_packet_samples(&[16 << 3]), Some(120));
223 // config 31 (CELT 20 ms), one frame; the 960 that every 48 kHz encoder
224 // in this family emits by default.
225 assert_eq!(opus_packet_samples(&[31 << 3]), Some(960));
226 // ...same config, code 1: two frames, so twice the samples.
227 assert_eq!(opus_packet_samples(&[(31 << 3) | 1]), Some(1920));
228 // Code 3 takes its frame count from the next byte, and 120 ms is the
229 // ceiling the RFC sets — 7 frames of 20 ms is over it.
230 assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 6]), Some(5760));
231 assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 7]), None);
232 assert_eq!(opus_packet_samples(&[(31 << 3) | 3, 0]), None);
233 assert_eq!(opus_packet_samples(&[(31 << 3) | 3]), None);
234 // SILK 60 ms narrowband.
235 assert_eq!(opus_packet_samples(&[3 << 3]), Some(2880));
236 assert_eq!(opus_packet_samples(&[]), None);
237 }
238}