forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB552edc4Tahinli2 months ago2048 commits

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