forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

frame.rs633 lines, 19.3 KiBHistoryRawDownload
1//! Decoded units: pictures and audio blocks.
2
3use crate::error::{Error, Result};
4use crate::packet::Buf;
5use crate::timebase::Timestamp;
6
7/// Pixel layout of a [`VideoFrame`].
8///
9/// Covers what the family actually moves: planar YUV 8/10/16-bit (software
10/// codecs), the semi-planar pairs hardware hands back (NV12, P010) and packed
11/// RGB for the display sink.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13pub enum PixelFormat {
14 /// Planar Y/U/V 4:2:0, 8-bit.
15 I420,
16 /// Planar Y/U/V 4:2:2, 8-bit.
17 I422,
18 /// Planar Y/U/V 4:4:4, 8-bit.
19 I444,
20 /// Planar Y/U/V 4:2:0, 10-bit in 16-bit little-endian samples.
21 I010,
22 /// Planar Y/U/V 4:2:2, 10-bit in 16-bit little-endian samples.
23 I210,
24 /// Planar Y/U/V 4:4:4, 10-bit in 16-bit little-endian samples.
25 I410,
26 /// Planar Y/U/V 4:4:4, 12-bit in 16-bit little-endian samples.
27 I412,
28 /// Y plane + interleaved U/V, 4:2:0, 8-bit.
29 Nv12,
30 /// Y plane + interleaved V/U, 4:2:0, 8-bit.
31 Nv21,
32 /// Y plane + interleaved U/V, 4:2:0, 10-bit in the high bits of 16.
33 P010,
34 /// Y plane + interleaved U/V, 4:2:0, 16-bit.
35 P016,
36 /// Single 8-bit luma plane.
37 Gray8,
38 /// Single 16-bit luma plane.
39 Gray16,
40 /// Packed 8-bit R,G,B.
41 Rgb8,
42 /// Packed 8-bit B,G,R.
43 Bgr8,
44 /// Packed 8-bit R,G,B,A.
45 Rgba8,
46 /// Packed 8-bit B,G,R,A — edith's display currency.
47 Bgra8,
48}
49
50impl PixelFormat {
51 /// Number of planes the format stores.
52 pub fn plane_count(&self) -> usize {
53 use PixelFormat::*;
54 match self {
55 I420 | I422 | I444 | I010 | I210 | I410 | I412 => 3,
56 Nv12 | Nv21 | P010 | P016 => 2,
57 Gray8 | Gray16 | Rgb8 | Bgr8 | Rgba8 | Bgra8 => 1,
58 }
59 }
60
61 /// True when chroma lives in its own plane(s) rather than packed with luma.
62 pub fn is_planar(&self) -> bool {
63 self.plane_count() > 1
64 }
65
66 /// True for the YUV families (planar and semi-planar).
67 pub fn is_yuv(&self) -> bool {
68 use PixelFormat::*;
69 matches!(
70 self,
71 I420 | I422 | I444 | I010 | I210 | I410 | I412 | Nv12 | Nv21 | P010 | P016
72 )
73 }
74
75 /// True when the format carries an alpha channel.
76 pub fn has_alpha(&self) -> bool {
77 matches!(self, PixelFormat::Rgba8 | PixelFormat::Bgra8)
78 }
79
80 /// Significant bits per component (10 for P010 even though it stores 16).
81 pub fn bits_per_component(&self) -> u32 {
82 use PixelFormat::*;
83 match self {
84 I010 | I210 | I410 | P010 => 10,
85 I412 => 12,
86 Gray16 | P016 => 16,
87 _ => 8,
88 }
89 }
90
91 /// Storage bytes per component (2 for every 10- and 16-bit format).
92 pub fn bytes_per_component(&self) -> usize {
93 if self.bits_per_component() > 8 { 2 } else { 1 }
94 }
95
96 /// `(log2 horizontal, log2 vertical)` chroma subsampling; `(0, 0)` for
97 /// non-subsampled and non-YUV formats.
98 pub fn chroma_shift(&self) -> (u32, u32) {
99 use PixelFormat::*;
100 match self {
101 I420 | I010 | Nv12 | Nv21 | P010 | P016 => (1, 1),
102 I422 | I210 => (1, 0),
103 _ => (0, 0),
104 }
105 }
106
107 /// Per plane: `(minimum bytes per row, number of rows)` for `width x height`.
108 pub fn plane_geometry(&self, width: u32, height: u32) -> Vec<(usize, usize)> {
109 use PixelFormat::*;
110 let (w, h) = (width as usize, height as usize);
111 let bpc = self.bytes_per_component();
112 let (sx, sy) = self.chroma_shift();
113 let cw = w.div_ceil(1 << sx);
114 let ch = h.div_ceil(1 << sy);
115 match self {
116 I420 | I422 | I444 | I010 | I210 | I410 | I412 => {
117 vec![(w * bpc, h), (cw * bpc, ch), (cw * bpc, ch)]
118 }
119 Nv12 | Nv21 | P010 | P016 => vec![(w * bpc, h), (cw * 2 * bpc, ch)],
120 Gray8 | Gray16 => vec![(w * bpc, h)],
121 Rgb8 | Bgr8 => vec![(w * 3, h)],
122 Rgba8 | Bgra8 => vec![(w * 4, h)],
123 }
124 }
125}
126
127/// One image plane: bytes plus the distance between row starts.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct Plane {
130 /// Plane bytes; may be a shared slice of a larger buffer.
131 pub data: Buf,
132 /// Bytes from the start of one row to the start of the next.
133 pub stride: usize,
134}
135
136impl Plane {
137 /// A plane over `data` with row pitch `stride`.
138 pub fn new(data: impl Into<Buf>, stride: usize) -> Plane {
139 Plane {
140 data: data.into(),
141 stride,
142 }
143 }
144
145 /// Row `y` of the plane, `len` bytes wide, or `None` when out of range.
146 pub fn row(&self, y: usize, len: usize) -> Option<&[u8]> {
147 let start = y.checked_mul(self.stride)?;
148 self.data.get(start..start.checked_add(len)?)
149 }
150}
151
152/// CICP (ITU-T H.273) colour code points, carried verbatim.
153///
154/// Kept as raw code points here so the IR never loses a value it cannot name;
155/// the named tables (BT.709/2020, PQ, HLG, ...) live in the colour module built
156/// on top of this.
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
158pub struct ColorInfo {
159 /// `colour_primaries` code point (1 = BT.709, 9 = BT.2020, 2 = unspecified).
160 pub primaries: u8,
161 /// `transfer_characteristics` code point (16 = PQ, 18 = HLG).
162 pub transfer: u8,
163 /// `matrix_coefficients` code point (1 = BT.709, 9 = BT.2020 NCL).
164 pub matrix: u8,
165 /// `video_full_range_flag`: false = limited (16-235), true = full.
166 pub full_range: bool,
167}
168
169impl Default for ColorInfo {
170 /// All three code points unspecified (2), limited range.
171 fn default() -> Self {
172 ColorInfo {
173 primaries: 2,
174 transfer: 2,
175 matrix: 2,
176 full_range: false,
177 }
178 }
179}
180
181/// How the two fields of a frame relate, for pictures from interlaced sources.
182///
183/// The planes of a [`VideoFrame`] always hold the fields woven together (top
184/// field on the even lines); this says whether they were captured as two
185/// moments in time, and which of them came first.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
187pub enum Interlace {
188 /// One moment in time for the whole frame.
189 #[default]
190 Progressive,
191 /// Interlaced; the top field (even lines) is displayed first.
192 TopFieldFirst,
193 /// Interlaced; the bottom field (odd lines) is displayed first.
194 BottomFieldFirst,
195}
196
197impl Interlace {
198 /// True for either interlaced order.
199 pub fn is_interlaced(self) -> bool {
200 self != Interlace::Progressive
201 }
202}
203
204/// A decoded picture.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct VideoFrame {
207 /// Pixel layout of `planes`.
208 pub format: PixelFormat,
209 /// Visible width in pixels.
210 pub width: u32,
211 /// Visible height in pixels.
212 pub height: u32,
213 /// One entry per [`PixelFormat::plane_count`].
214 pub planes: Vec<Plane>,
215 /// Colour description as signalled by the bitstream or container.
216 pub color: ColorInfo,
217 /// Presentation time, when the source provided one.
218 pub pts: Option<Timestamp>,
219 /// Whether the frame is interlaced and in which order its fields display.
220 pub interlace: Interlace,
221}
222
223impl VideoFrame {
224 /// A frame over existing planes, validating plane count and plane sizes.
225 ///
226 /// This is the trust boundary between a decoder and everything that indexes
227 /// planes afterwards; a short plane fails here rather than in a converter.
228 pub fn try_new(
229 format: PixelFormat,
230 width: u32,
231 height: u32,
232 planes: Vec<Plane>,
233 ) -> Result<VideoFrame> {
234 let geometry = format.plane_geometry(width, height);
235 if planes.len() != geometry.len() {
236 return Err(Error::corrupt(format!(
237 "{format:?} needs {} planes, got {}",
238 geometry.len(),
239 planes.len()
240 )));
241 }
242 for (i, (plane, (row_bytes, rows))) in planes.iter().zip(geometry).enumerate() {
243 if plane.stride < row_bytes {
244 return Err(Error::corrupt(format!(
245 "plane {i}: stride {} < {row_bytes} bytes per row",
246 plane.stride
247 )));
248 }
249 // The last row need only hold its visible bytes, not a full stride.
250 let needed = rows.saturating_sub(1) * plane.stride + row_bytes;
251 if plane.data.len() < needed {
252 return Err(Error::corrupt(format!(
253 "plane {i}: {} bytes for {rows} rows of stride {}",
254 plane.data.len(),
255 plane.stride
256 )));
257 }
258 }
259 Ok(VideoFrame {
260 format,
261 width,
262 height,
263 planes,
264 color: ColorInfo::default(),
265 pts: None,
266 interlace: Interlace::Progressive,
267 })
268 }
269
270 /// A zeroed frame with tightly packed planes.
271 pub fn alloc(format: PixelFormat, width: u32, height: u32) -> VideoFrame {
272 let planes = format
273 .plane_geometry(width, height)
274 .into_iter()
275 .map(|(row_bytes, rows)| Plane::new(vec![0u8; row_bytes * rows], row_bytes))
276 .collect();
277 VideoFrame {
278 format,
279 width,
280 height,
281 planes,
282 color: ColorInfo::default(),
283 pts: None,
284 interlace: Interlace::Progressive,
285 }
286 }
287}
288
289/// Sample storage of an [`AudioFrame`]. 24-bit sources decode into [`SampleFormat::S32`].
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
291pub enum SampleFormat {
292 /// Unsigned 8-bit.
293 U8,
294 /// Signed 16-bit native endian.
295 S16,
296 /// Signed 32-bit native endian.
297 S32,
298 /// 32-bit float, nominal range -1.0..=1.0 — the family's mixing currency.
299 F32,
300 /// 64-bit float.
301 F64,
302}
303
304impl SampleFormat {
305 /// Bytes one sample of one channel occupies.
306 pub fn bytes_per_sample(&self) -> usize {
307 match self {
308 SampleFormat::U8 => 1,
309 SampleFormat::S16 => 2,
310 SampleFormat::S32 | SampleFormat::F32 => 4,
311 SampleFormat::F64 => 8,
312 }
313 }
314
315 /// True for the float formats.
316 pub fn is_float(&self) -> bool {
317 matches!(self, SampleFormat::F32 | SampleFormat::F64)
318 }
319}
320
321/// A named speaker position.
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
323pub enum ChannelPosition {
324 /// Front left.
325 FrontLeft,
326 /// Front right.
327 FrontRight,
328 /// Front centre.
329 FrontCenter,
330 /// Low frequency effects.
331 Lfe,
332 /// Back (surround) left.
333 BackLeft,
334 /// Back (surround) right.
335 BackRight,
336 /// Side left.
337 SideLeft,
338 /// Side right.
339 SideRight,
340 /// Back centre.
341 BackCenter,
342 /// Front left of centre.
343 FrontLeftOfCenter,
344 /// Front right of centre.
345 FrontRightOfCenter,
346}
347
348use ChannelPosition::*;
349
350const MONO: &[ChannelPosition] = &[FrontCenter];
351const STEREO: &[ChannelPosition] = &[FrontLeft, FrontRight];
352const SURROUND_5_1: &[ChannelPosition] =
353 &[FrontLeft, FrontRight, FrontCenter, Lfe, BackLeft, BackRight];
354const SURROUND_7_1: &[ChannelPosition] = &[
355 FrontLeft,
356 FrontRight,
357 FrontCenter,
358 Lfe,
359 BackLeft,
360 BackRight,
361 SideLeft,
362 SideRight,
363];
364
365/// Channel count plus the meaning and order of each channel.
366///
367/// The named layouts fix the interleaving order the family decodes and encodes
368/// in; 5.1 is FL, FR, FC, LFE, BL, BR.
369#[derive(Debug, Clone, PartialEq, Eq, Hash)]
370pub enum ChannelLayout {
371 /// One channel, front centre.
372 Mono,
373 /// FL, FR.
374 Stereo,
375 /// FL, FR, FC, LFE, BL, BR.
376 Surround5_1,
377 /// FL, FR, FC, LFE, BL, BR, SL, SR.
378 Surround7_1,
379 /// Any other ordering a container states explicitly.
380 Custom(Vec<ChannelPosition>),
381}
382
383impl ChannelLayout {
384 /// Channel order, as interleaved and as planes are indexed.
385 pub fn positions(&self) -> &[ChannelPosition] {
386 match self {
387 ChannelLayout::Mono => MONO,
388 ChannelLayout::Stereo => STEREO,
389 ChannelLayout::Surround5_1 => SURROUND_5_1,
390 ChannelLayout::Surround7_1 => SURROUND_7_1,
391 ChannelLayout::Custom(v) => v,
392 }
393 }
394
395 /// Number of channels.
396 pub fn channel_count(&self) -> usize {
397 self.positions().len()
398 }
399
400 /// The default layout for a bare channel count, as containers that state
401 /// only a count intend it.
402 pub fn from_count(n: usize) -> ChannelLayout {
403 match n {
404 1 => ChannelLayout::Mono,
405 2 => ChannelLayout::Stereo,
406 6 => ChannelLayout::Surround5_1,
407 8 => ChannelLayout::Surround7_1,
408 _ => ChannelLayout::Custom(vec![FrontCenter; n]),
409 }
410 }
411}
412
413/// A decoded block of audio.
414#[derive(Debug, Clone, PartialEq, Eq)]
415pub struct AudioFrame {
416 /// Sample storage format.
417 pub format: SampleFormat,
418 /// True when `data` holds one plane per channel, false when interleaved.
419 pub planar: bool,
420 /// Channel count, order and meaning.
421 pub layout: ChannelLayout,
422 /// Sample rate in Hz.
423 pub rate: u32,
424 /// Samples per channel in this frame.
425 pub samples: usize,
426 /// One plane when interleaved, one per channel when planar.
427 pub data: Vec<Buf>,
428 /// Presentation time, when the source provided one.
429 pub pts: Option<Timestamp>,
430}
431
432impl AudioFrame {
433 /// An audio frame over existing planes, validating plane count and length.
434 pub fn try_new(
435 format: SampleFormat,
436 planar: bool,
437 layout: ChannelLayout,
438 rate: u32,
439 samples: usize,
440 data: Vec<Buf>,
441 ) -> Result<AudioFrame> {
442 let channels = layout.channel_count();
443 let wanted_planes = if planar { channels } else { 1 };
444 if data.len() != wanted_planes {
445 return Err(Error::corrupt(format!(
446 "{layout:?} {} needs {wanted_planes} planes, got {}",
447 if planar { "planar" } else { "interleaved" },
448 data.len()
449 )));
450 }
451 let per_plane = if planar { 1 } else { channels };
452 let needed = samples * per_plane * format.bytes_per_sample();
453 for (i, plane) in data.iter().enumerate() {
454 if plane.len() < needed {
455 return Err(Error::corrupt(format!(
456 "audio plane {i}: {} bytes, {needed} needed for {samples} samples",
457 plane.len()
458 )));
459 }
460 }
461 Ok(AudioFrame {
462 format,
463 planar,
464 layout,
465 rate,
466 samples,
467 data,
468 pts: None,
469 })
470 }
471
472 /// Channel count of the layout.
473 pub fn channels(&self) -> usize {
474 self.layout.channel_count()
475 }
476}
477
478/// What a decoder produces.
479///
480/// Subtitles are deliberately absent: a decoded subtitle is a cue list or a
481/// bitmap region set, not a sample grid, so subtitle streams travel as
482/// [`crate::packet::Packet`]s and are parsed by the subtitle crate into its own
483/// IR.
484#[derive(Debug, Clone, PartialEq, Eq)]
485pub enum Frame {
486 /// A decoded picture.
487 Video(VideoFrame),
488 /// A decoded audio block.
489 Audio(AudioFrame),
490}
491
492impl Frame {
493 /// Presentation time of either variant.
494 pub fn pts(&self) -> Option<Timestamp> {
495 match self {
496 Frame::Video(v) => v.pts,
497 Frame::Audio(a) => a.pts,
498 }
499 }
500}
501
502#[cfg(test)]
503mod tests {
504 use super::*;
505 use crate::timebase::TimeBase;
506
507 #[test]
508 fn plane_geometry_matches_formats() {
509 // Odd dimensions round chroma up, never down.
510 assert_eq!(
511 PixelFormat::I420.plane_geometry(1921, 1081),
512 vec![(1921, 1081), (961, 541), (961, 541)]
513 );
514 assert_eq!(
515 PixelFormat::Nv12.plane_geometry(1920, 1080),
516 vec![(1920, 1080), (1920, 540)]
517 );
518 // P010: 2 bytes per component, interleaved chroma pair.
519 assert_eq!(
520 PixelFormat::P010.plane_geometry(1920, 1080),
521 vec![(3840, 1080), (3840, 540)]
522 );
523 assert_eq!(PixelFormat::Bgra8.plane_geometry(64, 4), vec![(256, 4)]);
524 assert_eq!(PixelFormat::I444.plane_geometry(16, 16).len(), 3);
525 assert_eq!(PixelFormat::P010.bits_per_component(), 10);
526 assert_eq!(PixelFormat::P010.bytes_per_component(), 2);
527 assert!(PixelFormat::Bgra8.has_alpha());
528 assert!(!PixelFormat::Nv12.has_alpha());
529 assert!(PixelFormat::Nv12.is_yuv());
530 }
531
532 #[test]
533 fn video_frame_validates_planes() {
534 let f = VideoFrame::alloc(PixelFormat::I420, 64, 32);
535 assert_eq!(f.planes.len(), 3);
536 assert_eq!(f.planes[0].stride, 64);
537 assert_eq!(f.planes[1].data.len(), 32 * 16);
538 assert_eq!(f.planes[0].row(31, 64).unwrap().len(), 64);
539 assert!(f.planes[0].row(32, 64).is_none());
540
541 // Padded strides are legal; short planes and short strides are not.
542 let padded = VideoFrame::try_new(
543 PixelFormat::Gray8,
544 4,
545 2,
546 vec![Plane::new(vec![0u8; 8 + 4], 8)],
547 );
548 assert!(padded.is_ok());
549 assert!(
550 VideoFrame::try_new(PixelFormat::Gray8, 4, 2, vec![Plane::new(vec![0u8; 8], 2)])
551 .is_err()
552 );
553 assert!(
554 VideoFrame::try_new(PixelFormat::I420, 4, 2, vec![Plane::new(vec![0u8; 8], 4)])
555 .is_err()
556 );
557 }
558
559 #[test]
560 fn channel_layouts_are_named_and_ordered() {
561 assert_eq!(
562 ChannelLayout::Surround5_1.positions(),
563 &[
564 ChannelPosition::FrontLeft,
565 ChannelPosition::FrontRight,
566 ChannelPosition::FrontCenter,
567 ChannelPosition::Lfe,
568 ChannelPosition::BackLeft,
569 ChannelPosition::BackRight
570 ]
571 );
572 assert_eq!(ChannelLayout::Surround7_1.channel_count(), 8);
573 assert_eq!(ChannelLayout::from_count(6), ChannelLayout::Surround5_1);
574 assert_eq!(ChannelLayout::from_count(3).channel_count(), 3);
575 }
576
577 #[test]
578 fn audio_frame_validates_planes() {
579 let interleaved = AudioFrame::try_new(
580 SampleFormat::F32,
581 false,
582 ChannelLayout::Surround5_1,
583 48_000,
584 1024,
585 vec![Buf::from_vec(vec![0u8; 1024 * 6 * 4])],
586 )
587 .unwrap();
588 assert_eq!(interleaved.channels(), 6);
589
590 let planar = AudioFrame::try_new(
591 SampleFormat::S16,
592 true,
593 ChannelLayout::Stereo,
594 44_100,
595 512,
596 vec![Buf::from_vec(vec![0u8; 1024]); 2],
597 )
598 .unwrap();
599 assert_eq!(planar.data.len(), 2);
600
601 // Wrong plane count and short planes are rejected, not truncated.
602 assert!(
603 AudioFrame::try_new(
604 SampleFormat::F32,
605 true,
606 ChannelLayout::Stereo,
607 48_000,
608 64,
609 vec![Buf::from_vec(vec![0u8; 256])]
610 )
611 .is_err()
612 );
613 assert!(
614 AudioFrame::try_new(
615 SampleFormat::F32,
616 false,
617 ChannelLayout::Stereo,
618 48_000,
619 64,
620 vec![Buf::from_vec(vec![0u8; 4])]
621 )
622 .is_err()
623 );
624 }
625
626 #[test]
627 fn frame_pts_passthrough() {
628 let mut v = VideoFrame::alloc(PixelFormat::Nv12, 16, 16);
629 v.pts = Some(Timestamp::new(1001, TimeBase::new(1, 24_000)));
630 let f = Frame::Video(v);
631 assert_eq!(f.pts().unwrap().ticks, 1001);
632 }
633}