forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa7e1d4cTahinli2 months ago3424 commits

packet.rs250 lines, 7.0 KiBHistoryRawDownload
1//! Compressed data units and the shared cheap-clone byte buffer.
2
3use std::ops::{Bound, Deref, RangeBounds};
4use std::sync::Arc;
5
6use crate::timebase::TimeBase;
7
8/// Reference-counted byte range: clone is a refcount bump, `slice` is free.
9///
10/// This is what keeps demuxed packets and decoded planes zero-copy — a
11/// container reads one cluster into a `Vec<u8>`, wraps it once, and hands out
12/// packets that borrow into it without copying or borrowing a lifetime (so the
13/// result stays `Send + 'static`).
14#[derive(Clone, Default)]
15pub struct Buf {
16 data: Arc<[u8]>,
17 off: usize,
18 len: usize,
19}
20
21impl Buf {
22 /// Empty buffer, no allocation beyond the empty `Arc`.
23 pub fn new() -> Buf {
24 Buf::default()
25 }
26
27 /// Take ownership of a `Vec` without copying its bytes.
28 pub fn from_vec(v: Vec<u8>) -> Buf {
29 let len = v.len();
30 Buf {
31 data: Arc::from(v),
32 off: 0,
33 len,
34 }
35 }
36
37 /// Copy a slice into a new buffer.
38 pub fn copy_from_slice(s: &[u8]) -> Buf {
39 Buf::from_vec(s.to_vec())
40 }
41
42 /// Length in bytes.
43 pub fn len(&self) -> usize {
44 self.len
45 }
46
47 /// True when the buffer holds no bytes.
48 pub fn is_empty(&self) -> bool {
49 self.len == 0
50 }
51
52 /// A sub-range of this buffer, sharing the same allocation.
53 ///
54 /// Panics on an out-of-bounds range, exactly like slicing a `&[u8]`.
55 pub fn slice(&self, range: impl RangeBounds<usize>) -> Buf {
56 let start = match range.start_bound() {
57 Bound::Included(&n) => n,
58 Bound::Excluded(&n) => n + 1,
59 Bound::Unbounded => 0,
60 };
61 let end = match range.end_bound() {
62 Bound::Included(&n) => n + 1,
63 Bound::Excluded(&n) => n,
64 Bound::Unbounded => self.len,
65 };
66 assert!(start <= end && end <= self.len, "Buf::slice out of bounds");
67 Buf {
68 data: Arc::clone(&self.data),
69 off: self.off + start,
70 len: end - start,
71 }
72 }
73}
74
75impl Deref for Buf {
76 type Target = [u8];
77
78 fn deref(&self) -> &[u8] {
79 &self.data[self.off..self.off + self.len]
80 }
81}
82
83impl AsRef<[u8]> for Buf {
84 fn as_ref(&self) -> &[u8] {
85 self
86 }
87}
88
89impl From<Vec<u8>> for Buf {
90 fn from(v: Vec<u8>) -> Buf {
91 Buf::from_vec(v)
92 }
93}
94
95impl From<&[u8]> for Buf {
96 fn from(s: &[u8]) -> Buf {
97 Buf::copy_from_slice(s)
98 }
99}
100
101impl PartialEq for Buf {
102 fn eq(&self, other: &Buf) -> bool {
103 **self == **other
104 }
105}
106
107impl Eq for Buf {}
108
109impl std::fmt::Debug for Buf {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 write!(f, "Buf({} bytes)", self.len)
112 }
113}
114
115/// Out-of-band data attached to a packet.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub enum SideData {
118 /// Codec configuration in the codec's own form (avcC, hvcC, av1C,
119 /// AudioSpecificConfig, ...) when it arrives in band rather than in
120 /// [`crate::registry::CodecParameters::extradata`].
121 CodecConfig(Buf),
122 /// Palette for palettised subtitle/image codecs.
123 Palette(Buf),
124 /// ISO 14496-12 3x3 display matrix (rotation/flip).
125 DisplayMatrix(Buf),
126 /// Anything a single container needs and nothing else understands.
127 Custom {
128 /// Container-defined discriminator.
129 kind: u32,
130 /// Raw payload.
131 data: Buf,
132 },
133}
134
135/// Per-packet booleans. All default to false.
136#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
137pub struct PacketFlags {
138 /// Decoding may start here (IDR, audio sync frame, subtitle cue start).
139 pub keyframe: bool,
140 /// Carries headers/config only, no presentable sample.
141 pub header: bool,
142 /// Known-damaged payload; decoders may attempt it and must not panic.
143 pub corrupt: bool,
144 /// Decode for state but do not present (post-seek pre-roll).
145 pub discard: bool,
146}
147
148/// One compressed access unit of one stream.
149///
150/// Fields are public: containers and codecs assemble packets field by field,
151/// and a builder chain would only hide that.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct Packet {
154 /// Index of the stream in [`crate::registry::Demuxer::streams`].
155 pub stream: u32,
156 /// Base of `pts`, `dts` and `duration`.
157 pub time_base: TimeBase,
158 /// Presentation timestamp, when the container states one.
159 pub pts: Option<i64>,
160 /// Decode timestamp, when it differs from `pts` (B-frames).
161 pub dts: Option<i64>,
162 /// Duration in `time_base` ticks, when known.
163 pub duration: Option<i64>,
164 /// Per-packet flags.
165 pub flags: PacketFlags,
166 /// Out-of-band extras; empty for almost every packet.
167 pub side_data: Vec<SideData>,
168 /// Compressed payload.
169 pub data: Buf,
170}
171
172impl Packet {
173 /// A packet with no timestamps and no flags set.
174 pub fn new(stream: u32, time_base: TimeBase, data: impl Into<Buf>) -> Packet {
175 Packet {
176 stream,
177 time_base,
178 pts: None,
179 dts: None,
180 duration: None,
181 flags: PacketFlags::default(),
182 side_data: Vec::new(),
183 data: data.into(),
184 }
185 }
186
187 /// Set the presentation timestamp, for the callers that build a packet in
188 /// one expression.
189 pub fn with_pts(mut self, pts: i64) -> Packet {
190 self.pts = Some(pts);
191 self
192 }
193
194 /// Set the duration in `time_base` ticks.
195 pub fn with_duration(mut self, duration: i64) -> Packet {
196 self.duration = Some(duration);
197 self
198 }
199
200 /// `pts + duration`, when both are known.
201 pub fn end_pts(&self) -> Option<i64> {
202 self.pts?.checked_add(self.duration?)
203 }
204
205 /// True when decoding may start at this packet.
206 pub fn is_keyframe(&self) -> bool {
207 self.flags.keyframe
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn buf_slices_share_one_allocation() {
217 let buf = Buf::from_vec(vec![0, 1, 2, 3, 4, 5]);
218 let mid = buf.slice(2..5);
219 assert_eq!(&*mid, &[2, 3, 4]);
220 assert_eq!(&*mid.slice(1..), &[3, 4]);
221 assert_eq!(mid.len(), 3);
222 assert!(Buf::new().is_empty());
223 // Clone is a refcount bump, not a copy: same bytes, no reallocation.
224 let clone = mid.clone();
225 assert_eq!(clone, mid);
226 assert_eq!(&*buf.slice(..), &[0, 1, 2, 3, 4, 5]);
227 }
228
229 #[test]
230 #[should_panic(expected = "out of bounds")]
231 fn buf_slice_rejects_out_of_range() {
232 Buf::from_vec(vec![0, 1]).slice(0..3);
233 }
234
235 #[test]
236 fn packet_construction() {
237 let tb = TimeBase::from_rate(48_000);
238 let mut p = Packet::new(0, tb, vec![0xff; 4]);
239 assert!(!p.is_keyframe());
240 assert_eq!(p.end_pts(), None);
241 p = p.with_pts(1024).with_duration(1024);
242 p.flags.keyframe = true;
243 p.side_data
244 .push(SideData::CodecConfig(Buf::copy_from_slice(&[0x12, 0x10])));
245 assert_eq!(p.end_pts(), Some(2048));
246 assert!(p.is_keyframe());
247 assert_eq!(p.data.len(), 4);
248 assert_eq!(p.time_base, TimeBase::new(1, 48_000));
249 }
250}