forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

lib.rs771 lines, 29.3 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, VecDeque};
26use std::sync::Arc;
27
28use ec_core::{
29 CodecId, CodecParameters, Decoder, Error, Frame, PixelFormat, Plane, Result, VideoFrame,
30};
31
32/// Palette definition segment.
33pub const SEG_PDS: u8 = 0x14;
34/// Object definition segment: the run-length bitmap itself.
35pub const SEG_ODS: u8 = 0x15;
36/// Presentation composition segment: canvas size and object placement.
37pub const SEG_PCS: u8 = 0x16;
38/// Window definition segment.
39pub const SEG_WDS: u8 = 0x17;
40/// End of display set — the point at which a frame is complete.
41pub const SEG_END: u8 = 0x80;
42
43/// The largest width or height an object or a canvas may state. A disc's canvas is 1920×1080; the
44/// bound is generous, and it keeps the RLE bitmap and the RGBA canvas from being sized by a 16-bit
45/// field (65535×65535 is 17 GB of RGBA).
46pub const MAX_DIMENSION: u32 = 4096;
47
48/// How many finished display sets may wait for [`PgsDecoder::take_frame`] at once. A finished set
49/// is only its composition and the objects it places (the canvas is drawn when it is taken), so
50/// the bound is on a few kilobytes per set, not on a canvas. When the queue is full, [`PgsDecoder::push`]
51/// stops at the next display set and reports how many bytes it took.
52pub const MAX_PENDING_SETS: usize = 8;
53
54/// A palette: 256 straight-alpha RGBA entries.
55type Palette = [[u8; 4]; 256];
56
57/// The magic every `.sup` segment starts with.
58const MAGIC: [u8; 2] = *b"PG";
59/// Bytes before a segment's body: magic, PTS, DTS, type, size.
60const HEADER: usize = 13;
61
62/// A decoder over a `.sup` byte stream.
63///
64/// Feed it whole segments ([`PgsDecoder::push`]) — a partial one is held until
65/// the rest arrives, so a caller may split the stream anywhere — and take a
66/// frame per display set ([`PgsDecoder::take_frame`]).
67pub struct PgsDecoder {
68 params: CodecParameters,
69 /// Bytes not yet forming a whole segment.
70 pending: Vec<u8>,
71 /// Objects by id, decoded run-length data as the stream stated it. Shared with the finished
72 /// display sets that place them.
73 objects: HashMap<u16, Arc<Object>>,
74 /// The object being assembled out of a multi-segment ODS sequence.
75 partial: Option<(u16, Object)>,
76 /// Palettes by id. Shared with finished display sets; a later palette segment copies on write.
77 palettes: HashMap<u8, Arc<Palette>>,
78 /// Windows by id, for clipping.
79 windows: HashMap<u8, Rect>,
80 /// The composition the current display set is building.
81 composition: Composition,
82 /// Display sets finished but not yet taken, oldest first. Capped at [`MAX_PENDING_SETS`].
83 ready: VecDeque<Pending>,
84 /// Bytes of a packet [`Decoder::send_packet`] could not finish because the queue was full.
85 backlog: Vec<u8>,
86 /// An error from a segment of a call that stopped early, reported by the call that consumes
87 /// the rest of its input.
88 deferred: Option<Error>,
89}
90
91/// A finished display set, not yet drawn: the canvas size and everything it places, resolved
92/// against the state at the set's end so that later segments cannot change it.
93struct Pending {
94 width: u32,
95 height: u32,
96 draws: Vec<Draw>,
97}
98
99/// One object placed on a canvas.
100struct Draw {
101 object: Arc<Object>,
102 palette: Arc<Palette>,
103 x: u32,
104 y: u32,
105 window: Option<Rect>,
106 crop: Rect,
107}
108
109#[derive(Clone, Default)]
110struct Object {
111 width: u32,
112 height: u32,
113 rle: Vec<u8>,
114}
115
116#[derive(Clone, Copy, Default)]
117struct Rect {
118 x: u32,
119 y: u32,
120 width: u32,
121 height: u32,
122}
123
124#[derive(Clone, Default)]
125struct Composition {
126 width: u32,
127 height: u32,
128 palette_id: u8,
129 objects: Vec<Placement>,
130}
131
132#[derive(Clone, Copy)]
133struct Placement {
134 object_id: u16,
135 window_id: u8,
136 x: u32,
137 y: u32,
138 crop: Option<Rect>,
139}
140
141impl Default for PgsDecoder {
142 fn default() -> Self {
143 PgsDecoder::new()
144 }
145}
146
147impl PgsDecoder {
148 /// A decoder with no epoch yet: the first display set states everything.
149 pub fn new() -> PgsDecoder {
150 PgsDecoder {
151 params: CodecParameters::new(CodecId::Pgs),
152 pending: Vec::new(),
153 objects: HashMap::new(),
154 partial: None,
155 palettes: HashMap::new(),
156 windows: HashMap::new(),
157 composition: Composition::default(),
158 ready: VecDeque::new(),
159 backlog: Vec::new(),
160 deferred: None,
161 }
162 }
163
164 /// Feed stream bytes. Complete segments are consumed; a partial tail is kept for the next call.
165 ///
166 /// Returns how many bytes of `bytes` were consumed. That is all of them, unless the queue of
167 /// finished display sets is full ([`MAX_PENDING_SETS`]): then the call stops before the next
168 /// display set and the caller takes frames and pushes `bytes[consumed..]` again. A caller that
169 /// drains every frame as it goes never sees a short count.
170 ///
171 /// A segment whose body is nonsense (a palette entry short, an object claiming more pixels
172 /// than its bitmap holds) is dropped and the stream carries on: one torn display set out of
173 /// eleven thousand must not cost the track. A segment whose *size* is past [`MAX_DIMENSION`]
174 /// is refused with [`Error::corrupt`] the same way. The first such error is returned by the
175 /// call that consumes the rest of its input (an `Err` means every byte was consumed). A
176 /// framing error (no `PG` at a segment boundary) stops the call at once.
177 pub fn push(&mut self, bytes: &[u8]) -> Result<usize> {
178 let mut at = 0;
179 let mut first_error = self.deferred.take();
180 loop {
181 if self.pending.len() < HEADER {
182 let take = (HEADER - self.pending.len()).min(bytes.len() - at);
183 self.pending.extend_from_slice(&bytes[at..at + take]);
184 at += take;
185 if self.pending.len() < HEADER {
186 break;
187 }
188 if self.pending[..2] != MAGIC {
189 // Not a segment boundary at all: resynchronising would invent structure,
190 // so this is the one hard error.
191 self.pending.clear();
192 return Err(Error::corrupt("PGS: segment does not start with `PG`"));
193 }
194 }
195 let kind = self.pending[10];
196 if kind == SEG_END && self.ready.len() >= MAX_PENDING_SETS {
197 // The header waits in `pending`; the next call (or the next take_frame) resumes it.
198 break;
199 }
200 let size = u16::from_be_bytes([self.pending[11], self.pending[12]]) as usize;
201 let total = HEADER + size;
202 if self.pending.len() < total {
203 let take = (total - self.pending.len()).min(bytes.len() - at);
204 self.pending.extend_from_slice(&bytes[at..at + take]);
205 at += take;
206 if self.pending.len() < total {
207 break;
208 }
209 }
210 let segment = std::mem::take(&mut self.pending);
211 if let Err(e) = self.segment(kind, &segment[HEADER..total]) {
212 first_error.get_or_insert(e);
213 }
214 }
215 if at < bytes.len() {
216 self.deferred = first_error;
217 return Ok(at);
218 }
219 match first_error {
220 Some(e) => Err(e),
221 None => Ok(at),
222 }
223 }
224
225 /// The next finished display set, drawn, oldest first.
226 pub fn take_frame(&mut self) -> Option<VideoFrame> {
227 let set = self.ready.pop_front()?;
228 let frame = rasterize(&set);
229 self.resume();
230 frame
231 }
232
233 /// How many finished display sets are waiting for [`PgsDecoder::take_frame`]. Never more than
234 /// [`MAX_PENDING_SETS`].
235 pub fn pending_frames(&self) -> usize {
236 self.ready.len()
237 }
238
239 /// Carry on with what a full queue held back: the rest of a packet, or a header waiting on
240 /// its display set.
241 fn resume(&mut self) {
242 let rest = std::mem::take(&mut self.backlog);
243 match self.push(&rest) {
244 Ok(used) => self.backlog = rest[used..].to_vec(),
245 Err(e) => {
246 self.deferred.get_or_insert(e);
247 }
248 }
249 }
250
251 /// One segment against the running state.
252 fn segment(&mut self, kind: u8, body: &[u8]) -> Result<()> {
253 match kind {
254 SEG_PCS => self.pcs(body),
255 SEG_WDS => self.wds(body),
256 SEG_PDS => self.pds(body),
257 SEG_ODS => self.ods(body)?,
258 SEG_END => {
259 if let Some(set) = self.resolve()? {
260 self.ready.push_back(set);
261 }
262 }
263 _ => {}
264 }
265 Ok(())
266 }
267
268 fn pcs(&mut self, body: &[u8]) {
269 if body.len() < 11 {
270 return;
271 }
272 let composition_state = body[7];
273 // Epoch start: nothing from before this point is referenced again.
274 if composition_state & 0x80 != 0 {
275 self.objects.clear();
276 self.palettes.clear();
277 self.windows.clear();
278 self.partial = None;
279 }
280 let mut composition = Composition {
281 width: u32::from(u16::from_be_bytes([body[0], body[1]])),
282 height: u32::from(u16::from_be_bytes([body[2], body[3]])),
283 palette_id: body[9],
284 objects: Vec::new(),
285 };
286 let count = body[10] as usize;
287 let mut at = 11;
288 for _ in 0..count {
289 if body.len() < at + 8 {
290 break;
291 }
292 let flags = body[at + 3];
293 let cropped = flags & 0x80 != 0;
294 let placement = Placement {
295 object_id: u16::from_be_bytes([body[at], body[at + 1]]),
296 window_id: body[at + 2],
297 x: u32::from(u16::from_be_bytes([body[at + 4], body[at + 5]])),
298 y: u32::from(u16::from_be_bytes([body[at + 6], body[at + 7]])),
299 crop: match cropped && body.len() >= at + 16 {
300 true => Some(Rect {
301 x: u32::from(u16::from_be_bytes([body[at + 8], body[at + 9]])),
302 y: u32::from(u16::from_be_bytes([body[at + 10], body[at + 11]])),
303 width: u32::from(u16::from_be_bytes([body[at + 12], body[at + 13]])),
304 height: u32::from(u16::from_be_bytes([body[at + 14], body[at + 15]])),
305 }),
306 false => None,
307 },
308 };
309 at += if cropped { 16 } else { 8 };
310 composition.objects.push(placement);
311 }
312 self.composition = composition;
313 }
314
315 fn wds(&mut self, body: &[u8]) {
316 let count = body.first().copied().unwrap_or(0) as usize;
317 for i in 0..count {
318 let at = 1 + i * 9;
319 if body.len() < at + 9 {
320 break;
321 }
322 self.windows.insert(
323 body[at],
324 Rect {
325 x: u32::from(u16::from_be_bytes([body[at + 1], body[at + 2]])),
326 y: u32::from(u16::from_be_bytes([body[at + 3], body[at + 4]])),
327 width: u32::from(u16::from_be_bytes([body[at + 5], body[at + 6]])),
328 height: u32::from(u16::from_be_bytes([body[at + 7], body[at + 8]])),
329 },
330 );
331 }
332 }
333
334 fn pds(&mut self, body: &[u8]) {
335 if body.len() < 2 {
336 return;
337 }
338 // A palette segment *updates* the palette it names: entries it does not
339 // mention keep whatever the epoch left there.
340 let palette = self
341 .palettes
342 .entry(body[0])
343 .or_insert_with(|| Arc::new([[0, 0, 0, 0]; 256]));
344 let (entries, _) = body[2..].as_chunks::<5>();
345 let palette = Arc::make_mut(palette);
346 for entry in entries {
347 palette[entry[0] as usize] = rgba(entry[1], entry[2], entry[3], entry[4]);
348 }
349 }
350
351 fn ods(&mut self, body: &[u8]) -> Result<()> {
352 if body.len() < 4 {
353 return Ok(());
354 }
355 let id = u16::from_be_bytes([body[0], body[1]]);
356 let sequence = body[3];
357 if sequence & 0x80 != 0 {
358 // First (or only) segment of the sequence: the dimensions ride here.
359 if body.len() < 11 {
360 return Ok(());
361 }
362 let width = u32::from(u16::from_be_bytes([body[7], body[8]]));
363 let height = u32::from(u16::from_be_bytes([body[9], body[10]]));
364 if width > MAX_DIMENSION || height > MAX_DIMENSION {
365 // A partial sequence under this id is abandoned too, so its later fragments
366 // cannot attach to an older object.
367 self.partial = None;
368 return Err(Error::corrupt(format!(
369 "PGS: object {id} is {width}x{height}, past the {MAX_DIMENSION}x{MAX_DIMENSION} limit"
370 )));
371 }
372 let object = Object {
373 width,
374 height,
375 rle: body[11..].to_vec(),
376 };
377 self.partial = Some((id, object));
378 } else if let Some((pending_id, object)) = self.partial.as_mut()
379 && *pending_id == id
380 {
381 object.rle.extend_from_slice(&body[4..]);
382 }
383 if sequence & 0x40 != 0
384 && let Some((id, object)) = self.partial.take()
385 {
386 self.objects.insert(id, Arc::new(object));
387 }
388 Ok(())
389 }
390
391 /// The finished display set the composition describes, resolved against the state now, or
392 /// `None` when it states no canvas at all (a display set seen before any PCS). A canvas past
393 /// [`MAX_DIMENSION`] is refused. Nothing is drawn here: that waits for [`rasterize`].
394 fn resolve(&self) -> Result<Option<Pending>> {
395 let (width, height) = (self.composition.width, self.composition.height);
396 if width == 0 || height == 0 {
397 return Ok(None);
398 }
399 if width > MAX_DIMENSION || height > MAX_DIMENSION {
400 return Err(Error::corrupt(format!(
401 "PGS: canvas {width}x{height} is past the {MAX_DIMENSION}x{MAX_DIMENSION} limit"
402 )));
403 }
404 let mut draws = Vec::new();
405 if let Some(palette) = self.palettes.get(&self.composition.palette_id) {
406 for placement in &self.composition.objects {
407 let Some(object) = self.objects.get(&placement.object_id) else {
408 continue;
409 };
410 // A crop takes a rectangle out of the object before it is placed.
411 let crop = placement.crop.unwrap_or(Rect {
412 x: 0,
413 y: 0,
414 width: object.width,
415 height: object.height,
416 });
417 draws.push(Draw {
418 object: Arc::clone(object),
419 palette: Arc::clone(palette),
420 x: placement.x,
421 y: placement.y,
422 window: self.windows.get(&placement.window_id).copied(),
423 crop,
424 });
425 }
426 }
427 Ok(Some(Pending {
428 width,
429 height,
430 draws,
431 }))
432 }
433}
434
435/// One finished display set as an RGBA canvas. An object whose run-length data does not describe
436/// its bitmap is skipped.
437fn rasterize(set: &Pending) -> Option<VideoFrame> {
438 let (width, height) = (set.width, set.height);
439 let stride = width as usize * 4;
440 let mut canvas = vec![0u8; stride * height as usize];
441 for draw in &set.draws {
442 let object = &draw.object;
443 let Some(indices) = decode_rle(&object.rle, object.width, object.height) else {
444 continue;
445 };
446 let crop = draw.crop;
447 for row in 0..crop.height.min(object.height.saturating_sub(crop.y)) {
448 let target_y = draw.y + row;
449 if target_y >= height {
450 break;
451 }
452 for col in 0..crop.width.min(object.width.saturating_sub(crop.x)) {
453 let target_x = draw.x + col;
454 if target_x >= width {
455 break;
456 }
457 // A window clips its objects.
458 if let Some(w) = draw.window
459 && (target_x < w.x
460 || target_y < w.y
461 || target_x >= w.x + w.width
462 || target_y >= w.y + w.height)
463 {
464 continue;
465 }
466 let index = indices[((crop.y + row) * object.width + crop.x + col) as usize];
467 let colour = draw.palette[index as usize];
468 // Fully transparent palette entries paint nothing, which is what lets two
469 // objects share a window.
470 if colour[3] == 0 {
471 continue;
472 }
473 let at = target_y as usize * stride + target_x as usize * 4;
474 canvas[at..at + 4].copy_from_slice(&colour);
475 }
476 }
477 }
478 VideoFrame::try_new(
479 PixelFormat::Rgba8,
480 width,
481 height,
482 vec![Plane::new(canvas, stride)],
483 )
484 .ok()
485}
486
487impl Decoder for PgsDecoder {
488 fn codec_parameters(&self) -> &CodecParameters {
489 &self.params
490 }
491
492 fn send_packet(&mut self, packet: &ec_core::Packet) -> Result<()> {
493 // A packet the full queue held back is finished first; the caller receives before it sends.
494 if !self.backlog.is_empty() {
495 return Err(Error::NeedMore);
496 }
497 let used = self.push(&packet.data)?;
498 if used < packet.data.len() {
499 self.backlog = packet.data[used..].to_vec();
500 }
501 Ok(())
502 }
503
504 fn receive_frame(&mut self) -> Result<Frame> {
505 match self.take_frame() {
506 Some(frame) => Ok(Frame::Video(frame)),
507 None => Err(Error::NeedMore),
508 }
509 }
510
511 fn flush(&mut self) -> Result<()> {
512 Ok(())
513 }
514
515 fn reset(&mut self) {
516 let params = self.params.clone();
517 *self = PgsDecoder::new();
518 self.params = params;
519 }
520}
521
522/// A PGS decoder as the family's registry hands one out.
523pub fn make_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> {
524 Ok(Box::new(PgsDecoder::new()))
525}
526
527/// One palette entry: BT.601 Y'CbCr with straight alpha, the way a disc writes
528/// it, into RGBA.
529///
530/// The luma is taken at its own scale — `Y' = 235` comes out 235, not the 255
531/// an expansion of the 16..235 video range would give. That is not a reading of
532/// the Blu-ray spec but a measurement of what every player draws: the oracle's own
533/// `pgssub` decoder, burning `fixtures/subs/pgs-1080p.sup` over black, tops out
534/// at 235 (`scripts/pgs-white-level.sh`), and a subtitle that is brighter than
535/// the one the disc is mastered against is our bug, not the world's.
536fn rgba(y: u8, cr: u8, cb: u8, alpha: u8) -> [u8; 4] {
537 let y = i32::from(y) << 8;
538 let cb = i32::from(cb) - 128;
539 let cr = i32::from(cr) - 128;
540 let clamp = |v: i32| ((v + 128) >> 8).clamp(0, 255) as u8;
541 [
542 clamp(y + 359 * cr),
543 clamp(y - 88 * cb - 183 * cr),
544 clamp(y + 454 * cb),
545 alpha,
546 ]
547}
548
549/// The run-length coding of §8.2 of the format: a byte is a pixel of that
550/// palette index; a zero byte opens a run whose length and colour follow.
551///
552/// `None` for data that does not describe a `width` × `height` bitmap — a
553/// truncated object, or one whose rows run past their width.
554fn decode_rle(data: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
555 let (width, height) = (width as usize, height as usize);
556 let mut out = vec![0u8; width.checked_mul(height)?];
557 let mut at = 0;
558 let mut x = 0;
559 let mut y = 0;
560 while at < data.len() {
561 let (colour, run) = match data[at] {
562 0 => {
563 let flags = *data.get(at + 1)?;
564 match flags {
565 // A line ends where the encoder says it does, even short.
566 0 => {
567 at += 2;
568 x = 0;
569 y += 1;
570 continue;
571 }
572 // 00 0LLLLLL — L pixels of entry 0.
573 f if f & 0xC0 == 0x00 => {
574 at += 2;
575 (0, usize::from(f & 0x3F))
576 }
577 // 00 01LLLLLL LLLLLLLL — 14-bit run of entry 0.
578 f if f & 0xC0 == 0x40 => {
579 let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?);
580 at += 3;
581 (0, run)
582 }
583 // 00 10LLLLLL CC — L pixels of entry CC.
584 f if f & 0xC0 == 0x80 => {
585 let colour = *data.get(at + 2)?;
586 at += 3;
587 (colour, usize::from(f & 0x3F))
588 }
589 // 00 11LLLLLL LLLLLLLL CC — 14-bit run of entry CC.
590 f => {
591 let run = (usize::from(f & 0x3F) << 8) | usize::from(*data.get(at + 2)?);
592 let colour = *data.get(at + 3)?;
593 at += 4;
594 (colour, run)
595 }
596 }
597 }
598 colour => {
599 at += 1;
600 (colour, 1)
601 }
602 };
603 if y >= height || x + run > width {
604 return None;
605 }
606 out[y * width + x..y * width + x + run].fill(colour);
607 x += run;
608 }
609 Some(out)
610}
611
612#[cfg(test)]
613mod tests {
614 use super::*;
615
616 /// One `.sup` segment: the framing a Matroska block gets back on the way in.
617 fn segment(kind: u8, body: &[u8]) -> Vec<u8> {
618 let mut out = Vec::with_capacity(HEADER + body.len());
619 out.extend_from_slice(&MAGIC);
620 out.extend_from_slice(&[0; 8]);
621 out.push(kind);
622 out.extend_from_slice(&(body.len() as u16).to_be_bytes());
623 out.extend_from_slice(body);
624 out
625 }
626
627 /// A display set: an 8×2 white-on-transparent object at (2, 1) of a 16×4
628 /// canvas.
629 fn display_set() -> Vec<u8> {
630 let mut pcs = vec![0, 16, 0, 4, 0x10, 0, 0, 0x80, 0, 0, 1];
631 pcs.extend_from_slice(&[0, 0, 0, 0, 0, 2, 0, 1]); // object 0, window 0, at (2,1)
632 let wds = vec![1, 0, 0, 0, 0, 0, 0, 16, 0, 4];
633 // Entry 1 is opaque white, entry 2 opaque black; entry 0 stays clear.
634 let pds = vec![0, 0, 1, 235, 128, 128, 255, 2, 16, 128, 128, 255];
635 // Two rows of 8: a run of 8 of entry 1, then a run of 8 of entry 2.
636 let rle = vec![0x00, 0x88, 0x01, 0x00, 0x00, 0x00, 0x88, 0x02, 0x00, 0x00];
637 let mut ods = vec![0, 0, 0, 0xC0];
638 ods.extend_from_slice(&((rle.len() + 4) as u32).to_be_bytes()[1..]);
639 ods.extend_from_slice(&[0, 8, 0, 2]);
640 ods.extend_from_slice(&rle);
641 [
642 segment(SEG_PCS, &pcs),
643 segment(SEG_WDS, &wds),
644 segment(SEG_PDS, &pds),
645 segment(SEG_ODS, &ods),
646 segment(SEG_END, &[]),
647 ]
648 .concat()
649 }
650
651 #[test]
652 fn a_display_set_decodes_to_the_canvas_it_composes() {
653 let mut decoder = PgsDecoder::new();
654 decoder.push(&display_set()).unwrap();
655 let frame = decoder.take_frame().expect("one frame per display set");
656 assert_eq!((frame.width, frame.height), (16, 4));
657 assert_eq!(frame.format, PixelFormat::Rgba8);
658 let stride = frame.planes[0].stride;
659 let pixel = |x: usize, y: usize| &frame.planes[0].data[y * stride + x * 4..][..4];
660 // Outside the object: nothing painted at all.
661 assert_eq!(pixel(0, 0), [0, 0, 0, 0]);
662 assert_eq!(pixel(1, 1), [0, 0, 0, 0]);
663 // Row 1 of the object is white, row 2 is black, both opaque. White is
664 // the palette's own `Y' = 235`, black its `Y' = 16` — see [`rgba`].
665 assert_eq!(pixel(2, 1), [235, 235, 235, 255]);
666 assert_eq!(pixel(9, 1), [235, 235, 235, 255]);
667 assert_eq!(pixel(2, 2), [16, 16, 16, 255]);
668 // Past the object's width again.
669 assert_eq!(pixel(10, 1), [0, 0, 0, 0]);
670 assert!(decoder.take_frame().is_none());
671 }
672
673 #[test]
674 fn a_stream_split_anywhere_decodes_the_same() {
675 let bytes = display_set();
676 for split in [1, 7, 13, 20, bytes.len() - 1] {
677 let mut decoder = PgsDecoder::new();
678 decoder.push(&bytes[..split]).unwrap();
679 decoder.push(&bytes[split..]).unwrap();
680 let frame = decoder.take_frame().expect("split framing still decodes");
681 assert_eq!((frame.width, frame.height), (16, 4));
682 }
683 }
684
685 #[test]
686 fn rubbish_never_panics() {
687 // Not segment framing at all.
688 let mut decoder = PgsDecoder::new();
689 assert!(decoder.push(b"not a sup file at all").is_err());
690 // Well-framed segments with torn bodies: dropped, no frame, no panic.
691 let mut decoder = PgsDecoder::new();
692 let torn = [
693 segment(SEG_PCS, &[0, 16, 0, 4]),
694 segment(SEG_ODS, &[0, 0, 0, 0x80, 9, 9, 9]),
695 segment(SEG_PDS, &[0]),
696 segment(SEG_END, &[]),
697 ]
698 .concat();
699 decoder.push(&torn).unwrap();
700 assert!(decoder.take_frame().is_none());
701 }
702
703 #[test]
704 fn a_long_stream_in_one_push_keeps_the_queue_bounded() {
705 // 3000 display sets in one call: far more than the queue holds. The call stops when the
706 // queue is full and reports how far it got; draining and pushing the rest finishes it.
707 const SETS: usize = 3000;
708 let one = display_set();
709 let stream = one.repeat(SETS);
710 let mut decoder = PgsDecoder::new();
711 let mut at = 0;
712 let mut max_queued = 0;
713 let mut frames = 0;
714 let first = decoder.push(&stream).unwrap();
715 assert!(first < stream.len(), "a full queue must stop the call");
716 at += first;
717 while at < stream.len() || decoder.pending_frames() > 0 {
718 max_queued = max_queued.max(decoder.pending_frames());
719 while let Some(frame) = decoder.take_frame() {
720 assert_eq!((frame.width, frame.height), (16, 4));
721 frames += 1;
722 }
723 if at < stream.len() {
724 at += decoder.push(&stream[at..]).unwrap();
725 }
726 max_queued = max_queued.max(decoder.pending_frames());
727 }
728 assert!(max_queued <= MAX_PENDING_SETS, "queued {max_queued}");
729 assert_eq!(frames, SETS);
730 }
731
732 #[test]
733 fn a_full_queue_holds_the_last_end_until_a_frame_is_taken() {
734 // One more set than the queue holds. The END that would finish the last set has an empty
735 // body, so its header is the last thing in the call: it waits in the decoder, and taking a
736 // frame finishes it without another push.
737 let stream = display_set().repeat(MAX_PENDING_SETS + 1);
738 let mut decoder = PgsDecoder::new();
739 assert_eq!(decoder.push(&stream).unwrap(), stream.len());
740 assert_eq!(decoder.pending_frames(), MAX_PENDING_SETS);
741 let mut frames = 0;
742 while decoder.take_frame().is_some() {
743 frames += 1;
744 }
745 assert_eq!(frames, MAX_PENDING_SETS + 1);
746 }
747
748 #[test]
749 fn run_length_shapes_and_their_refusals() {
750 // Short form, long form, coloured runs, end of line.
751 let data = [0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x83, 0x02, 0x00, 0x00];
752 let out = decode_rle(&data, 4, 2).unwrap();
753 assert_eq!(out, [0, 0, 0, 1, 2, 2, 2, 0]);
754 // A run past the row is a refusal, not a wrap.
755 assert!(decode_rle(&[0x00, 0x08, 0x01], 4, 1).is_none());
756 // A truncated run is a refusal too.
757 assert!(decode_rle(&[0x00, 0x80], 4, 1).is_none());
758 }
759
760 #[test]
761 fn palette_entries_convert_at_their_own_luma_scale() {
762 // A disc's white and black land where the oracle's PGS decoder puts them —
763 // 235 and 16, not an expansion to 255 and 0 — and alpha rides through
764 // untouched.
765 assert_eq!(rgba(235, 128, 128, 255), [235, 235, 235, 255]);
766 assert_eq!(rgba(16, 128, 128, 128), [16, 16, 16, 128]);
767 // A red palette entry: Y=81, Cr=240, Cb=90 in BT.601.
768 let red = rgba(81, 240, 90, 255);
769 assert!(red[0] > 230 && red[1] < 30 && red[2] < 30, "{red:?}");
770 }
771}