| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | #![forbid(unsafe_code)] |
| 24 | |
| 25 | use std::collections::HashMap; |
| 26 | |
| 27 | use ec_core::{ |
| 28 | CodecId, CodecParameters, Decoder, Error, Frame, PixelFormat, Plane, Result, VideoFrame, |
| 29 | }; |
| 30 | |
| 31 | |
| 32 | pub const SEG_PDS: u8 = 0x14; |
| 33 | |
| 34 | pub const SEG_ODS: u8 = 0x15; |
| 35 | |
| 36 | pub const SEG_PCS: u8 = 0x16; |
| 37 | |
| 38 | pub const SEG_WDS: u8 = 0x17; |
| 39 | |
| 40 | pub const SEG_END: u8 = 0x80; |
| 41 | |
| 42 | |
| 43 | const MAGIC: [u8; 2] = *b"PG"; |
| 44 | |
| 45 | const HEADER: usize = 13; |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | pub struct PgsDecoder { |
| 53 | params: CodecParameters, |
| 54 | |
| 55 | pending: Vec<u8>, |
| 56 | |
| 57 | objects: HashMap<u16, Object>, |
| 58 | |
| 59 | partial: Option<(u16, Object)>, |
| 60 | |
| 61 | palettes: HashMap<u8, Box<[[u8; 4]; 256]>>, |
| 62 | |
| 63 | windows: HashMap<u8, Rect>, |
| 64 | |
| 65 | composition: Composition, |
| 66 | |
| 67 | ready: Vec<VideoFrame>, |
| 68 | } |
| 69 | |
| 70 | #[derive(Clone, Default)] |
| 71 | struct Object { |
| 72 | width: u32, |
| 73 | height: u32, |
| 74 | rle: Vec<u8>, |
| 75 | } |
| 76 | |
| 77 | #[derive(Clone, Copy, Default)] |
| 78 | struct Rect { |
| 79 | x: u32, |
| 80 | y: u32, |
| 81 | width: u32, |
| 82 | height: u32, |
| 83 | } |
| 84 | |
| 85 | #[derive(Clone, Default)] |
| 86 | struct Composition { |
| 87 | width: u32, |
| 88 | height: u32, |
| 89 | palette_id: u8, |
| 90 | objects: Vec<Placement>, |
| 91 | } |
| 92 | |
| 93 | #[derive(Clone, Copy)] |
| 94 | struct Placement { |
| 95 | object_id: u16, |
| 96 | window_id: u8, |
| 97 | x: u32, |
| 98 | y: u32, |
| 99 | crop: Option<Rect>, |
| 100 | } |
| 101 | |
| 102 | impl Default for PgsDecoder { |
| 103 | fn default() -> Self { |
| 104 | PgsDecoder::new() |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | impl PgsDecoder { |
| 109 | |
| 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 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 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 | |
| 140 | |
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 251 | |
| 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 | |
| 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 | |
| 291 | |
| 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 | |
| 309 | |
| 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 | |
| 338 | |
| 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 | |
| 357 | impl 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 | |
| 385 | pub fn make_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> { |
| 386 | Ok(Box::new(PgsDecoder::new())) |
| 387 | } |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | fn 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 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | fn 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 | |
| 428 | 0 => { |
| 429 | at += 2; |
| 430 | x = 0; |
| 431 | y += 1; |
| 432 | continue; |
| 433 | } |
| 434 | |
| 435 | f if f & 0xC0 == 0x00 => { |
| 436 | at += 2; |
| 437 | (0, usize::from(f & 0x3F)) |
| 438 | } |
| 439 | |
| 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 | |
| 446 | f if f & 0xC0 == 0x80 => { |
| 447 | let colour = *data.get(at + 2)?; |
| 448 | at += 3; |
| 449 | (colour, usize::from(f & 0x3F)) |
| 450 | } |
| 451 | |
| 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)] |
| 475 | mod tests { |
| 476 | use super::*; |
| 477 | |
| 478 | |
| 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 | |
| 490 | |
| 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]); |
| 494 | let wds = vec![1, 0, 0, 0, 0, 0, 0, 16, 0, 4]; |
| 495 | |
| 496 | let pds = vec![0, 0, 1, 235, 128, 128, 255, 2, 16, 128, 128, 255]; |
| 497 | |
| 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 | |
| 523 | assert_eq!(pixel(0, 0), [0, 0, 0, 0]); |
| 524 | assert_eq!(pixel(1, 1), [0, 0, 0, 0]); |
| 525 | |
| 526 | |
| 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 | |
| 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 | |
| 550 | let mut decoder = PgsDecoder::new(); |
| 551 | assert!(decoder.push(b"not a sup file at all").is_err()); |
| 552 | |
| 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 | |
| 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 | |
| 572 | assert!(decode_rle(&[0x00, 0x08, 0x01], 4, 1).is_none()); |
| 573 | |
| 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 | |
| 580 | |
| 581 | |
| 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 | |
| 585 | let red = rgba(81, 240, 90, 255); |
| 586 | assert!(red[0] > 230 && red[1] < 30 && red[2] < 30, "{red:?}"); |
| 587 | } |
| 588 | } |