forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa5441e8Tahinli3 months ago1014 commits

lib.rs588 lines, 21.6 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 Y'CbCr with straight alpha, the way a disc writes
390/// it, into RGBA.
391///
392/// The luma is taken at its own scale — `Y' = 235` comes out 235, not the 255
393/// an expansion of the 16..235 video range would give. That is not a reading of
394/// the Blu-ray spec but a measurement of what every player draws: the oracle's own
395/// `pgssub` decoder, burning `fixtures/subs/pgs-1080p.sup` over black, tops out
396/// at 235 (`scripts/pgs-white-level.sh`), and a subtitle that is brighter than
397/// the one the disc is mastered against is our bug, not the world's.
398fn rgba(y: u8, cr: u8, cb: u8, alpha: u8) -> [u8; 4] {
399 let y = i32::from(y) << 8;
400 let cb = i32::from(cb) - 128;
401 let cr = i32::from(cr) - 128;
402 let clamp = |v: i32| ((v + 128) >> 8).clamp(0, 255) as u8;
403 [
404 clamp(y + 359 * cr),
405 clamp(y - 88 * cb - 183 * cr),
406 clamp(y + 454 * cb),
407 alpha,
408 ]
409}
410
411/// The run-length coding of §8.2 of the format: a byte is a pixel of that
412/// palette index; a zero byte opens a run whose length and colour follow.
413///
414/// `None` for data that does not describe a `width` × `height` bitmap — a
415/// truncated object, or one whose rows run past their width.
416fn decode_rle(data: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
417 let (width, height) = (width as usize, height as usize);
418 let mut out = vec![0u8; width.checked_mul(height)?];
419 let mut at = 0;
420 let mut x = 0;
421 let mut y = 0;
422 while at < data.len() {
423 let (colour, run) = match data[at] {
424 0 => {
425 let flags = *data.get(at + 1)?;
426 match flags {
427 // A line ends where the encoder says it does, even short.
428 0 => {
429 at += 2;
430 x = 0;
431 y += 1;
432 continue;
433 }
434 // 00 0LLLLLL — L pixels of entry 0.
435 f if f & 0xC0 == 0x00 => {
436 at += 2;
437 (0, usize::from(f & 0x3F))
438 }
439 // 00 01LLLLLL LLLLLLLL — 14-bit run of entry 0.
440 f if f & 0xC0 == 0x40 => {
441 let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?);
442 at += 3;
443 (0, run)
444 }
445 // 00 10LLLLLL CC — L pixels of entry CC.
446 f if f & 0xC0 == 0x80 => {
447 let colour = *data.get(at + 2)?;
448 at += 3;
449 (colour, usize::from(f & 0x3F))
450 }
451 // 00 11LLLLLL LLLLLLLL CC — 14-bit run of entry CC.
452 f => {
453 let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?);
454 let colour = *data.get(at + 3)?;
455 at += 4;
456 (colour, run)
457 }
458 }
459 }
460 colour => {
461 at += 1;
462 (colour, 1)
463 }
464 };
465 if y >= height || x + run > width {
466 return None;
467 }
468 out[y * width + x..y * width + x + run].fill(colour);
469 x += run;
470 }
471 Some(out)
472}
473
474#[cfg(test)]
475mod tests {
476 use super::*;
477
478 /// One `.sup` segment: the framing a Matroska block gets back on the way in.
479 fn segment(kind: u8, body: &[u8]) -> Vec<u8> {
480 let mut out = Vec::with_capacity(HEADER + body.len());
481 out.extend_from_slice(&MAGIC);
482 out.extend_from_slice(&[0; 8]);
483 out.push(kind);
484 out.extend_from_slice(&(body.len() as u16).to_be_bytes());
485 out.extend_from_slice(body);
486 out
487 }
488
489 /// A display set: an 8×2 white-on-transparent object at (2, 1) of a 16×4
490 /// canvas.
491 fn display_set() -> Vec<u8> {
492 let mut pcs = vec![0, 16, 0, 4, 0x10, 0, 0, 0x80, 0, 0, 1];
493 pcs.extend_from_slice(&[0, 0, 0, 0, 0, 2, 0, 1]); // object 0, window 0, at (2,1)
494 let wds = vec![1, 0, 0, 0, 0, 0, 0, 16, 0, 4];
495 // Entry 1 is opaque white, entry 2 opaque black; entry 0 stays clear.
496 let pds = vec![0, 0, 1, 235, 128, 128, 255, 2, 16, 128, 128, 255];
497 // Two rows of 8: a run of 8 of entry 1, then a run of 8 of entry 2.
498 let rle = vec![0x00, 0x88, 0x01, 0x00, 0x00, 0x00, 0x88, 0x02, 0x00, 0x00];
499 let mut ods = vec![0, 0, 0, 0xC0];
500 ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]);
501 ods.extend_from_slice(&[0, 8, 0, 2]);
502 ods.extend_from_slice(&rle);
503 [
504 segment(SEG_PCS, &pcs),
505 segment(SEG_WDS, &wds),
506 segment(SEG_PDS, &pds),
507 segment(SEG_ODS, &ods),
508 segment(SEG_END, &[]),
509 ]
510 .concat()
511 }
512
513 #[test]
514 fn a_display_set_decodes_to_the_canvas_it_composes() {
515 let mut decoder = PgsDecoder::new();
516 decoder.push(&display_set()).unwrap();
517 let frame = decoder.take_frame().expect("one frame per display set");
518 assert_eq!((frame.width, frame.height), (16, 4));
519 assert_eq!(frame.format, PixelFormat::Rgba8);
520 let stride = frame.planes[0].stride;
521 let pixel = |x: usize, y: usize| &frame.planes[0].data[y * stride + x * 4..][..4];
522 // Outside the object: nothing painted at all.
523 assert_eq!(pixel(0, 0), [0, 0, 0, 0]);
524 assert_eq!(pixel(1, 1), [0, 0, 0, 0]);
525 // Row 1 of the object is white, row 2 is black, both opaque. White is
526 // the palette's own `Y' = 235`, black its `Y' = 16` — see [`rgba`].
527 assert_eq!(pixel(2, 1), [235, 235, 235, 255]);
528 assert_eq!(pixel(9, 1), [235, 235, 235, 255]);
529 assert_eq!(pixel(2, 2), [16, 16, 16, 255]);
530 // Past the object's width again.
531 assert_eq!(pixel(10, 1), [0, 0, 0, 0]);
532 assert!(decoder.take_frame().is_none());
533 }
534
535 #[test]
536 fn a_stream_split_anywhere_decodes_the_same() {
537 let bytes = display_set();
538 for split in [1, 7, 13, 20, bytes.len() - 1] {
539 let mut decoder = PgsDecoder::new();
540 decoder.push(&bytes[..split]).unwrap();
541 decoder.push(&bytes[split..]).unwrap();
542 let frame = decoder.take_frame().expect("split framing still decodes");
543 assert_eq!((frame.width, frame.height), (16, 4));
544 }
545 }
546
547 #[test]
548 fn rubbish_never_panics() {
549 // Not segment framing at all.
550 let mut decoder = PgsDecoder::new();
551 assert!(decoder.push(b"not a sup file at all").is_err());
552 // Well-framed segments with torn bodies: dropped, no frame, no panic.
553 let mut decoder = PgsDecoder::new();
554 let torn = [
555 segment(SEG_PCS, &[0, 16, 0, 4]),
556 segment(SEG_ODS, &[0, 0, 0, 0x80, 9, 9, 9]),
557 segment(SEG_PDS, &[0]),
558 segment(SEG_END, &[]),
559 ]
560 .concat();
561 decoder.push(&torn).unwrap();
562 assert!(decoder.take_frame().is_none());
563 }
564
565 #[test]
566 fn run_length_shapes_and_their_refusals() {
567 // Short form, long form, coloured runs, end of line.
568 let data = [0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00];
569 let out = decode_rle(&data, 4, 2).unwrap();
570 assert_eq!(out, [0, 0, 0, 1, 2, 2, 2, 0]);
571 // A run past the row is a refusal, not a wrap.
572 assert!(decode_rle(&[0x00, 0x08, 0x01], 4, 1).is_none());
573 // A truncated run is a refusal too.
574 assert!(decode_rle(&[0x00, 0x80], 4, 1).is_none());
575 }
576
577 #[test]
578 fn palette_entries_convert_at_their_own_luma_scale() {
579 // A disc's white and black land where the oracle's PGS decoder puts them —
580 // 235 and 16, not an expansion to 255 and 0 — and alpha rides through
581 // untouched.
582 assert_eq!(rgba(235, 128, 128, 255), [235, 235, 235, 255]);
583 assert_eq!(rgba(16, 128, 128, 128), [16, 16, 16, 128]);
584 // A red palette entry: Y=81, Cr=240, Cb=90 in BT.601.
585 let red = rgba(81, 240, 90, 255);
586 assert!(red[0] > 230 && red[1] < 30 && red[2] < 30, "{red:?}");
587 }
588}