forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8fd360cTahinli2 months ago2655 commits

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