diff --git a/crates/ec-ass/src/lib.rs b/crates/ec-ass/src/lib.rs index cfa54674..38e683a7 100644 --- a/crates/ec-ass/src/lib.rs +++ b/crates/ec-ass/src/lib.rs @@ -42,7 +42,7 @@ pub fn parse(bytes: &[u8]) -> Result { let mut saw_events = false; // `WrapStyle` is read once, when its line is seen; scanning the metadata for // every Dialogue line instead made a long script quadratic. - let mut wrap_style = 0u8; + let mut wrap_style = WrapStyle::Auto; let mut wrap_seen = false; for line in text.split_inclusive('\n') { let trimmed = line.trim(); @@ -70,7 +70,7 @@ pub fn parse(bytes: &[u8]) -> Result { let key = snake_case(key); // The first `WrapStyle` line counts, as it always did. if key == "wrap_style" && !wrap_seen { - wrap_style = value.parse::().unwrap_or(0); + wrap_style = WrapStyle::parse(value); wrap_seen = true; } track.metadata.push((key, value.to_owned())); @@ -210,8 +210,10 @@ fn alignment(code: i32, v4: bool) -> TextAlign { } } +type Rgba = (u8, u8, u8, u8); + /// `&HAABBGGRR&`: BGR with a *transparency* byte, so 0 is opaque. -fn parse_color(value: &str) -> Option<(u8, u8, u8, u8)> { +fn parse_color(value: &str) -> Option { let digits: String = value .trim() .trim_start_matches(['&', 'H', 'h']) @@ -228,7 +230,7 @@ fn parse_color(value: &str) -> Option<(u8, u8, u8, u8)> { )) } -fn dialogue(format: &[String], row: &str, wrap_style: u8) -> Option { +fn dialogue(format: &[String], row: &str, wrap_style: WrapStyle) -> Option { const DEFAULT: &str = "Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text"; let fallback = fields(DEFAULT); let format = if format.is_empty() { &fallback } else { format }; @@ -276,7 +278,7 @@ struct Overrides { } /// One `Text` field into runs, plus whatever positioning its overrides state. -fn body(text: &str, wrap_style: u8) -> (Vec, Option) { +fn body(text: &str, wrap_style: WrapStyle) -> (Vec, Option) { let mut out: Vec = Vec::new(); let mut state = Overrides::default(); let mut position = CuePosition::default(); @@ -445,12 +447,27 @@ fn split_tag(tag: &str) -> Option<(&str, &str)> { } /// Plain text between override blocks, with the three escapes ASS gives it. +#[derive(Clone, Copy, PartialEq, Eq)] +enum WrapStyle { + Auto, + Manual, +} + +impl WrapStyle { + fn parse(value: &str) -> WrapStyle { + match value.parse::() { + Ok(2) => WrapStyle::Manual, + _ => WrapStyle::Auto, + } + } +} + fn push_text( out: &mut Vec, run: &mut String, text: &str, state: &Overrides, - wrap_style: u8, + wrap_style: WrapStyle, ) { let mut chars = text.chars().peekable(); while let Some(c) = chars.next() { @@ -466,7 +483,7 @@ fn push_text( flush(out, run, state); out.push(Segment::LineBreak); } - Some('n') if wrap_style == 2 => { + Some('n') if wrap_style == WrapStyle::Manual => { flush(out, run, state); out.push(Segment::LineBreak); } diff --git a/crates/ec-cc/src/extract.rs b/crates/ec-cc/src/extract.rs index 3c342460..75fb9459 100644 --- a/crates/ec-cc/src/extract.rs +++ b/crates/ec-cc/src/extract.rs @@ -24,6 +24,25 @@ struct PictureCc { triplets: Vec, } +/// The previous reference picture's POC MSB and LSB, for the wrap-around rule. +#[derive(Clone, Copy, Debug, Default)] +struct Poc { + msb: i64, + lsb: i64, +} + +impl Poc { + fn msb_for(&self, lsb: i64, max: i64) -> i64 { + if lsb < self.lsb && self.lsb - lsb >= max / 2 { + self.msb + max + } else if lsb > self.lsb && lsb - self.lsb > max / 2 { + self.msb - max + } else { + self.msb + } + } +} + /// Captions of one presentation-order picture. #[derive(Clone, Debug, PartialEq, Eq)] pub struct TimedCc { @@ -131,6 +150,15 @@ fn for_each_nal(data: &[u8], fmt: NalFormat, mut f: impl FnMut(&[u8])) { } } +/// A parameter set in `avcC` or `hvcC`: a big-endian u16 length, then the NAL. +/// Returns the NAL and the offset just past it. +fn u16_prefixed(data: &[u8], at: usize) -> Option<(&[u8], usize)> { + let len = data.get(at..at + 2)?; + let len = u16::from_be_bytes([len[0], len[1]]) as usize; + let nal = data.get(at + 2..at + 2 + len)?; + Some((nal, at + 2 + len)) +} + fn unescape(p: &[u8]) -> Vec { let mut out = Vec::with_capacity(p.len()); let mut zeros = 0; @@ -185,8 +213,7 @@ pub struct H264Extractor { pending: Vec, stream: CcStream, epoch: u32, - prev_msb: i64, - prev_lsb: i64, + poc: Poc, counter: i64, last_top_field: Option<(u32, u32)>, } @@ -201,8 +228,7 @@ impl H264Extractor { pending: Vec::new(), stream: CcStream::default(), epoch: 0, - prev_msb: 0, - prev_lsb: 0, + poc: Poc::default(), counter: 0, last_top_field: None, } @@ -225,13 +251,11 @@ impl H264Extractor { }; i += 1; for _ in 0..count { - let Some(l) = avcc.get(i..i + 2) else { return }; - let l = u16::from_be_bytes([l[0], l[1]]) as usize; - let Some(n) = avcc.get(i + 2..i + 2 + l) else { + let Some((n, next)) = u16_prefixed(avcc, i) else { return; }; sets.push(n); - i += 2 + l; + i = next; } } for n in sets { @@ -309,23 +333,15 @@ impl H264Extractor { }; if h.unit_type == H264Nal::SliceIdr { self.epoch += 1; - self.prev_msb = 0; - self.prev_lsb = 0; + self.poc = Poc::default(); self.counter = 0; } let order = if sps.pic_order_cnt_type == 0 { let max = 1i64 << sps.log2_max_pic_order_cnt_lsb; let lsb = sh.pic_order_cnt_lsb as i64; - let msb = if lsb < self.prev_lsb && self.prev_lsb - lsb >= max / 2 { - self.prev_msb + max - } else if lsb > self.prev_lsb && lsb - self.prev_lsb > max / 2 { - self.prev_msb - max - } else { - self.prev_msb - }; + let msb = self.poc.msb_for(lsb, max); if h.ref_idc != 0 { - self.prev_msb = msb; - self.prev_lsb = lsb; + self.poc = Poc { msb, lsb }; } msb + lsb } else { @@ -370,8 +386,7 @@ pub struct HevcExtractor { pending: Vec, stream: CcStream, epoch: u32, - prev_msb: i64, - prev_lsb: i64, + poc: Poc, } impl HevcExtractor { @@ -384,8 +399,7 @@ impl HevcExtractor { pending: Vec::new(), stream: CcStream::default(), epoch: 0, - prev_msb: 0, - prev_lsb: 0, + poc: Poc::default(), } } @@ -401,13 +415,11 @@ impl HevcExtractor { let count = u16::from_be_bytes([h[1], h[2]]) as usize; i += 3; for _ in 0..count { - let Some(l) = hvcc.get(i..i + 2) else { return }; - let l = u16::from_be_bytes([l[0], l[1]]) as usize; - let Some(n) = hvcc.get(i + 2..i + 2 + l) else { + let Some((n, next)) = u16_prefixed(hvcc, i) else { return; }; self.nal(n, None); - i += 2 + l; + i = next; } } } @@ -483,25 +495,19 @@ impl HevcExtractor { })(); if idr || bla { self.epoch += 1; - self.prev_msb = 0; - self.prev_lsb = 0; + self.poc = Poc::default(); } let order = match parsed { Some((lsb, bits)) => { let max = 1i64 << bits; let msb = if idr || bla { 0 - } else if lsb < self.prev_lsb && self.prev_lsb - lsb >= max / 2 { - self.prev_msb + max - } else if lsb > self.prev_lsb && lsb - self.prev_lsb > max / 2 { - self.prev_msb - max } else { - self.prev_msb + self.poc.msb_for(lsb, max) }; // Sub-layer non-reference pictures (types 0,2,4,...,14 even) do not update prevTid0. if ty >= 16 || ty % 2 == 1 { - self.prev_msb = msb; - self.prev_lsb = lsb; + self.poc = Poc { msb, lsb }; } msb + lsb } diff --git a/crates/ec-dvbsub/src/lib.rs b/crates/ec-dvbsub/src/lib.rs index f314302c..a768f427 100644 --- a/crates/ec-dvbsub/src/lib.rs +++ b/crates/ec-dvbsub/src/lib.rs @@ -43,14 +43,40 @@ pub struct DvbCue { pub timeout_ms: u32, /// No region is shown: this set clears the screen. pub empty: bool, - /// Page state: 0 normal case, 1 acquisition point, 2 mode change. - pub page_state: u8, + /// Page state: normal case, acquisition point, mode change. + pub page_state: PageState, /// The regions shown: x, y, width, height. pub regions: Vec<(u32, u32, u32, u32)>, } type Rgba = [u8; 4]; +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum PageState { + Normal, + Acquisition, + ModeChange, + Reserved, +} + +impl PageState { + fn from_bits(v: u8) -> PageState { + match v { + 0 => PageState::Normal, + 1 => PageState::Acquisition, + 2 => PageState::ModeChange, + _ => PageState::Reserved, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Depth { + Bits2, + Bits4, + Bits8, +} + struct Clut { c2: [Rgba; 4], c4: [Rgba; 16], @@ -60,7 +86,7 @@ struct Clut { struct Region { width: u32, height: u32, - depth: u8, // bits: 2, 4, 8 + depth: Depth, clut: u8, pix: Vec, objects: Vec<(u16, u32, u32)>, // id, x, y @@ -73,7 +99,7 @@ pub struct DvbSubDecoder { cluts: HashMap, page: Vec<(u8, u32, u32)>, timeout: u8, - page_state: u8, + page_state: PageState, display: (u32, u32), ready: VecDeque, pts: Option, @@ -180,12 +206,12 @@ impl Bits<'_> { /// One pixel-data sub-block's code string, calling `put(count, code)` for each run. Returns the /// bytes the string took (through its end code and byte alignment; all of `d` if truncated). -fn code_string(d: &[u8], depth: u8, mut put: impl FnMut(usize, u8)) -> usize { +fn code_string(d: &[u8], depth: Depth, mut put: impl FnMut(usize, u8)) -> usize { let mut b = Bits { d, pos: 0 }; loop { let r = (|| -> Option> { Some(match depth { - 2 => { + Depth::Bits2 => { let v = b.get(2)?; if v != 0 { Some((1, v as u8)) @@ -209,7 +235,7 @@ fn code_string(d: &[u8], depth: u8, mut put: impl FnMut(usize, u8)) -> usize { } } } - 4 => { + Depth::Bits4 => { let v = b.get(4)?; if v != 0 { Some((1, v as u8)) @@ -234,7 +260,7 @@ fn code_string(d: &[u8], depth: u8, mut put: impl FnMut(usize, u8)) -> usize { } } } - _ => { + Depth::Bits8 => { let v = b.get(8)?; if v != 0 { Some((1, v as u8)) @@ -268,7 +294,7 @@ impl DvbSubDecoder { cluts: HashMap::new(), page: Vec::new(), timeout: 0, - page_state: 0, + page_state: PageState::Normal, display: (720, 576), ready: VecDeque::new(), pts: None, @@ -328,8 +354,8 @@ impl DvbSubDecoder { return Err(Error::corrupt("dvbsub: short page composition")); } self.timeout = b[0]; - self.page_state = (b[1] >> 2) & 3; - if self.page_state != 0 { + self.page_state = PageState::from_bits((b[1] >> 2) & 3); + if self.page_state != PageState::Normal { // Acquisition point / mode change: nothing from before is kept. self.regions.clear(); self.cluts.clear(); @@ -357,16 +383,16 @@ impl DvbSubDecoder { return Err(Error::corrupt("dvbsub: region size out of range")); } let depth = match (b[6] >> 2) & 7 { - 1 => 2, - 2 => 4, - 3 => 8, + 1 => Depth::Bits2, + 2 => Depth::Bits4, + 3 => Depth::Bits8, _ => return Err(Error::corrupt("dvbsub: bad region depth")), }; let clut = b[7]; let bg = match depth { - 2 => (b[9] >> 2) & 3, - 4 => b[9] >> 4, - _ => b[8], + Depth::Bits2 => (b[9] >> 2) & 3, + Depth::Bits4 => b[9] >> 4, + Depth::Bits8 => b[8], }; let mut pix = vec![0u8; (w * h) as usize]; if fill { @@ -486,9 +512,9 @@ impl DvbSubDecoder { } let code = usize::from(r.pix[(row * r.width + col) as usize]); let c = match r.depth { - 2 => clut.c2[code & 3], - 4 => clut.c4[code & 15], - _ => clut.c8[code], + Depth::Bits2 => clut.c2[code & 3], + Depth::Bits4 => clut.c4[code & 15], + Depth::Bits8 => clut.c8[code], }; let o = ty as usize * stride + tx as usize * 4; px[o..o + 4].copy_from_slice(&c); @@ -528,17 +554,17 @@ fn paint_field(region: &mut Region, data: &[u8], x: u32, y: u32, field: u32) { match kind { 0x10..=0x12 => { let src_depth = match kind { - 0x10 => 2, - 0x11 => 4, - _ => 8, + 0x10 => Depth::Bits2, + 0x11 => Depth::Bits4, + _ => Depth::Bits8, }; let depth = region.depth; let (m24c, m28c, m48c) = (m24, m28, m48); let mapped = |c: u8| -> u8 { match (src_depth, depth) { - (2, 4) => m24c[usize::from(c & 3)], - (2, 8) => m28c[usize::from(c & 3)], - (4, 8) => m48c[usize::from(c & 15)], + (Depth::Bits2, Depth::Bits4) => m24c[usize::from(c & 3)], + (Depth::Bits2, Depth::Bits8) => m28c[usize::from(c & 3)], + (Depth::Bits4, Depth::Bits8) => m48c[usize::from(c & 15)], _ => c, } }; diff --git a/crates/ec-image/src/bmp.rs b/crates/ec-image/src/bmp.rs index ba50e0d4..932c320e 100644 --- a/crates/ec-image/src/bmp.rs +++ b/crates/ec-image/src/bmp.rs @@ -26,7 +26,7 @@ struct Header { /// Rows are stored bottom-up unless the height was negative. top_down: bool, bits: u16, - compression: u32, + compression: Compression, /// Palette entries actually present in the file. colours: usize, /// Bytes per palette entry: 4 in a Windows header, 3 in an OS/2 one. @@ -37,13 +37,31 @@ struct Header { masks: [u32; 4], } -const BI_RGB: u32 = 0; -const BI_RLE8: u32 = 1; -const BI_RLE4: u32 = 2; -const BI_BITFIELDS: u32 = 3; -const BI_JPEG: u32 = 4; -const BI_PNG: u32 = 5; -const BI_ALPHABITFIELDS: u32 = 6; +#[derive(Clone, Copy, PartialEq, Eq)] +enum Compression { + Rgb, + Rle8, + Rle4, + Bitfields, + Jpeg, + Png, + AlphaBitfields, +} + +impl Compression { + fn from_raw(raw: u32) -> Option { + Some(match raw { + 0 => Compression::Rgb, + 1 => Compression::Rle8, + 2 => Compression::Rle4, + 3 => Compression::Bitfields, + 4 => Compression::Jpeg, + 5 => Compression::Png, + 6 => Compression::AlphaBitfields, + _ => return None, + }) + } +} fn u16_at(data: &[u8], at: usize) -> Result { data.get(at..at + 2) @@ -72,7 +90,7 @@ fn header(data: &[u8]) -> Result
{ u32::from(u16_at(data, 20)?), false, u16_at(data, 24)?, - BI_RGB, + 0, 0usize, ) } else if (16..40).contains(&info_size) { @@ -84,7 +102,7 @@ fn header(data: &[u8]) -> Result
{ raw_height.unsigned_abs(), raw_height < 0, u16_at(data, 28)?, - BI_RGB, + 0, 0usize, ) } else if info_size >= 40 { @@ -106,16 +124,11 @@ fn header(data: &[u8]) -> Result
{ if !matches!(bits, 1 | 2 | 4 | 8 | 16 | 24 | 32) { return Err(Error::corrupt(format!("BMP: {bits} bits per pixel"))); } - match compression { - // Handled before the header is read; reaching here means the caller - // asked for the fields of a file that has none of them. - BI_JPEG | BI_PNG => {} - BI_RGB | BI_RLE8 | BI_RLE4 | BI_BITFIELDS | BI_ALPHABITFIELDS => {} - other => { - return Err(Error::corrupt(format!("BMP: compression {other}"))); - } - } - if (compression == BI_RLE8 && bits != 8) || (compression == BI_RLE4 && bits != 4) { + let compression = Compression::from_raw(compression) + .ok_or_else(|| Error::corrupt(format!("BMP: compression {compression}")))?; + if (compression == Compression::Rle8 && bits != 8) + || (compression == Compression::Rle4 && bits != 4) + { return Err(Error::corrupt(format!( "BMP: run-length encoding with {bits} bits per pixel" ))); @@ -123,18 +136,21 @@ fn header(data: &[u8]) -> Result
{ // Under BI_BITFIELDS the masks follow the 40-byte header in a v3 file and // live inside a v4/v5 one; either way they start at offset 54. - let bitfields = compression == BI_BITFIELDS || compression == BI_ALPHABITFIELDS; + let bitfields = matches!( + compression, + Compression::Bitfields | Compression::AlphaBitfields + ); let mut masks = [0u32; 4]; let mut palette_at = 14 + info_size; if bitfields && info_size == 40 { for (i, mask) in masks.iter_mut().enumerate().take(3) { *mask = u32_at(data, 54 + i * 4)?; } - if compression == BI_ALPHABITFIELDS { + if compression == Compression::AlphaBitfields { masks[3] = u32_at(data, 66)?; } palette_at += 12 - + if compression == BI_ALPHABITFIELDS { + + if compression == Compression::AlphaBitfields { 4 } else { 0 @@ -216,9 +232,9 @@ fn embedded(data: &[u8]) -> Result> { if !data.starts_with(b"BM") || u32_at(data, 14)? < 40 { return Ok(None); } - let format = match u32_at(data, 30)? { - BI_PNG => ImageFormat::Png, - BI_JPEG => ImageFormat::Jpeg, + let format = match Compression::from_raw(u32_at(data, 30)?) { + Some(Compression::Png) => ImageFormat::Png, + Some(Compression::Jpeg) => ImageFormat::Jpeg, _ => return Ok(None), }; let offset = u32_at(data, 10)? as usize; @@ -289,7 +305,7 @@ pub fn decode(data: &[u8], limits: Limits) -> Result { // Indices first, then colour: every form below produces either palette // indices or direct samples, and the bottom-up flip is the same either way. let has_alpha = header.masks[3] != 0 - || (header.bits == 32 && header.compression == BI_RGB && palette.is_empty()); + || (header.bits == 32 && header.compression == Compression::Rgb && palette.is_empty()); let channels = if has_alpha { 4 } else { 3 }; // The output is checked before anything else sizes from the header; the RLE index buffer // below is width * height, which this bound already covers. @@ -298,7 +314,7 @@ pub fn decode(data: &[u8], limits: Limits) -> Result { let row_of = |y: usize| if header.top_down { y } else { height - 1 - y }; match header.compression { - BI_RLE8 | BI_RLE4 => { + Compression::Rle8 | Compression::Rle4 => { let indices = rle(body, &header)?; for y in 0..height { for x in 0..width { @@ -427,7 +443,7 @@ fn rle(body: &[u8], header: &Header) -> Result> { let mut out = vec![0u8; width * height]; let (mut x, mut y) = (0usize, 0usize); let mut at = 0usize; - let four_bit = header.compression == BI_RLE4; + let four_bit = header.compression == Compression::Rle4; let put = |out: &mut Vec, x: &mut usize, y: usize, index: u8| { if *x < width && y < height { diff --git a/crates/ec-image/src/bytes.rs b/crates/ec-image/src/bytes.rs new file mode 100644 index 00000000..f72f6fd8 --- /dev/null +++ b/crates/ec-image/src/bytes.rs @@ -0,0 +1,17 @@ +pub(crate) fn u16_at(data: &[u8], at: usize, big_endian: bool) -> Option { + let b: [u8; 2] = data.get(at..at + 2)?.try_into().ok()?; + Some(if big_endian { + u16::from_be_bytes(b) + } else { + u16::from_le_bytes(b) + }) +} + +pub(crate) fn u32_at(data: &[u8], at: usize, big_endian: bool) -> Option { + let b: [u8; 4] = data.get(at..at + 4)?.try_into().ok()?; + Some(if big_endian { + u32::from_be_bytes(b) + } else { + u32::from_le_bytes(b) + }) +} diff --git a/crates/ec-image/src/exif.rs b/crates/ec-image/src/exif.rs index 256f0f73..32a40cad 100644 --- a/crates/ec-image/src/exif.rs +++ b/crates/ec-image/src/exif.rs @@ -8,27 +8,13 @@ /// Orientation 1..=8 from a bare TIFF block, or `None` if the block is not a /// readable TIFF or carries no valid orientation entry. pub(crate) fn tiff_orientation(tiff: &[u8]) -> Option { - let little = match tiff.get(..2)? { - b"II" => true, - b"MM" => false, + let big_endian = match tiff.get(..2)? { + b"II" => false, + b"MM" => true, _ => return None, }; - let u16_at = |at: usize| -> Option { - let b = tiff.get(at..at + 2)?; - Some(if little { - u16::from_le_bytes([b[0], b[1]]) - } else { - u16::from_be_bytes([b[0], b[1]]) - }) - }; - let u32_at = |at: usize| -> Option { - let b = tiff.get(at..at + 4)?; - Some(if little { - u32::from_le_bytes([b[0], b[1], b[2], b[3]]) - } else { - u32::from_be_bytes([b[0], b[1], b[2], b[3]]) - }) - }; + let u16_at = |at: usize| crate::bytes::u16_at(tiff, at, big_endian); + let u32_at = |at: usize| crate::bytes::u32_at(tiff, at, big_endian); if u16_at(2)? != 42 { return None; } diff --git a/crates/ec-image/src/lib.rs b/crates/ec-image/src/lib.rs index dca332e3..2858436d 100644 --- a/crates/ec-image/src/lib.rs +++ b/crates/ec-image/src/lib.rs @@ -42,6 +42,7 @@ pub mod png_encode; pub mod transform; pub mod webp; +mod bytes; mod exif; mod probe; diff --git a/crates/ec-image/src/tiff.rs b/crates/ec-image/src/tiff.rs index 23ace55a..222e5097 100644 --- a/crates/ec-image/src/tiff.rs +++ b/crates/ec-image/src/tiff.rs @@ -39,11 +39,13 @@ const TAG_TILE_COUNTS: u16 = 325; const TAG_EXTRA_SAMPLES: u16 = 338; const TAG_SAMPLE_FORMAT: u16 = 339; -const COMPRESSION_NONE: u64 = 1; -const COMPRESSION_LZW: u64 = 5; -const COMPRESSION_DEFLATE: u64 = 8; -const COMPRESSION_PACKBITS: u64 = 32773; -const COMPRESSION_DEFLATE_OLD: u64 = 32946; +#[derive(Clone, Copy, PartialEq, Eq)] +enum Compression { + None, + Lzw, + PackBits, + Deflate, +} /// The endianness the file declared, and the bytes it declared it about. struct Reader<'a> { @@ -53,27 +55,13 @@ struct Reader<'a> { impl<'a> Reader<'a> { fn u16_at(&self, at: usize) -> Result { - let bytes = self - .data - .get(at..at + 2) - .ok_or_else(|| Error::corrupt("TIFF: a field past the end of the file"))?; - Ok(if self.big_endian { - u16::from_be_bytes([bytes[0], bytes[1]]) - } else { - u16::from_le_bytes([bytes[0], bytes[1]]) - }) + crate::bytes::u16_at(self.data, at, self.big_endian) + .ok_or_else(|| Error::corrupt("TIFF: a field past the end of the file")) } fn u32_at(&self, at: usize) -> Result { - let bytes = self - .data - .get(at..at + 4) - .ok_or_else(|| Error::corrupt("TIFF: a field past the end of the file"))?; - Ok(if self.big_endian { - u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) - } else { - u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) - }) + crate::bytes::u32_at(self.data, at, self.big_endian) + .ok_or_else(|| Error::corrupt("TIFF: a field past the end of the file")) } } @@ -153,7 +141,7 @@ struct Layout { bits: Vec, samples: usize, photometric: u64, - compression: u64, + compression: Compression, planar: u64, predictor: u64, /// Strip or tile data offsets, in the order the file lists them. @@ -203,16 +191,15 @@ fn layout(data: &[u8]) -> Result { } let entries = directory(&reader, reader.u32_at(4)? as usize)?; - let compression = first(&entries, TAG_COMPRESSION, COMPRESSION_NONE); - match compression { - COMPRESSION_NONE - | COMPRESSION_LZW - | COMPRESSION_DEFLATE - | COMPRESSION_PACKBITS - | COMPRESSION_DEFLATE_OLD => {} + let raw = first(&entries, TAG_COMPRESSION, 1); + let compression = match raw { + 1 => Compression::None, + 5 => Compression::Lzw, + 32773 => Compression::PackBits, + 8 | 32946 => Compression::Deflate, 2..=4 => { return Err(Error::unsupported( - format!("TIFF: CCITT compression {compression}"), + format!("TIFF: CCITT compression {raw}"), "the fax coders are a separate format with their own \ two-dimensional coding modes", )); @@ -225,7 +212,7 @@ fn layout(data: &[u8]) -> Result { )); } other => return Err(Error::corrupt(format!("TIFF: compression {other}"))), - } + }; let samples = first(&entries, TAG_SAMPLES, 1) as usize; if samples == 0 || samples > 4 { @@ -482,10 +469,10 @@ fn segment(layout: &Layout, data: &[u8], index: usize, expect: usize) -> Result< .get(at..at.saturating_add(len)) .ok_or_else(|| Error::corrupt("TIFF: a strip reaching past the end of the file"))?; Ok(match layout.compression { - COMPRESSION_NONE => body.to_vec(), - COMPRESSION_LZW => lzw(body, expect)?, - COMPRESSION_PACKBITS => packbits(body, expect), - _ => ec_inflate::inflate_zlib(body, expect.saturating_mul(2).max(1024)) + Compression::None => body.to_vec(), + Compression::Lzw => lzw(body, expect)?, + Compression::PackBits => packbits(body, expect), + Compression::Deflate => ec_inflate::inflate_zlib(body, expect.saturating_mul(2).max(1024)) .map_err(|e| Error::corrupt(format!("TIFF: a Deflate strip: {e}")))?, }) } diff --git a/crates/ec-subs/src/ir.rs b/crates/ec-subs/src/ir.rs index f71ee609..91360ba1 100644 --- a/crates/ec-subs/src/ir.rs +++ b/crates/ec-subs/src/ir.rs @@ -7,6 +7,8 @@ //! ASS `\pos` and `\an` — rides beside the runs instead of inside them, because //! it applies to the cue as a whole. +pub type Rgb = (u8, u8, u8); + /// How a karaoke syllable is highlighted, after libass. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum KaraokeMode { @@ -38,7 +40,7 @@ pub enum Segment { /// Children in an explicit colour (``, ASS `\c` / `\1c`). Color { /// Text colour, one byte per channel. - rgb: (u8, u8, u8), + rgb: Rgb, /// What the colour applies to. children: Vec, }, diff --git a/crates/ec-subs/src/markup.rs b/crates/ec-subs/src/markup.rs index 9ee5af6a..22032969 100644 --- a/crates/ec-subs/src/markup.rs +++ b/crates/ec-subs/src/markup.rs @@ -8,7 +8,7 @@ //! with nothing open is dropped, and a `<` that begins no tag at all is the //! character it looks like. -use crate::ir::Segment; +use crate::ir::{Rgb, Segment}; /// Bytes to text, the way a subtitle file has to be read: a UTF-8 or UTF-16 BOM /// consumed, invalid sequences replaced rather than refused, and CRLF (or a @@ -86,70 +86,119 @@ pub fn parse_clock(field: &str) -> Option { /// quadratic to close or the tree too deep to walk. const MAX_NEST: usize = 64; -/// One cue body's markup as runs. `webvtt` turns on the two tags only WebVTT +/// Which markup a cue body is written in. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Dialect { + Srt, + WebVtt, +} + +/// The cue being built: its top-level runs, and the open tags above them, innermost last. +#[derive(Default)] +struct Tree { + root: Vec, + open: Vec<(Open, Vec)>, +} + +impl Tree { + fn top(&mut self) -> &mut Vec { + match self.open.last_mut() { + Some((_, children)) => children, + None => &mut self.root, + } + } + + fn close_top(&mut self) { + let Some((open, children)) = self.open.pop() else { + return; + }; + let parent = self.top(); + match open.name.as_str() { + "b" => parent.push(Segment::Bold(children)), + "i" => parent.push(Segment::Italic(children)), + "u" => parent.push(Segment::Underline(children)), + "s" => parent.push(Segment::Strike(children)), + "v" => parent.push(Segment::Voice { + name: open.annotation, + children, + }), + "c" => parent.push(Segment::Class { + name: open.annotation, + children, + }), + _ => { + if let Some(rgb) = open.color { + parent.push(Segment::Color { rgb, children }); + } else if open.family.is_some() || open.size.is_some() { + parent.push(Segment::Font { + family: open.family, + size: open.size, + children, + }); + } else { + parent.extend(children); + } + } + } + } +} + +/// One cue body's markup as runs. `WebVtt` turns on the two tags only WebVTT /// has — `` and `` — and the inline timestamps that go with them. -pub(crate) fn parse_inline(body: &str, webvtt: bool) -> Vec { - // A stack of open tags, each with the children collected inside it so far; - // the bottom frame is the cue itself and can never be popped. - let mut stack: Vec<(Option, Vec)> = vec![(None, Vec::new())]; +pub(crate) fn parse_inline(body: &str, dialect: Dialect) -> Vec { + let mut tree = Tree::default(); let mut text = String::new(); let mut rest = body; while let Some(at) = rest.find('<') { text.push_str(&unescape(&rest[..at])); let after = &rest[at + 1..]; let Some(end) = after.find('>') else { - // No closing bracket anywhere: the rest of the cue is text. text.push_str(&unescape(&rest[at..])); rest = ""; break; }; let tag = &after[..end]; rest = &after[end + 1..]; - match classify(tag, webvtt) { + match classify(tag, dialect) { Tag::Text => { text.push('<'); text.push_str(&unescape(tag)); text.push('>'); } Tag::Timestamp(offset_us) => { - flush(&mut text, &mut stack); - push(&mut stack, Segment::Timestamp { offset_us }); + flush(&mut text, &mut tree); + tree.top().push(Segment::Timestamp { offset_us }); } Tag::Raw => { - flush(&mut text, &mut stack); - push(&mut stack, Segment::Raw(format!("<{tag}>"))); + flush(&mut text, &mut tree); + tree.top().push(Segment::Raw(format!("<{tag}>"))); } Tag::Open(open) => { - flush(&mut text, &mut stack); - if stack.len() <= MAX_NEST { - stack.push((Some(open), Vec::new())); + flush(&mut text, &mut tree); + if tree.open.len() < MAX_NEST { + tree.open.push((open, Vec::new())); } } Tag::Close(name) => { - flush(&mut text, &mut stack); + flush(&mut text, &mut tree); // Close the innermost frame with that name, and everything // inside it: `` closes both, which is what a browser // does with the same bytes. - let found = stack - .iter() - .rposition(|(open, _)| open.as_ref().is_some_and(|o| o.name == name)); + let found = tree.open.iter().rposition(|(open, _)| open.name == name); if let Some(depth) = found { - while stack.len() > depth { - close_top(&mut stack); + while tree.open.len() > depth { + tree.close_top(); } } } } } text.push_str(&unescape(rest)); - flush(&mut text, &mut stack); - while stack.len() > 1 { - close_top(&mut stack); + flush(&mut text, &mut tree); + while !tree.open.is_empty() { + tree.close_top(); } - stack - .pop() - .map(|(_, children)| children) - .unwrap_or_default() + tree.root } /// An open tag: its name and the arguments the closing wrapper will need. @@ -170,7 +219,7 @@ enum Tag { Text, } -fn classify(tag: &str, webvtt: bool) -> Tag { +fn classify(tag: &str, dialect: Dialect) -> Tag { let trimmed = tag.trim(); if trimmed.is_empty() { return Tag::Text; @@ -181,7 +230,7 @@ fn classify(tag: &str, webvtt: bool) -> Tag { return Tag::Close(name); } // `<00:00:01.500>` is a cue timestamp, not an element. - if webvtt && trimmed.starts_with(|c: char| c.is_ascii_digit()) { + if dialect == Dialect::WebVtt && trimmed.starts_with(|c: char| c.is_ascii_digit()) { return match parse_clock(trimmed) { Some(offset_us) => Tag::Timestamp(offset_us), None => Tag::Text, @@ -211,7 +260,7 @@ fn classify(tag: &str, webvtt: bool) -> Tag { size: attribute(attrs, "size").and_then(|v| v.trim().parse().ok()), annotation: String::new(), }), - "v" | "c" if webvtt => Tag::Open(Open { + "v" | "c" if dialect == Dialect::WebVtt => Tag::Open(Open { annotation: match name.as_str() { "v" => attrs.trim().to_owned(), _ => classes.replace('.', " "), @@ -252,7 +301,7 @@ fn attribute(attrs: &str, name: &str) -> Option { } /// `#rrggbb`, `#rgb`, or one of the sixteen names HTML has always had. -fn parse_color(value: &str) -> Option<(u8, u8, u8)> { +fn parse_color(value: &str) -> Option { let value = value.trim(); if let Some(hex) = value.strip_prefix('#') { let digits: String = hex.chars().take_while(char::is_ascii_hexdigit).collect(); @@ -350,22 +399,17 @@ fn unescape(text: &str) -> String { out } -fn flush(text: &mut String, stack: &mut [(Option, Vec)]) { +fn flush(text: &mut String, tree: &mut Tree) { if !text.is_empty() { let taken = std::mem::take(text); - // A newline inside a cue body is a line break, not whitespace. let mut lines = taken.split('\n'); if let Some(first) = lines.next() && !first.is_empty() { - stack - .last_mut() - .unwrap() - .1 - .push(Segment::Text(first.into())); + tree.top().push(Segment::Text(first.into())); } for line in lines { - let children = &mut stack.last_mut().unwrap().1; + let children = tree.top(); children.push(Segment::LineBreak); if !line.is_empty() { children.push(Segment::Text(line.into())); @@ -374,48 +418,6 @@ fn flush(text: &mut String, stack: &mut [(Option, Vec)]) { } } -fn push(stack: &mut [(Option, Vec)], segment: Segment) { - stack.last_mut().unwrap().1.push(segment); -} - -fn close_top(stack: &mut Vec<(Option, Vec)>) { - let Some((open, children)) = stack.pop() else { - return; - }; - let Some(open) = open else { return }; - let parent = &mut stack.last_mut().unwrap().1; - match open.name.as_str() { - "b" => parent.push(Segment::Bold(children)), - "i" => parent.push(Segment::Italic(children)), - "u" => parent.push(Segment::Underline(children)), - "s" => parent.push(Segment::Strike(children)), - "v" => parent.push(Segment::Voice { - name: open.annotation, - children, - }), - "c" => parent.push(Segment::Class { - name: open.annotation, - children, - }), - // ``: whichever of colour and face/size it stated. One that - // stated neither is a frame with nothing to say, so it is unwrapped - // rather than kept as an empty node. - _ => { - if let Some(rgb) = open.color { - parent.push(Segment::Color { rgb, children }); - } else if open.family.is_some() || open.size.is_some() { - parent.push(Segment::Font { - family: open.family, - size: open.size, - children, - }); - } else { - parent.extend(children); - } - } - } -} - #[cfg(test)] mod tests { use super::*; @@ -446,33 +448,33 @@ mod tests { #[test] fn markup_nests_and_forgives() { - let segments = parse_inline("a b", false); + let segments = parse_inline("a b", Dialect::Srt); assert_eq!(plain_text(&segments), "a b"); assert!(matches!(segments[0], Segment::Italic(_))); assert!(matches!(segments[2], Segment::Bold(_))); // Mismatched close, stray close, and a `<` that is just a `<`. - assert_eq!(plain_text(&parse_inline("xy", false)), "xy"); - assert_eq!(plain_text(&parse_inline("plain", false)), "plain"); - assert_eq!(plain_text(&parse_inline("a < b", false)), "a < b"); + assert_eq!(plain_text(&parse_inline("xy", Dialect::Srt)), "xy"); + assert_eq!(plain_text(&parse_inline("plain", Dialect::Srt)), "plain"); + assert_eq!(plain_text(&parse_inline("a < b", Dialect::Srt)), "a < b"); assert_eq!( - plain_text(&parse_inline("2 < 3 & 4", false)), + plain_text(&parse_inline("2 < 3 & 4", Dialect::Srt)), "2 < 3 & 4" ); } #[test] fn webvtt_only_tags_are_off_for_srt() { - let vtt = parse_inline("hi", true); + let vtt = parse_inline("hi", Dialect::WebVtt); assert!(matches!(vtt[0], Segment::Voice { .. })); assert_eq!(plain_text(&vtt), "hi"); - let srt = parse_inline("hi", false); + let srt = parse_inline("hi", Dialect::Srt); assert_eq!(plain_text(&srt), "hi"); assert!(matches!(srt[0], Segment::Raw(_))); } #[test] fn font_colour_is_read_by_hex_and_by_name() { - let segments = parse_inline("red", false); + let segments = parse_inline("red", Dialect::Srt); assert!(matches!( segments[0], Segment::Color { @@ -480,7 +482,7 @@ mod tests { .. } )); - let named = parse_inline("green", false); + let named = parse_inline("green", Dialect::Srt); assert!(matches!( named[0], Segment::Color { diff --git a/crates/ec-subs/src/srt.rs b/crates/ec-subs/src/srt.rs index 432675ba..6001c996 100644 --- a/crates/ec-subs/src/srt.rs +++ b/crates/ec-subs/src/srt.rs @@ -10,7 +10,7 @@ use ec_core::{Error, Result}; use crate::ir::{SourceFormat, SubtitleCue, SubtitleTrack}; -use crate::markup::{decode, parse_clock, parse_inline}; +use crate::markup::{decode, parse_clock, parse_inline, Dialect}; /// Parse a SubRip document. /// @@ -40,7 +40,7 @@ pub fn parse(bytes: &[u8]) -> Result { end_us: end_us.max(start_us), style_ref: None, positioning: None, - segments: parse_inline(body.trim_end(), false), + segments: parse_inline(body.trim_end(), Dialect::Srt), }); } if track.cues.is_empty() && text.split_whitespace().next().is_some() { diff --git a/crates/ec-subs/src/webvtt.rs b/crates/ec-subs/src/webvtt.rs index 795392e8..673d9c2d 100644 --- a/crates/ec-subs/src/webvtt.rs +++ b/crates/ec-subs/src/webvtt.rs @@ -9,7 +9,7 @@ use ec_core::{Error, Result}; use crate::ir::{CuePosition, SourceFormat, SubtitleCue, SubtitleTrack, TextAlign}; -use crate::markup::{decode, parse_inline}; +use crate::markup::{decode, parse_inline, Dialect}; use crate::srt::timing; /// Parse a WebVTT document. @@ -57,7 +57,7 @@ pub fn parse(bytes: &[u8]) -> Result { end_us: end_us.max(start_us), style_ref: None, positioning: settings(lines[at]), - segments: parse_inline(body.trim_end(), true), + segments: parse_inline(body.trim_end(), Dialect::WebVtt), }); } if track.cues.is_empty() && text.split_whitespace().next().is_some() {