forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

lib.rs634 lines, 23.6 KiBHistoryRawDownload
1//! DVD-Video subpictures (VobSub): the other bitmap subtitle of the disc era.
2//!
3//! A subpicture unit (SPU) is `size:u16, control_offset:u16`, a two-field run-length bitmap of
4//! 2-bit pixels, and a chain of control sequences. Each sequence has a delay (units of
5//! 1024/90000 s after the unit's PTS) and commands: forced start, start, stop, the four palette
6//! indices, the four alpha values, the display area, the two field offsets of the bitmap.
7//!
8//! The palette (16 RGB entries) is not in the unit. It comes from the disc's IFO, from the
9//! `.idx` text (`palette: 000000, ffffff, ...`) that Matroska keeps as `CodecPrivate`, or from the
10//! `mp4s` sample entry's `esds`. [`parse_idx`] reads the text form.
11//!
12//! What comes out is the shape `ec-pgs` produces: a straight-alpha RGBA frame the size of the
13//! canvas (the screen, from the idx `size:` line or the caller), transparent where the cue paints
14//! nothing, plus the cue's timing and forced flag ([`Cue`]).
15//!
16//! Also here: [`SpuAssembler`] (an SPU is split over several PES packets in a program stream) and
17//! [`sub_file_cues`] (a standalone `.sub` MPEG-PS read against its `.idx`).
18
19#![forbid(unsafe_code)]
20
21use std::collections::VecDeque;
22
23use ec_core::{
24 CodecId, CodecParameters, Decoder, Error, Frame, PixelFormat, Plane, Result, TimeBase,
25 Timestamp, VideoFrame,
26};
27
28/// Largest canvas side accepted.
29pub const MAX_DIMENSION: u32 = 4096;
30/// Ticks of the SPU delay unit: 1024 periods of the 90 kHz clock.
31pub const DELAY_UNIT_90K: i64 = 1024;
32/// Finished cues kept for [`DvdSubDecoder::take_cue`].
33pub const MAX_PENDING: usize = 64;
34
35/// 16 RGB entries.
36pub type Palette = [[u8; 3]; 16];
37
38/// The DVD default palette ffmpeg's encoder writes (used when a stream has no palette at all).
39pub const DEFAULT_PALETTE: Palette = [
40 [0x00, 0x00, 0x00],
41 [0x00, 0x00, 0xff],
42 [0x00, 0xff, 0x00],
43 [0xff, 0x00, 0x00],
44 [0xff, 0xff, 0x00],
45 [0xff, 0x00, 0xff],
46 [0x00, 0xff, 0xff],
47 [0xff, 0xff, 0xff],
48 [0x80, 0x80, 0x00],
49 [0x80, 0x80, 0xff],
50 [0x80, 0x00, 0x80],
51 [0x80, 0xff, 0x80],
52 [0x00, 0x80, 0x80],
53 [0xff, 0x80, 0x80],
54 [0x55, 0x55, 0x55],
55 [0xaa, 0xaa, 0xaa],
56];
57
58/// What an `.idx` file (or Matroska `CodecPrivate`) says.
59#[derive(Debug, Clone, Default, PartialEq, Eq)]
60pub struct Idx {
61 /// `size: 720x576`.
62 pub size: Option<(u32, u32)>,
63 /// `palette:` line.
64 pub palette: Option<Palette>,
65 /// `id: en, index: 0` pairs.
66 pub languages: Vec<(String, u32)>,
67 /// `timestamp: hh:mm:ss:mmm, filepos: hex` entries, per the stream selected by the last `id:`
68 /// line (index into `languages`). `(stream index, time in ms, byte offset in the .sub)`.
69 pub entries: Vec<(u32, i64, u64)>,
70}
71
72/// Parses the text of an `.idx` file or a Matroska `S_VOBSUB` `CodecPrivate`. Unknown lines are
73/// ignored; this never fails.
74pub fn parse_idx(data: &[u8]) -> Idx {
75 let text = String::from_utf8_lossy(data);
76 let mut idx = Idx::default();
77 let mut current = 0u32;
78 for line in text.lines() {
79 let line = line.trim();
80 let Some((key, value)) = line.split_once(':') else {
81 continue;
82 };
83 let value = value.trim();
84 match key.trim() {
85 "size" => {
86 if let Some((w, h)) = value.split_once('x')
87 && let (Ok(w), Ok(h)) = (w.trim().parse::<u32>(), h.trim().parse::<u32>())
88 && w > 0
89 && h > 0
90 && w <= MAX_DIMENSION
91 && h <= MAX_DIMENSION
92 {
93 idx.size = Some((w, h));
94 }
95 }
96 "palette" => {
97 let mut p = DEFAULT_PALETTE;
98 let mut n = 0;
99 for (i, tok) in value.split(',').take(16).enumerate() {
100 if let Ok(v) = u32::from_str_radix(tok.trim(), 16) {
101 p[i] = [(v >> 16) as u8, (v >> 8) as u8, v as u8];
102 n += 1;
103 }
104 }
105 if n > 0 {
106 idx.palette = Some(p);
107 }
108 }
109 "id" => {
110 let lang = value.split(',').next().unwrap_or("").trim().to_string();
111 let index = value
112 .split("index:")
113 .nth(1)
114 .and_then(|s| s.trim().parse::<u32>().ok())
115 .unwrap_or(idx.languages.len() as u32);
116 current = index;
117 idx.languages.push((lang, index));
118 }
119 "timestamp" => {
120 let (ts, rest) = value.split_once(',').unwrap_or((value, ""));
121 let pos = rest
122 .split_once(':')
123 .and_then(|(_, v)| u64::from_str_radix(v.trim(), 16).ok());
124 let parts: Vec<&str> = ts.trim().split(':').collect();
125 if parts.len() == 4
126 && let Some(pos) = pos
127 {
128 let neg = parts[0].starts_with('-');
129 let n = |s: &str| s.trim_start_matches('-').parse::<i64>().ok();
130 if let (Some(h), Some(m), Some(s), Some(ms)) =
131 (n(parts[0]), n(parts[1]), n(parts[2]), n(parts[3]))
132 {
133 let t = ((h * 60 + m) * 60 + s) * 1000 + ms;
134 idx.entries.push((current, if neg { -t } else { t }, pos));
135 }
136 }
137 }
138 _ => {}
139 }
140 }
141 idx
142}
143
144/// One decoded subpicture.
145#[derive(Debug, Clone)]
146pub struct Cue {
147 /// Straight-alpha RGBA canvas, transparent where nothing is painted.
148 pub frame: VideoFrame,
149 /// The display area on the canvas: x, y, width, height.
150 pub area: (u32, u32, u32, u32),
151 /// Start, in 90 kHz ticks after the unit's PTS.
152 pub start_90k: i64,
153 /// Stop, in 90 kHz ticks after the unit's PTS; `None` when the unit never states a stop
154 /// (shown until the next one).
155 pub end_90k: Option<i64>,
156 /// The forced-display start command (0x00) was used.
157 pub forced: bool,
158}
159
160#[derive(Default)]
161struct Control {
162 start: Option<i64>,
163 stop: Option<i64>,
164 forced: bool,
165 colors: Option<[u8; 4]>,
166 alphas: Option<[u8; 4]>,
167 area: Option<(u32, u32, u32, u32)>, // x1 x2 y1 y2
168 offsets: Option<(usize, usize)>,
169}
170
171fn be16(d: &[u8], at: usize) -> Option<usize> {
172 Some(usize::from(u16::from_be_bytes([*d.get(at)?, *d.get(at + 1)?])))
173}
174
175fn parse_controls(d: &[u8]) -> Result<Control> {
176 let mut c = Control::default();
177 let mut seq = be16(d, 2).ok_or_else(|| Error::corrupt("dvdsub: short unit"))?;
178 let mut hops = 0;
179 loop {
180 hops += 1;
181 if hops > 64 {
182 return Err(Error::corrupt("dvdsub: control chain too long"));
183 }
184 let date = be16(d, seq).ok_or_else(|| Error::corrupt("dvdsub: control past end"))? as i64;
185 let next = be16(d, seq + 2).ok_or_else(|| Error::corrupt("dvdsub: control past end"))?;
186 let mut p = seq + 4;
187 loop {
188 let Some(&cmd) = d.get(p) else {
189 return Err(Error::corrupt("dvdsub: control sequence without end"));
190 };
191 p += 1;
192 match cmd {
193 0x00 => {
194 c.forced = true;
195 c.start.get_or_insert(date * DELAY_UNIT_90K);
196 }
197 0x01 => {
198 c.start.get_or_insert(date * DELAY_UNIT_90K);
199 }
200 0x02 => {
201 c.stop.get_or_insert(date * DELAY_UNIT_90K);
202 }
203 0x03 | 0x04 => {
204 let (a, b) = (
205 *d.get(p).ok_or_else(|| Error::corrupt("dvdsub: short command"))?,
206 *d.get(p + 1).ok_or_else(|| Error::corrupt("dvdsub: short command"))?,
207 );
208 p += 2;
209 // Nibbles, high to low, are entries 3, 2, 1, 0.
210 let v = [b & 15, b >> 4, a & 15, a >> 4];
211 if cmd == 0x03 {
212 c.colors = Some(v);
213 } else {
214 c.alphas = Some(v);
215 }
216 }
217 0x05 => {
218 let b = d.get(p..p + 6).ok_or_else(|| Error::corrupt("dvdsub: short area"))?;
219 p += 6;
220 let x1 = (u32::from(b[0]) << 4) | u32::from(b[1] >> 4);
221 let x2 = (u32::from(b[1] & 15) << 8) | u32::from(b[2]);
222 let y1 = (u32::from(b[3]) << 4) | u32::from(b[4] >> 4);
223 let y2 = (u32::from(b[4] & 15) << 8) | u32::from(b[5]);
224 c.area = Some((x1, x2, y1, y2));
225 }
226 0x06 => {
227 let o1 = be16(d, p).ok_or_else(|| Error::corrupt("dvdsub: short offsets"))?;
228 let o2 = be16(d, p + 2).ok_or_else(|| Error::corrupt("dvdsub: short offsets"))?;
229 p += 4;
230 c.offsets = Some((o1, o2));
231 }
232 0x07 => {
233 // Colour/contrast change: a size-prefixed blob this decoder does not apply.
234 let n = be16(d, p).ok_or_else(|| Error::corrupt("dvdsub: short chg_colcon"))?;
235 if n < 2 {
236 return Err(Error::corrupt("dvdsub: bad chg_colcon size"));
237 }
238 p += n;
239 }
240 0xff => break,
241 _ => return Err(Error::corrupt("dvdsub: unknown control command")),
242 }
243 }
244 if next == seq || next >= d.len() {
245 break;
246 }
247 if next < seq {
248 return Err(Error::corrupt("dvdsub: control chain goes backwards"));
249 }
250 seq = next;
251 }
252 Ok(c)
253}
254
255/// Decodes one field of 2-bit run-length data into rows `first, first+2, ...` of `out`
256/// (`w` x `h` colour indices). Truncated data leaves the rest of the bitmap at index 0.
257fn rle_field(data: &[u8], start: usize, w: usize, h: usize, first: usize, out: &mut [u8]) {
258 let total = data.len() * 2;
259 let mut nib = start * 2;
260 let get = |n: usize| -> u32 {
261 let b = data[n / 2];
262 u32::from(if n.is_multiple_of(2) { b >> 4 } else { b & 15 })
263 };
264 let (mut x, mut y) = (0usize, first);
265 while y < h && nib < total {
266 let mut v = get(nib);
267 nib += 1;
268 let need = |v: &mut u32, nib: &mut usize| -> bool {
269 if *nib >= total {
270 return false;
271 }
272 *v = (*v << 4) | get(*nib);
273 *nib += 1;
274 true
275 };
276 if v < 4 {
277 if !need(&mut v, &mut nib) {
278 return;
279 }
280 if v < 0x10 {
281 if !need(&mut v, &mut nib) {
282 return;
283 }
284 if v < 0x40 && !need(&mut v, &mut nib) {
285 return;
286 }
287 }
288 }
289 let colour = (v & 3) as u8;
290 let mut len = (v >> 2) as usize;
291 if len == 0 {
292 len = w - x;
293 }
294 let len = len.min(w - x);
295 if colour != 0 {
296 let row = &mut out[y * w + x..y * w + x + len];
297 row.fill(colour);
298 }
299 x += len;
300 if x >= w {
301 x = 0;
302 y += 2;
303 nib = nib.div_ceil(2) * 2; // lines start on a byte
304 }
305 }
306}
307
308/// Decodes one subpicture unit against `palette` onto a canvas of `canvas` pixels (grown if the
309/// unit's area lies outside it).
310pub fn decode_spu(data: &[u8], palette: &Palette, canvas: (u32, u32)) -> Result<Cue> {
311 let size = be16(data, 0).ok_or_else(|| Error::corrupt("dvdsub: short unit"))?;
312 // A size of 0 means 64 KiB in some muxers; otherwise the unit may be padded but not short.
313 let data = if size >= 4 && size <= data.len() { &data[..size] } else { data };
314 let c = parse_controls(data)?;
315 let (x1, x2, y1, y2) = c.area.ok_or_else(|| Error::corrupt("dvdsub: no display area"))?;
316 let (o1, o2) = c.offsets.ok_or_else(|| Error::corrupt("dvdsub: no bitmap offsets"))?;
317 if x2 < x1 || y2 < y1 {
318 return Err(Error::corrupt("dvdsub: empty display area"));
319 }
320 let (w, h) = ((x2 - x1 + 1) as usize, (y2 - y1 + 1) as usize);
321 if o1 >= data.len() || o2 >= data.len() {
322 return Err(Error::corrupt("dvdsub: bitmap offset past the unit"));
323 }
324 let mut idx = vec![0u8; w * h];
325 rle_field(data, o1, w, h, 0, &mut idx);
326 rle_field(data, o2, w, h, 1, &mut idx);
327 let colors = c.colors.unwrap_or([0, 1, 2, 3]);
328 let alphas = c.alphas.unwrap_or([0, 15, 15, 15]);
329 let mut table = [[0u8; 4]; 4];
330 for i in 0..4 {
331 let rgb = palette[usize::from(colors[i] & 15)];
332 table[i] = [rgb[0], rgb[1], rgb[2], alphas[i] * 17];
333 }
334 let cw = canvas.0.max(x2 + 1).clamp(1, MAX_DIMENSION);
335 let ch = canvas.1.max(y2 + 1).clamp(1, MAX_DIMENSION);
336 if x2 >= MAX_DIMENSION || y2 >= MAX_DIMENSION {
337 return Err(Error::corrupt("dvdsub: area past the dimension limit"));
338 }
339 let stride = cw as usize * 4;
340 let mut px = vec![0u8; stride * ch as usize];
341 for row in 0..h {
342 let base = (y1 as usize + row) * stride + x1 as usize * 4;
343 for col in 0..w {
344 let t = table[usize::from(idx[row * w + col])];
345 if t[3] != 0 {
346 px[base + col * 4..base + col * 4 + 4].copy_from_slice(&t);
347 }
348 }
349 }
350 let frame = VideoFrame::try_new(PixelFormat::Rgba8, cw, ch, vec![Plane::new(px, stride)])?;
351 Ok(Cue {
352 frame,
353 area: (x1, y1, w as u32, h as u32),
354 start_90k: c.start.unwrap_or(0),
355 end_90k: c.stop,
356 forced: c.forced,
357 })
358}
359
360/// Joins the PES fragments of subpicture units into whole units.
361///
362/// Units are cut from the byte stream by their own size field, so one PES may hold the end of a
363/// unit and the start of the next (ffmpeg's VOB muxer packs sectors that way; a disc pads
364/// instead). PTS values are handed to units in order: the k-th unit gets the k-th PTS seen.
365#[derive(Default)]
366pub struct SpuAssembler {
367 buf: Vec<u8>,
368 pts: VecDeque<i64>,
369}
370
371impl SpuAssembler {
372 /// Drops any partial unit and pending PTS (after a seek or a re-read).
373 pub fn reset(&mut self) {
374 self.buf.clear();
375 self.pts.clear();
376 }
377
378 /// Feeds one PES payload. Returns the units it completed, with their PTS (`None` when the
379 /// stream stated fewer PTS values than units).
380 pub fn push(&mut self, payload: &[u8], pts: Option<i64>) -> Vec<(Vec<u8>, Option<i64>)> {
381 if let Some(p) = pts {
382 if self.pts.len() >= 64 {
383 self.pts.pop_front();
384 }
385 self.pts.push_back(p);
386 }
387 if self.buf.len() + payload.len() > 1 << 20 {
388 self.buf.clear();
389 return Vec::new();
390 }
391 self.buf.extend_from_slice(payload);
392 let mut out = Vec::new();
393 while self.buf.len() >= 2 {
394 let size = usize::from(u16::from_be_bytes([self.buf[0], self.buf[1]]));
395 if size < 4 {
396 // Not a unit (padding, or a torn stream): drop it, wait for the next start.
397 self.buf.clear();
398 break;
399 }
400 if self.buf.len() < size {
401 break;
402 }
403 let rest = self.buf.split_off(size);
404 let unit = std::mem::replace(&mut self.buf, rest);
405 out.push((unit, self.pts.pop_front()));
406 }
407 out
408 }
409}
410
411/// Reads a standalone `.sub` (MPEG program stream, private stream 1 substreams 0x20..0x3f) and
412/// returns, for `stream`, every unit with its PTS in 90 kHz ticks. The `.idx` is not needed to
413/// find the units (they are in the stream), only for the palette.
414pub fn sub_file_units(sub: &[u8], stream: u8) -> Vec<(Vec<u8>, i64)> {
415 let mut out = Vec::new();
416 let mut asm = SpuAssembler::default();
417 let mut i = 0;
418 while i + 4 <= sub.len() {
419 if sub[i] != 0 || sub[i + 1] != 0 || sub[i + 2] != 1 {
420 i += 1;
421 continue;
422 }
423 let id = sub[i + 3];
424 match id {
425 0xBA => {
426 // Pack header: MPEG-2 (0x44 marker) is 14 bytes + stuffing; MPEG-1 is 12.
427 let Some(&b) = sub.get(i + 4) else { break };
428 i += if b >> 6 == 1 {
429 14 + usize::from(sub.get(i + 13).copied().unwrap_or(0) & 7)
430 } else {
431 12
432 };
433 }
434 0xB9 => break,
435 0xBB..=0xEF => {
436 let Some(len) = be16(sub, i + 4) else { break };
437 let end = (i + 6 + len).min(sub.len());
438 if id == 0xBD {
439 let body = &sub[i + 6..end];
440 if body.len() >= 3 {
441 let flags = body[1];
442 let hl = usize::from(body[2]);
443 let mut pts = None;
444 if flags & 0x80 != 0 && body.len() >= 8 {
445 let p = &body[3..8];
446 pts = Some(
447 (i64::from(p[0] >> 1 & 7) << 30)
448 | (i64::from(p[1]) << 22)
449 | (i64::from(p[2] >> 1) << 15)
450 | (i64::from(p[3]) << 7)
451 | i64::from(p[4] >> 1),
452 );
453 }
454 if let Some(&sid) = body.get(3 + hl)
455 && (0x20..=0x3f).contains(&sid)
456 && sid - 0x20 == stream
457 && let Some(payload) = body.get(4 + hl..)
458 {
459 for (unit, p) in asm.push(payload, pts) {
460 out.push((unit, p.unwrap_or(0)));
461 }
462 }
463 }
464 }
465 i = end;
466 }
467 _ => i += 4,
468 }
469 }
470 out
471}
472
473/// A decoder of subpicture units: one packet is one unit.
474pub struct DvdSubDecoder {
475 params: CodecParameters,
476 palette: Palette,
477 canvas: (u32, u32),
478 ready: VecDeque<(Cue, Option<Timestamp>)>,
479}
480
481impl DvdSubDecoder {
482 /// A decoder whose palette and canvas come from `.idx`-style text (`extradata`), or the
483 /// DVD default palette on a 720x576 canvas.
484 pub fn new(extradata: Option<&[u8]>) -> DvdSubDecoder {
485 let idx = extradata.map(parse_idx).unwrap_or_default();
486 let mut params = CodecParameters::new(CodecId::DvdSub);
487 params.extradata = extradata.map(ec_core::Buf::copy_from_slice);
488 DvdSubDecoder {
489 params,
490 palette: idx.palette.unwrap_or(DEFAULT_PALETTE),
491 canvas: idx.size.unwrap_or((720, 576)),
492 ready: VecDeque::new(),
493 }
494 }
495
496 /// Decodes one unit; `pts` is the unit's PTS. The cue's `frame.pts` is `pts` plus the start
497 /// delay when `pts` is given.
498 pub fn push_unit(&mut self, unit: &[u8], pts: Option<Timestamp>) -> Result<()> {
499 let mut cue = decode_spu(unit, &self.palette, self.canvas)?;
500 if let Some(p) = pts {
501 let base = TimeBase::try_new(1, 90_000).map_err(|_| Error::corrupt("dvdsub: time base"))?;
502 let delay = Timestamp::new(cue.start_90k, base)
503 .rescale(p.base, ec_core::Rounding::Nearest);
504 cue.frame.pts = Some(Timestamp::new(p.ticks.saturating_add(delay.ticks), p.base));
505 }
506 if self.ready.len() >= MAX_PENDING {
507 self.ready.pop_front();
508 }
509 self.ready.push_back((cue, pts));
510 Ok(())
511 }
512
513 /// The next decoded cue with its timing, oldest first.
514 pub fn take_cue(&mut self) -> Option<Cue> {
515 self.ready.pop_front().map(|(c, _)| c)
516 }
517}
518
519impl Decoder for DvdSubDecoder {
520 fn codec_parameters(&self) -> &CodecParameters {
521 &self.params
522 }
523
524 fn send_packet(&mut self, packet: &ec_core::Packet) -> Result<()> {
525 let pts = packet.pts.map(|t| Timestamp::new(t, packet.time_base));
526 self.push_unit(&packet.data, pts)
527 }
528
529 fn receive_frame(&mut self) -> Result<Frame> {
530 match self.take_cue() {
531 Some(c) => Ok(Frame::Video(c.frame)),
532 None => Err(Error::NeedMore),
533 }
534 }
535
536 fn flush(&mut self) -> Result<()> {
537 Ok(())
538 }
539
540 fn reset(&mut self) {
541 self.ready.clear();
542 }
543}
544
545/// A DVD subpicture decoder as the family's registry hands one out.
546pub fn make_decoder(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
547 Ok(Box::new(DvdSubDecoder::new(params.extradata.as_deref())))
548}
549
550#[cfg(test)]
551mod tests {
552 use super::*;
553
554 /// A unit: 4x2 area at (10, 20); row 0 = [1,1,2,2], row 1 = [3,3,0,0] (fill to end).
555 fn unit() -> Vec<u8> {
556 // Field 0 (row 0): runs (len 2, colour 1), (len 2, colour 2): nibbles 9, A -> 0x9A.
557 // Field 1 (row 1): (len 2, colour 3) = 0xB, then len 0 (fill) colour 0 = 0x0000 -> 4 nibbles.
558 let rle0 = [0x9A];
559 let rle1 = [0xB0, 0x00, 0x00];
560 let ctrl_at = 4 + rle0.len() + rle1.len();
561 let mut u = vec![0, 0, (ctrl_at >> 8) as u8, ctrl_at as u8];
562 u.extend_from_slice(&rle0);
563 u.extend_from_slice(&rle1);
564 let seq = [
565 0x00, 0x00, (ctrl_at >> 8) as u8, ctrl_at as u8, // date 0, next = itself
566 0x01, // start
567 0x03, 0x32, 0x10, // colours: entries 3,2,1,0 -> palette idx 3,2,1,0
568 0x04, 0xFF, 0xF0, // alpha: 15,15,15,0
569 0x05, 0x00, 0xA0, 0x0D, 0x01, 0x40, 0x15, // x 10..13, y 20..21
570 0x06, 0x00, 0x04, 0x00, 0x05, // field offsets
571 0xFF,
572 ];
573 u.extend_from_slice(&seq);
574 let n = u.len();
575 u[0] = (n >> 8) as u8;
576 u[1] = n as u8;
577 u
578 }
579
580 #[test]
581 fn a_small_unit_decodes_to_its_pixels() {
582 let cue = decode_spu(&unit(), &DEFAULT_PALETTE, (32, 32)).unwrap();
583 assert_eq!(cue.area, (10, 20, 4, 2));
584 let px = &cue.frame.planes[0].data;
585 let at = |x: usize, y: usize| &px[(y * 32 + x) * 4..(y * 32 + x) * 4 + 4];
586 assert_eq!(at(10, 20)[3], 255);
587 assert_eq!(at(10, 20)[..3], DEFAULT_PALETTE[1]);
588 assert_eq!(at(12, 20)[..3], DEFAULT_PALETTE[2]);
589 assert_eq!(at(10, 21)[..3], DEFAULT_PALETTE[3]);
590 assert_eq!(at(12, 21)[3], 0);
591 assert_eq!(at(0, 0)[3], 0);
592 }
593
594 #[test]
595 fn idx_text_is_read() {
596 let i = parse_idx(b"size: 720x480\npalette: 000000, ffffff\nid: de, index: 1\ntimestamp: 00:00:01:500, filepos: 000000800\n");
597 assert_eq!(i.size, Some((720, 480)));
598 assert_eq!(i.palette.unwrap()[1], [255, 255, 255]);
599 assert_eq!(i.languages, vec![("de".to_string(), 1)]);
600 assert_eq!(i.entries, vec![(1, 1500, 0x800)]);
601 }
602
603 #[test]
604 fn rubbish_never_panics() {
605 let mut x = 0x9E37_79B9u32;
606 let mut mutate = unit();
607 for n in 0..4000usize {
608 x = x.wrapping_mul(1664525).wrapping_add(1013904223);
609 let at = (x >> 8) as usize % mutate.len();
610 mutate[at] = (x >> 24) as u8;
611 let _ = decode_spu(&mutate, &DEFAULT_PALETTE, (64, 64));
612 if n % 50 == 0 {
613 mutate = unit();
614 }
615 let junk: Vec<u8> = (0..(n % 200)).map(|i| (i as u32 ^ x) as u8).collect();
616 let _ = decode_spu(&junk, &DEFAULT_PALETTE, (64, 64));
617 let _ = sub_file_units(&junk, 0);
618 }
619 }
620
621 #[test]
622 fn units_split_across_and_packed_within_pes_are_cut_by_size() {
623 let u = unit();
624 let mut stream = u.clone();
625 stream.extend_from_slice(&u);
626 let mut a = SpuAssembler::default();
627 let cut = u.len() + 5;
628 let mut got = a.push(&stream[..cut], Some(100));
629 got.extend(a.push(&stream[cut..], Some(200)));
630 assert_eq!(got.len(), 2);
631 assert_eq!(got[0], (u.clone(), Some(100)));
632 assert_eq!(got[1], (u, Some(200)));
633 }
634}