Skip to main content

ob_engine/
smk.rs

1//! Smacker (`SMK2`/`SMK4`) video decoder, written from the public format description:
2//! a header with per-frame sizes and types, four Huffman trees, then per frame an optional
3//! palette update, audio chunks (skipped; Blood's cutscene audio is in separate WAV files)
4//! and a bitstream of 4x4 blocks.
5
6use std::io;
7
8fn invalid(m: &str) -> io::Error {
9    io::Error::new(io::ErrorKind::InvalidData, m.to_string())
10}
11
12/// Least-significant-bit-first bit reader.
13struct Bits<'a> {
14    data: &'a [u8],
15    pos: usize,
16}
17
18impl<'a> Bits<'a> {
19    fn new(data: &'a [u8]) -> Self {
20        Bits { data, pos: 0 }
21    }
22
23    #[inline]
24    fn bit(&mut self) -> u32 {
25        let byte = self.data.get(self.pos >> 3).copied().unwrap_or(0);
26        let b = (byte >> (self.pos & 7)) & 1;
27        self.pos += 1;
28        b as u32
29    }
30
31    fn bits(&mut self, n: u32) -> u32 {
32        let mut v = 0;
33        for i in 0..n {
34            v |= self.bit() << i;
35        }
36        v
37    }
38
39    fn overrun(&self) -> bool {
40        self.pos > self.data.len() * 8
41    }
42}
43
44/// Huffman tree stored as nodes: `Branch(zero, one)` or a leaf index into a value table.
45#[derive(Clone, Copy)]
46enum Node {
47    Branch(u32, u32),
48    Leaf(u32),
49}
50
51/// 8-bit tree used to build the 16-bit trees.
52struct SmallTree {
53    nodes: Vec<Node>,
54    values: Vec<u8>,
55}
56
57impl SmallTree {
58    fn read(br: &mut Bits) -> io::Result<SmallTree> {
59        let mut t = SmallTree {
60            nodes: Vec::new(),
61            values: Vec::new(),
62        };
63        if br.bit() == 0 {
64            return Ok(t); // empty: always 0
65        }
66        t.build(br, 0)?;
67        br.bit(); // terminator
68        Ok(t)
69    }
70
71    fn build(&mut self, br: &mut Bits, depth: u32) -> io::Result<u32> {
72        if depth > 32 || br.overrun() {
73            return Err(invalid("smacker: bad small tree"));
74        }
75        let me = self.nodes.len() as u32;
76        if br.bit() == 1 {
77            self.nodes.push(Node::Branch(0, 0));
78            let a = self.build(br, depth + 1)?;
79            let b = self.build(br, depth + 1)?;
80            self.nodes[me as usize] = Node::Branch(a, b);
81        } else {
82            self.values.push(br.bits(8) as u8);
83            self.nodes.push(Node::Leaf(self.values.len() as u32 - 1));
84        }
85        Ok(me)
86    }
87
88    fn decode(&self, br: &mut Bits) -> u32 {
89        if self.nodes.is_empty() {
90            return 0;
91        }
92        let mut n = 0usize;
93        loop {
94            match self.nodes[n] {
95                Node::Leaf(v) => return self.values[v as usize] as u32,
96                Node::Branch(a, b) => n = if br.bit() == 0 { a } else { b } as usize,
97            }
98        }
99    }
100}
101
102/// 16-bit tree with Smacker's three "recent value" escape leaves.
103struct BigTree {
104    nodes: Vec<Node>,
105    values: Vec<u32>,
106    last: [usize; 3],
107}
108
109impl BigTree {
110    fn read(br: &mut Bits) -> io::Result<BigTree> {
111        let mut t = BigTree {
112            nodes: Vec::new(),
113            values: Vec::new(),
114            last: [0; 3],
115        };
116        if br.bit() == 0 {
117            // Empty tree: every value is 0 and no bits are read.
118            t.values = vec![0; 3];
119            t.last = [0, 1, 2];
120            return Ok(t);
121        }
122        let lo = SmallTree::read(br)?;
123        let hi = SmallTree::read(br)?;
124        let esc = [br.bits(16), br.bits(16), br.bits(16)];
125        let mut last: [Option<usize>; 3] = [None; 3];
126        t.build(br, &lo, &hi, &esc, &mut last, 0)?;
127        br.bit(); // terminator
128        for (i, l) in last.iter().enumerate() {
129            t.last[i] = match l {
130                Some(idx) => *idx,
131                None => {
132                    // No leaf carried this escape: use a spare slot outside the tree.
133                    t.values.push(0);
134                    t.values.len() - 1
135                }
136            };
137        }
138        Ok(t)
139    }
140
141    #[allow(clippy::too_many_arguments)]
142    fn build(
143        &mut self,
144        br: &mut Bits,
145        lo: &SmallTree,
146        hi: &SmallTree,
147        esc: &[u32; 3],
148        last: &mut [Option<usize>; 3],
149        depth: u32,
150    ) -> io::Result<u32> {
151        if depth > 32 || br.overrun() {
152            return Err(invalid("smacker: bad big tree"));
153        }
154        let me = self.nodes.len() as u32;
155        if br.bit() == 1 {
156            self.nodes.push(Node::Branch(0, 0));
157            let a = self.build(br, lo, hi, esc, last, depth + 1)?;
158            let b = self.build(br, lo, hi, esc, last, depth + 1)?;
159            self.nodes[me as usize] = Node::Branch(a, b);
160        } else {
161            let mut v = lo.decode(br) | (hi.decode(br) << 8);
162            let idx = self.values.len();
163            if let Some(k) = esc.iter().position(|&e| e == v) {
164                last[k] = Some(idx);
165                v = 0;
166            }
167            self.values.push(v);
168            self.nodes.push(Node::Leaf(idx as u32));
169        }
170        Ok(me)
171    }
172
173    /// Clears the recent-value cache (done before every frame).
174    fn reset(&mut self) {
175        for &l in &self.last {
176            self.values[l] = 0;
177        }
178    }
179
180    fn decode(&mut self, br: &mut Bits) -> u32 {
181        if self.nodes.is_empty() {
182            return 0;
183        }
184        let mut n = 0usize;
185        let leaf = loop {
186            match self.nodes[n] {
187                Node::Leaf(v) => break v as usize,
188                Node::Branch(a, b) => n = if br.bit() == 0 { a } else { b } as usize,
189            }
190        };
191        let v = self.values[leaf];
192        let [l0, l1, l2] = self.last;
193        if v != self.values[l0] {
194            self.values[l2] = self.values[l1];
195            self.values[l1] = self.values[l0];
196            self.values[l0] = v;
197        }
198        v
199    }
200}
201
202const RING_FRAME: u32 = 1;
203const Y_INTERLACE: u32 = 2;
204const Y_DOUBLE: u32 = 4;
205
206/// An open Smacker video; call [`Smk::next_frame`] to advance and read [`Smk::pixels`].
207pub struct Smk {
208    data: Vec<u8>,
209    pub width: usize,
210    pub height: usize,
211    pub frames: usize,
212    /// Milliseconds per frame.
213    pub frame_ms: f64,
214    flags: u32,
215    v4: bool,
216    sizes: Vec<u32>,
217    types: Vec<u8>,
218    offsets: Vec<usize>,
219    mmap: BigTree,
220    mclr: BigTree,
221    full: BigTree,
222    ty: BigTree,
223    /// Current frame as palette indices, `width * height`.
224    index: Vec<u8>,
225    /// Current palette, 0x00RRGGBB.
226    palette: [u32; 256],
227    current: usize,
228}
229
230const BLOCK_RUNS: [u32; 64] = {
231    let mut t = [0u32; 64];
232    let mut i = 0;
233    while i < 59 {
234        t[i] = i as u32 + 1;
235        i += 1;
236    }
237    t[59] = 128;
238    t[60] = 256;
239    t[61] = 512;
240    t[62] = 1024;
241    t[63] = 2048;
242    t
243};
244
245fn pal6(v: u8) -> u32 {
246    ((v as u32 & 63) * 255 + 31) / 63
247}
248
249impl Smk {
250    pub fn parse(data: Vec<u8>) -> io::Result<Smk> {
251        if data.len() < 104 || !(data.starts_with(b"SMK2") || data.starts_with(b"SMK4")) {
252            return Err(invalid("not a Smacker file"));
253        }
254        let u32_at = |o: usize| u32::from_le_bytes(data[o..o + 4].try_into().unwrap());
255        let width = u32_at(4) as usize;
256        let height = u32_at(8) as usize;
257        let frames = u32_at(12) as usize;
258        let rate = u32_at(16) as i32;
259        let flags = u32_at(20);
260        let trees_size = u32_at(52) as usize;
261        if width == 0 || height == 0 || width > 4096 || height > 4096 || frames == 0 || frames > 100_000 {
262            return Err(invalid("smacker: bad header"));
263        }
264        let frame_ms = match rate {
265            r if r > 0 => r as f64,
266            r if r < 0 => -r as f64 / 100.0,
267            _ => 100.0,
268        };
269        let n = frames + (flags & RING_FRAME) as usize;
270        let mut p = 104;
271        let need = p + n * 5 + trees_size;
272        if data.len() < need {
273            return Err(invalid("smacker: truncated"));
274        }
275        let sizes: Vec<u32> = (0..n).map(|i| u32_at(p + i * 4)).collect();
276        p += n * 4;
277        let types = data[p..p + n].to_vec();
278        p += n;
279        let (mmap, mclr, full, ty) = {
280            let mut br = Bits::new(&data[p..p + trees_size]);
281            (
282                BigTree::read(&mut br)?,
283                BigTree::read(&mut br)?,
284                BigTree::read(&mut br)?,
285                BigTree::read(&mut br)?,
286            )
287        };
288        p += trees_size;
289        let mut offsets = Vec::with_capacity(n);
290        for s in &sizes {
291            offsets.push(p);
292            p += (s & !3) as usize;
293        }
294        if p > data.len() {
295            return Err(invalid("smacker: frame data truncated"));
296        }
297        let v4 = data.starts_with(b"SMK4");
298        Ok(Smk {
299            width,
300            height,
301            frames,
302            frame_ms,
303            flags,
304            v4,
305            sizes,
306            types,
307            offsets,
308            mmap,
309            mclr,
310            full,
311            ty,
312            index: vec![0; width * height],
313            palette: [0; 256],
314            current: 0,
315            data,
316        })
317    }
318
319    /// Height the video is meant to be shown at (doubled/interlaced files are stretched).
320    pub fn display_height(&self) -> usize {
321        if self.flags & (Y_INTERLACE | Y_DOUBLE) != 0 {
322            self.height * 2
323        } else {
324            self.height
325        }
326    }
327
328    /// Decodes the next frame. Returns false after the last one.
329    pub fn next_frame(&mut self) -> io::Result<bool> {
330        if self.current >= self.frames {
331            return Ok(false);
332        }
333        let i = self.current;
334        self.current += 1;
335        let start = self.offsets[i];
336        let end = start + (self.sizes[i] & !3) as usize;
337        let mut p = start;
338        let ft = self.types[i];
339        if ft & 1 != 0 {
340            let len = self.data.get(p).copied().unwrap_or(0) as usize * 4;
341            if len == 0 || p + len > end {
342                return Err(invalid("smacker: bad palette chunk"));
343            }
344            self.update_palette(p + 1, p + len);
345            p += len;
346        }
347        for track in 0..7 {
348            if ft & (2 << track) != 0 {
349                let len = u32::from_le_bytes(self.data[p..p + 4].try_into().unwrap()) as usize;
350                p += len.max(4);
351            }
352        }
353        if p > end {
354            return Err(invalid("smacker: bad audio chunk"));
355        }
356        self.decode_video(p, end);
357        Ok(true)
358    }
359
360    fn update_palette(&mut self, mut p: usize, end: usize) {
361        let old = self.palette;
362        let mut i = 0usize;
363        while i < 256 && p < end {
364            let t = self.data[p];
365            p += 1;
366            if t & 0x80 != 0 {
367                i += (t & 0x7f) as usize + 1; // keep entries
368            } else if t & 0x40 != 0 {
369                let off = self.data.get(p).copied().unwrap_or(0) as usize;
370                p += 1;
371                let n = (t & 0x3f) as usize + 1;
372                for k in 0..n {
373                    if i + k < 256 && off + k < 256 {
374                        self.palette[i + k] = old[off + k];
375                    }
376                }
377                i += n;
378            } else {
379                let (r, g, b) = (
380                    t,
381                    self.data.get(p).copied().unwrap_or(0),
382                    self.data.get(p + 1).copied().unwrap_or(0),
383                );
384                p += 2;
385                self.palette[i] = (pal6(r) << 16) | (pal6(g) << 8) | pal6(b);
386                i += 1;
387            }
388        }
389    }
390
391    fn decode_video(&mut self, p: usize, end: usize) {
392        let data = std::mem::take(&mut self.data);
393        let mut br = Bits::new(&data[p..end.min(data.len())]);
394        for t in [&mut self.mmap, &mut self.mclr, &mut self.full, &mut self.ty] {
395            t.reset();
396        }
397        let (w, h) = (self.width, self.height);
398        let bw = w / 4;
399        let blocks = bw * (h / 4);
400        let mut blk = 0usize;
401        while blk < blocks && !br.overrun() {
402            let v = self.ty.decode(&mut br);
403            let kind = v & 3;
404            let mut run = BLOCK_RUNS[((v >> 2) & 63) as usize] as usize;
405            let arg = v >> 8;
406            let mode = if kind == 1 && self.v4 {
407                if br.bit() == 1 {
408                    1
409                } else if br.bit() == 1 {
410                    2
411                } else {
412                    0
413                }
414            } else {
415                0
416            };
417            while run > 0 && blk < blocks {
418                run -= 1;
419                let x0 = (blk % bw) * 4;
420                let y0 = (blk / bw) * 4;
421                let at = |x: usize, y: usize| (y0 + y) * w + x0 + x;
422                match kind {
423                    0 => {
424                        let clr = self.mclr.decode(&mut br);
425                        let mut map = self.mmap.decode(&mut br);
426                        let (lo, hi) = ((clr & 0xff) as u8, (clr >> 8) as u8);
427                        for y in 0..4 {
428                            for x in 0..4 {
429                                self.index[at(x, y)] = if map & 1 != 0 { hi } else { lo };
430                                map >>= 1;
431                            }
432                        }
433                    }
434                    1 => match mode {
435                        0 => {
436                            for y in 0..4 {
437                                let a = self.full.decode(&mut br);
438                                self.index[at(2, y)] = a as u8;
439                                self.index[at(3, y)] = (a >> 8) as u8;
440                                let b = self.full.decode(&mut br);
441                                self.index[at(0, y)] = b as u8;
442                                self.index[at(1, y)] = (b >> 8) as u8;
443                            }
444                        }
445                        1 => {
446                            for half in 0..2 {
447                                let a = self.full.decode(&mut br);
448                                for y in half * 2..half * 2 + 2 {
449                                    self.index[at(0, y)] = a as u8;
450                                    self.index[at(1, y)] = a as u8;
451                                    self.index[at(2, y)] = (a >> 8) as u8;
452                                    self.index[at(3, y)] = (a >> 8) as u8;
453                                }
454                            }
455                        }
456                        _ => {
457                            for half in 0..2 {
458                                let a = self.full.decode(&mut br);
459                                let b = self.full.decode(&mut br);
460                                for y in half * 2..half * 2 + 2 {
461                                    self.index[at(0, y)] = b as u8;
462                                    self.index[at(1, y)] = (b >> 8) as u8;
463                                    self.index[at(2, y)] = a as u8;
464                                    self.index[at(3, y)] = (a >> 8) as u8;
465                                }
466                            }
467                        }
468                    },
469                    2 => {}
470                    _ => {
471                        let c = arg as u8;
472                        for y in 0..4 {
473                            for x in 0..4 {
474                                self.index[at(x, y)] = c;
475                            }
476                        }
477                    }
478                }
479                blk += 1;
480            }
481        }
482        self.data = data;
483    }
484
485    /// The current frame as 0x00RRGGBB pixels (`width * height`).
486    pub fn pixels(&self) -> Vec<u32> {
487        self.index.iter().map(|&i| self.palette[i as usize]).collect()
488    }
489
490    /// Index of the frame most recently decoded (0-based); `frames` when finished.
491    pub fn position(&self) -> usize {
492        self.current
493    }
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499
500    #[test]
501    fn bit_reader_is_lsb_first() {
502        let mut b = Bits::new(&[0b1010_0101, 0xff]);
503        assert_eq!(b.bit(), 1);
504        assert_eq!(b.bit(), 0);
505        assert_eq!(b.bits(6), 0b101001);
506        assert_eq!(b.bits(4), 0xf);
507    }
508
509    #[test]
510    fn six_bit_palette_scale() {
511        assert_eq!(pal6(0), 0);
512        assert_eq!(pal6(63), 255);
513        assert_eq!(pal6(16), 0x41);
514    }
515
516    #[test]
517    fn rejects_other_files() {
518        assert!(Smk::parse(b"RIFF....".to_vec()).is_err());
519    }
520}