forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

lib.rs578 lines, 21.0 KiBHistoryRawDownload
1//! Blu-ray Presentation Graphic Stream: the subtitles that are *pictures*.
2//!
3//! A PGS stream is a sequence of display sets, each a handful of segments: a
4//! presentation composition (PCS — the canvas and where the objects go on it), a
5//! window definition (WDS), a palette (PDS), one or more run-length objects
6//! (ODS) and an end marker (END). A set is decoded against the state the sets
7//! before it left behind, which is why this is a decoder with an epoch and not
8//! a function: an acquisition point re-states everything, a normal-case set may
9//! re-use an object or merely swap the palette.
10//!
11//! What comes out is one straight-alpha RGBA frame per display set, the size of
12//! the composition's own canvas (1920×1080 off a disc), transparent everywhere
13//! the cue paints nothing. That is the shape a compositor wants and the shape
14//! `.sup` tooling shows: a caller lays the whole canvas over the film rather
15//! than placing a sprite.
16//!
17//! The framing read here is the `.sup` one — `PG`, two timestamps, type, size —
18//! because that is what a `.sup` file holds and what a Matroska block becomes
19//! once its header is put back on ([`ec_subs`] is the text half of the same
20//! story). Colour is BT.601 limited-range, which is what the palette entries of
21//! a disc are and what every other decoder of this format assumes.
22
23#![forbid(unsafe_code)]
24
25use std::collections::HashMap;
26
27use ec_core::{
28 CodecId, CodecParameters, Decoder, Error, Frame, PixelFormat, Plane, Result, VideoFrame,
29};
30
31/// Palette definition segment.
32pub const SEG_PDS: u8 = 0x14;
33/// Object definition segment: the run-length bitmap itself.
34pub const SEG_ODS: u8 = 0x15;
35/// Presentation composition segment: canvas size and object placement.
36pub const SEG_PCS: u8 = 0x16;
37/// Window definition segment.
38pub const SEG_WDS: u8 = 0x17;
39/// End of display set — the point at which a frame is complete.
40pub const SEG_END: u8 = 0x80;
41
42/// The magic every `.sup` segment starts with.
43const MAGIC: [u8; 2] = *b"PG";
44/// Bytes before a segment's body: magic, PTS, DTS, type, size.
45const HEADER: usize = 13;
46
47/// A decoder over a `.sup` byte stream.
48///
49/// Feed it whole segments ([`PgsDecoder::push`]) — a partial one is held until
50/// the rest arrives, so a caller may split the stream anywhere — and take a
51/// frame per display set ([`PgsDecoder::take_frame`]).
52pub struct PgsDecoder {
53 params: CodecParameters,
54 /// Bytes not yet forming a whole segment.
55 pending: Vec<u8>,
56 /// Objects by id, decoded run-length data as the stream stated it.
57 objects: HashMap<u16, Object>,
58 /// The object being assembled out of a multi-segment ODS sequence.
59 partial: Option<(u16, Object)>,
60 /// Palettes by id: 256 straight-alpha RGBA entries each.
61 palettes: HashMap<u8, Box<[[u8; 4]; 256]>>,
62 /// Windows by id, for clipping.
63 windows: HashMap<u8, Rect>,
64 /// The composition the current display set is building.
65 composition: Composition,
66 /// Frames finished but not yet taken.
67 ready: Vec<VideoFrame>,
68}
69
70#[derive(Clone, Default)]
71struct Object {
72 width: u32,
73 height: u32,
74 rle: Vec<u8>,
75}
76
77#[derive(Clone, Copy, Default)]
78struct Rect {
79 x: u32,
80 y: u32,
81 width: u32,
82 height: u32,
83}
84
85#[derive(Clone, Default)]
86struct Composition {
87 width: u32,
88 height: u32,
89 palette_id: u8,
90 objects: Vec<Placement>,
91}
92
93#[derive(Clone, Copy)]
94struct Placement {
95 object_id: u16,
96 window_id: u8,
97 x: u32,
98 y: u32,
99 crop: Option<Rect>,
100}
101
102impl Default for PgsDecoder {
103 fn default() -> Self {
104 PgsDecoder::new()
105 }
106}
107
108impl PgsDecoder {
109 /// A decoder with no epoch yet: the first display set states everything.
110 pub fn new() -> PgsDecoder {
111 PgsDecoder {
112 params: CodecParameters::new(CodecId::Pgs),
113 pending: Vec::new(),
114 objects: HashMap::new(),
115 partial: None,
116 palettes: HashMap::new(),
117 windows: HashMap::new(),
118 composition: Composition::default(),
119 ready: Vec::new(),
120 }
121 }
122
123 /// Feed stream bytes. Every complete segment in them is consumed; a partial
124 /// tail is kept for the next call.
125 ///
126 /// A segment whose body is nonsense (a palette entry short, an object
127 /// claiming more pixels than its bitmap holds) is dropped and the stream
128 /// carries on: one torn display set out of eleven thousand must not cost
129 /// the track.
130 pub fn push(&mut self, bytes: &[u8]) -> Result<()> {
131 let mut buffer = std::mem::take(&mut self.pending);
132 buffer.extend_from_slice(bytes);
133 let mut data: &[u8] = &buffer;
134 loop {
135 if data.len() < HEADER {
136 break;
137 }
138 if data[..2] != MAGIC {
139 // Not a segment boundary at all: resynchronising would invent
140 // structure, so this is the one hard error.
141 return Err(Error::corrupt("PGS: segment does not start with `PG`"));
142 }
143 let size = u16::from_be_bytes([data[11], data[12]]) as usize;
144 if data.len() < HEADER + size {
145 break;
146 }
147 let kind = data[10];
148 let body = &data[HEADER..HEADER + size];
149 self.segment(kind, body);
150 data = &data[HEADER + size..];
151 }
152 self.pending = data.to_vec();
153 Ok(())
154 }
155
156 /// The next finished display set, oldest first.
157 pub fn take_frame(&mut self) -> Option<VideoFrame> {
158 match self.ready.is_empty() {
159 true => None,
160 false => Some(self.ready.remove(0)),
161 }
162 }
163
164 /// One segment against the running state.
165 fn segment(&mut self, kind: u8, body: &[u8]) {
166 match kind {
167 SEG_PCS => self.pcs(body),
168 SEG_WDS => self.wds(body),
169 SEG_PDS => self.pds(body),
170 SEG_ODS => self.ods(body),
171 SEG_END => {
172 if let Some(frame) = self.render() {
173 self.ready.push(frame);
174 }
175 }
176 _ => {}
177 }
178 }
179
180 fn pcs(&mut self, body: &[u8]) {
181 if body.len() < 11 {
182 return;
183 }
184 let composition_state = body[7];
185 // Epoch start: nothing from before this point is referenced again.
186 if composition_state & 0x80 != 0 {
187 self.objects.clear();
188 self.palettes.clear();
189 self.windows.clear();
190 self.partial = None;
191 }
192 let mut composition = Composition {
193 width: u32::from(u16::from_be_bytes([body[0], body[1]])),
194 height: u32::from(u16::from_be_bytes([body[2], body[3]])),
195 palette_id: body[9],
196 objects: Vec::new(),
197 };
198 let count = body[10] as usize;
199 let mut at = 11;
200 for _ in 0..count {
201 if body.len() < at + 8 {
202 break;
203 }
204 let flags = body[at + 3];
205 let cropped = flags & 0x80 != 0;
206 let placement = Placement {
207 object_id: u16::from_be_bytes([body[at], body[at + 1]]),
208 window_id: body[at + 2],
209 x: u32::from(u16::from_be_bytes([body[at + 4], body[at + 5]])),
210 y: u32::from(u16::from_be_bytes([body[at + 6], body[at + 7]])),
211 crop: match cropped && body.len() >= at + 16 {
212 true => Some(Rect {
213 x: u32::from(u16::from_be_bytes([body[at + 8], body[at + 9]])),
214 y: u32::from(u16::from_be_bytes([body[at + 10], body[at + 11]])),
215 width: u32::from(u16::from_be_bytes([body[at + 12], body[at + 13]])),
216 height: u32::from(u16::from_be_bytes([body[at + 14], body[at + 15]])),
217 }),
218 false => None,
219 },
220 };
221 at += if cropped { 16 } else { 8 };
222 composition.objects.push(placement);
223 }
224 self.composition = composition;
225 }
226
227 fn wds(&mut self, body: &[u8]) {
228 let count = body.first().copied().unwrap_or(0) as usize;
229 for i in 0..count {
230 let at = 1 + i * 9;
231 if body.len() < at + 9 {
232 break;
233 }
234 self.windows.insert(
235 body[at],
236 Rect {
237 x: u32::from(u16::from_be_bytes([body[at + 1], body[at + 2]])),
238 y: u32::from(u16::from_be_bytes([body[at + 3], body[at + 4]])),
239 width: u32::from(u16::from_be_bytes([body[at + 5], body[at + 6]])),
240 height: u32::from(u16::from_be_bytes([body[at + 7], body[at + 8]])),
241 },
242 );
243 }
244 }
245
246 fn pds(&mut self, body: &[u8]) {
247 if body.len() < 2 {
248 return;
249 }
250 // A palette segment *updates* the palette it names: entries it does not
251 // mention keep whatever the epoch left there.
252 let palette = self
253 .palettes
254 .entry(body[0])
255 .or_insert_with(|| Box::new([[0, 0, 0, 0]; 256]));
256 for entry in body[2..].chunks_exact(5) {
257 palette[entry[0] as usize] = rgba(entry[1], entry[2], entry[3], entry[4]);
258 }
259 }
260
261 fn ods(&mut self, body: &[u8]) {
262 if body.len() < 4 {
263 return;
264 }
265 let id = u16::from_be_bytes([body[0], body[1]]);
266 let sequence = body[3];
267 if sequence & 0x80 != 0 {
268 // First (or only) segment of the sequence: the dimensions ride here.
269 if body.len() < 11 {
270 return;
271 }
272 let object = Object {
273 width: u32::from(u16::from_be_bytes([body[7], body[8]])),
274 height: u32::from(u16::from_be_bytes([body[9], body[10]])),
275 rle: body[11..].to_vec(),
276 };
277 self.partial = Some((id, object));
278 } else if let Some((pending_id, object)) = self.partial.as_mut()
279 && *pending_id == id
280 {
281 object.rle.extend_from_slice(&body[4..]);
282 }
283 if sequence & 0x40 != 0
284 && let Some((id, object)) = self.partial.take()
285 {
286 self.objects.insert(id, object);
287 }
288 }
289
290 /// The current composition as one RGBA canvas, or `None` when it states no
291 /// canvas at all (a display set seen before any PCS).
292 fn render(&mut self) -> Option<VideoFrame> {
293 let (width, height) = (self.composition.width, self.composition.height);
294 if width == 0 || height == 0 {
295 return None;
296 }
297 let stride = width as usize * 4;
298 let mut canvas = vec![0u8; stride.checked_mul(height as usize)?];
299 let palette = self.palettes.get(&self.composition.palette_id);
300 for placement in &self.composition.objects {
301 let (Some(object), Some(palette)) = (self.objects.get(&placement.object_id), palette)
302 else {
303 continue;
304 };
305 let Some(indices) = decode_rle(&object.rle, object.width, object.height) else {
306 continue;
307 };
308 // A window clips its objects; a crop takes a rectangle out of the
309 // object before it is placed.
310 let window = self.windows.get(&placement.window_id).copied();
311 let crop = placement.crop.unwrap_or(Rect {
312 x: 0,
313 y: 0,
314 width: object.width,
315 height: object.height,
316 });
317 for row in 0..crop.height.min(object.height.saturating_sub(crop.y)) {
318 let target_y = placement.y + row;
319 if target_y >= height {
320 break;
321 }
322 for col in 0..crop.width.min(object.width.saturating_sub(crop.x)) {
323 let target_x = placement.x + col;
324 if target_x >= width {
325 break;
326 }
327 if let Some(w) = window
328 && (target_x < w.x
329 || target_y < w.y
330 || target_x >= w.x + w.width
331 || target_y >= w.y + w.height)
332 {
333 continue;
334 }
335 let index = indices[((crop.y + row) * object.width + crop.x + col) as usize];
336 let colour = palette[index as usize];
337 // Fully transparent palette entries paint nothing, which is
338 // what lets two objects share a window.
339 if colour[3] == 0 {
340 continue;
341 }
342 let at = target_y as usize * stride + target_x as usize * 4;
343 canvas[at..at + 4].copy_from_slice(&colour);
344 }
345 }
346 }
347 VideoFrame::try_new(
348 PixelFormat::Rgba8,
349 width,
350 height,
351 vec![Plane::new(canvas, stride)],
352 )
353 .ok()
354 }
355}
356
357impl Decoder for PgsDecoder {
358 fn codec_parameters(&self) -> &CodecParameters {
359 &self.params
360 }
361
362 fn send_packet(&mut self, packet: &ec_core::Packet) -> Result<()> {
363 self.push(&packet.data)
364 }
365
366 fn receive_frame(&mut self) -> Result<Frame> {
367 match self.take_frame() {
368 Some(frame) => Ok(Frame::Video(frame)),
369 None => Err(Error::NeedMore),
370 }
371 }
372
373 fn flush(&mut self) -> Result<()> {
374 Ok(())
375 }
376
377 fn reset(&mut self) {
378 let params = self.params.clone();
379 *self = PgsDecoder::new();
380 self.params = params;
381 }
382}
383
384/// A PGS decoder as the family's registry hands one out.
385pub fn make_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> {
386 Ok(Box::new(PgsDecoder::new()))
387}
388
389/// One palette entry: BT.601 limited-range Y'CbCr with straight alpha, the way
390/// a disc writes it, into RGBA.
391fn rgba(y: u8, cr: u8, cb: u8, alpha: u8) -> [u8; 4] {
392 let y = 298 * (i32::from(y) - 16);
393 let cb = i32::from(cb) - 128;
394 let cr = i32::from(cr) - 128;
395 let clamp = |v: i32| ((v + 128) >> 8).clamp(0, 255) as u8;
396 [
397 clamp(y + 409 * cr),
398 clamp(y - 100 * cb - 208 * cr),
399 clamp(y + 516 * cb),
400 alpha,
401 ]
402}
403
404/// The run-length coding of §8.2 of the format: a byte is a pixel of that
405/// palette index; a zero byte opens a run whose length and colour follow.
406///
407/// `None` for data that does not describe a `width` × `height` bitmap — a
408/// truncated object, or one whose rows run past their width.
409fn decode_rle(data: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
410 let (width, height) = (width as usize, height as usize);
411 let mut out = vec![0u8; width.checked_mul(height)?];
412 let mut at = 0;
413 let mut x = 0;
414 let mut y = 0;
415 while at < data.len() {
416 let (colour, run) = match data[at] {
417 0 => {
418 let flags = *data.get(at + 1)?;
419 match flags {
420 // A line ends where the encoder says it does, even short.
421 0 => {
422 at += 2;
423 x = 0;
424 y += 1;
425 continue;
426 }
427 // 00 0LLLLLL — L pixels of entry 0.
428 f if f & 0xC0 == 0x00 => {
429 at += 2;
430 (0, usize::from(f & 0x3F))
431 }
432 // 00 01LLLLLL LLLLLLLL — 14-bit run of entry 0.
433 f if f & 0xC0 == 0x40 => {
434 let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?);
435 at += 3;
436 (0, run)
437 }
438 // 00 10LLLLLL CC — L pixels of entry CC.
439 f if f & 0xC0 == 0x80 => {
440 let colour = *data.get(at + 2)?;
441 at += 3;
442 (colour, usize::from(f & 0x3F))
443 }
444 // 00 11LLLLLL LLLLLLLL CC — 14-bit run of entry CC.
445 f => {
446 let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?);
447 let colour = *data.get(at + 3)?;
448 at += 4;
449 (colour, run)
450 }
451 }
452 }
453 colour => {
454 at += 1;
455 (colour, 1)
456 }
457 };
458 if y >= height || x + run > width {
459 return None;
460 }
461 out[y * width + x..y * width + x + run].fill(colour);
462 x += run;
463 }
464 Some(out)
465}
466
467#[cfg(test)]
468mod tests {
469 use super::*;
470
471 /// One `.sup` segment: the framing a Matroska block gets back on the way in.
472 fn segment(kind: u8, body: &[u8]) -> Vec<u8> {
473 let mut out = Vec::with_capacity(HEADER + body.len());
474 out.extend_from_slice(&MAGIC);
475 out.extend_from_slice(&[0; 8]);
476 out.push(kind);
477 out.extend_from_slice(&(body.len() as u16).to_be_bytes());
478 out.extend_from_slice(body);
479 out
480 }
481
482 /// A display set: an 8×2 white-on-transparent object at (2, 1) of a 16×4
483 /// canvas.
484 fn display_set() -> Vec<u8> {
485 let mut pcs = vec![0, 16, 0, 4, 0x10, 0, 0, 0x80, 0, 0, 1];
486 pcs.extend_from_slice(&[0, 0, 0, 0, 0, 2, 0, 1]); // object 0, window 0, at (2,1)
487 let wds = vec![1, 0, 0, 0, 0, 0, 0, 16, 0, 4];
488 // Entry 1 is opaque white, entry 2 opaque black; entry 0 stays clear.
489 let pds = vec![0, 0, 1, 235, 128, 128, 255, 2, 16, 128, 128, 255];
490 // Two rows of 8: a run of 8 of entry 1, then a run of 8 of entry 2.
491 let rle = vec![0x00, 0x88, 0x01, 0x00, 0x00, 0x00, 0x88, 0x02, 0x00, 0x00];
492 let mut ods = vec![0, 0, 0, 0xC0];
493 ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]);
494 ods.extend_from_slice(&[0, 8, 0, 2]);
495 ods.extend_from_slice(&rle);
496 [
497 segment(SEG_PCS, &pcs),
498 segment(SEG_WDS, &wds),
499 segment(SEG_PDS, &pds),
500 segment(SEG_ODS, &ods),
501 segment(SEG_END, &[]),
502 ]
503 .concat()
504 }
505
506 #[test]
507 fn a_display_set_decodes_to_the_canvas_it_composes() {
508 let mut decoder = PgsDecoder::new();
509 decoder.push(&display_set()).unwrap();
510 let frame = decoder.take_frame().expect("one frame per display set");
511 assert_eq!((frame.width, frame.height), (16, 4));
512 assert_eq!(frame.format, PixelFormat::Rgba8);
513 let stride = frame.planes[0].stride;
514 let pixel = |x: usize, y: usize| &frame.planes[0].data[y * stride + x * 4..][..4];
515 // Outside the object: nothing painted at all.
516 assert_eq!(pixel(0, 0), [0, 0, 0, 0]);
517 assert_eq!(pixel(1, 1), [0, 0, 0, 0]);
518 // Row 1 of the object is white, row 2 is black, both opaque.
519 assert_eq!(pixel(2, 1), [255, 255, 255, 255]);
520 assert_eq!(pixel(9, 1), [255, 255, 255, 255]);
521 assert_eq!(pixel(2, 2), [0, 0, 0, 255]);
522 // Past the object's width again.
523 assert_eq!(pixel(10, 1), [0, 0, 0, 0]);
524 assert!(decoder.take_frame().is_none());
525 }
526
527 #[test]
528 fn a_stream_split_anywhere_decodes_the_same() {
529 let bytes = display_set();
530 for split in [1, 7, 13, 20, bytes.len() - 1] {
531 let mut decoder = PgsDecoder::new();
532 decoder.push(&bytes[..split]).unwrap();
533 decoder.push(&bytes[split..]).unwrap();
534 let frame = decoder.take_frame().expect("split framing still decodes");
535 assert_eq!((frame.width, frame.height), (16, 4));
536 }
537 }
538
539 #[test]
540 fn rubbish_never_panics() {
541 // Not segment framing at all.
542 let mut decoder = PgsDecoder::new();
543 assert!(decoder.push(b"not a sup file at all").is_err());
544 // Well-framed segments with torn bodies: dropped, no frame, no panic.
545 let mut decoder = PgsDecoder::new();
546 let torn = [
547 segment(SEG_PCS, &[0, 16, 0, 4]),
548 segment(SEG_ODS, &[0, 0, 0, 0x80, 9, 9, 9]),
549 segment(SEG_PDS, &[0]),
550 segment(SEG_END, &[]),
551 ]
552 .concat();
553 decoder.push(&torn).unwrap();
554 assert!(decoder.take_frame().is_none());
555 }
556
557 #[test]
558 fn run_length_shapes_and_their_refusals() {
559 // Short form, long form, coloured runs, end of line.
560 let data = [0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00];
561 let out = decode_rle(&data, 4, 2).unwrap();
562 assert_eq!(out, [0, 0, 0, 1, 2, 2, 2, 0]);
563 // A run past the row is a refusal, not a wrap.
564 assert!(decode_rle(&[0x00, 0x08, 0x01], 4, 1).is_none());
565 // A truncated run is a refusal too.
566 assert!(decode_rle(&[0x00, 0x80], 4, 1).is_none());
567 }
568
569 #[test]
570 fn palette_entries_are_bt601_limited_range() {
571 // Y=235 is white, Y=16 is black, and alpha rides through untouched.
572 assert_eq!(rgba(235, 128, 128, 255), [255, 255, 255, 255]);
573 assert_eq!(rgba(16, 128, 128, 128), [0, 0, 0, 128]);
574 // A red palette entry: Y=81, Cr=240, Cb=90 in BT.601.
575 let red = rgba(81, 240, 90, 255);
576 assert!(red[0] > 230 && red[1] < 30 && red[2] < 30, "{red:?}");
577 }
578}