diff --git a/crates/audio/src/vmd.rs b/crates/audio/src/vmd.rs index 137396671..9e45b1a5c 100644 --- a/crates/audio/src/vmd.rs +++ b/crates/audio/src/vmd.rs @@ -25,8 +25,9 @@ //! Not decoded: IMA ADPCM sound (audio flag 0x10) and the external codecs of later Coktel Vision //! files ([`Error::Unsupported`]). //! -//! Input is treated as hostile: a frame yields at most 32 blocks (the width of the silence -//! mask) of at most 65 535 samples a channel, and a block is decoded only if all of it is there. No `unsafe`, no panics. +//! Input is treated as hostile: a block is at most 65 535 samples a channel and is decoded only +//! if all of it is there; a frame with a silence mask yields at most 32 blocks (the width of +//! the mask), any other frame as many whole blocks as its data holds. No `unsafe`, no panics. #![warn(missing_docs)] @@ -61,7 +62,7 @@ pub struct Decoder { channels: usize, sixteen_bit: bool, /// Samples of one block, all channels counted. - block_samples: usize, + block_total: usize, } impl Decoder { @@ -82,12 +83,12 @@ impl Decoder { let length = u16_at(806) as i16; let frame_length = usize::from(length.unsigned_abs()); // old-style stereo counts both channels, new-style one - let (channels, block_samples) = match flags { + let (channels, block_total) = match flags { f if f & 0x8000 != 0 => (2, frame_length & !1), f if f & 0x200 != 0 => (2, frame_length * 2), _ => (1, frame_length), }; - Ok(Decoder { sample_rate: u32::from(u16_at(804)), channels, sixteen_bit: length < 0, block_samples }) + Ok(Decoder { sample_rate: u32::from(u16_at(804)), channels, sixteen_bit: length < 0, block_total }) } /// Samples a second. @@ -107,12 +108,12 @@ impl Decoder { /// Samples of one block for each channel. pub fn block_samples(&self) -> usize { - self.block_samples / self.channels + self.block_total / self.channels } /// Bytes of one block of sound in a frame. pub fn block_bytes(&self) -> usize { - if self.sixteen_bit { (self.block_samples + self.channels).min(self.block_samples * 2) } else { self.block_samples } + if self.sixteen_bit { (self.block_total + self.channels).min(self.block_total * 2) } else { self.block_total } } /// Decode one sound frame: `flags` is the frame's flag byte from its record, `data` the @@ -126,16 +127,16 @@ impl Decoder { /// the order here is the description's; /// - flags 3: one block of silence. /// - /// An empty frame gives no samples. A frame's first block cut short is an error; a part of a - /// block after the last whole one is left out. + /// An empty frame gives no samples. With flags 1, a first block cut short is an error. A part + /// of a block after the last whole one is left out, with flags 1 and 2. /// /// The sound of a file is its sound frames decoded in file order and played end to end from /// the first picture on: see `craft_media::vmd` for how that lines up with the pictures. pub fn decode(&self, flags: u8, data: &[u8]) -> Result, Error> { let mut out = Vec::new(); match flags { - 3 => out.resize(self.block_samples, 0), - _ if data.is_empty() => {} + 3 => out.resize(self.block_total, 0), + 1 | 2 if data.is_empty() => {} 1 => { // one block; a frame that holds more whole blocks plays them all, as in ffmpeg self.block(data, &mut out)?; @@ -154,7 +155,7 @@ impl Decoder { // one block fewer than it says. for i in 0..32 { if mask >> i & 1 == 1 { - out.resize(out.len() + self.block_samples, 0); + out.resize(out.len() + self.block_total, 0); } else if !data.is_empty() && data.len() >= self.block_bytes() { self.block(data, &mut out)?; data = &data[self.block_bytes()..]; diff --git a/crates/audio/tests/vmd.rs b/crates/audio/tests/vmd.rs index c1746d4df..145aafa79 100644 --- a/crates/audio/tests/vmd.rs +++ b/crates/audio/tests/vmd.rs @@ -141,6 +141,10 @@ fn sixteen_bit_steps() { data.extend([1, 0x82].repeat(3)); let d = decoder(-4, 0x200); assert_eq!(d.decode(1, &data).unwrap(), [1000, -1000, 1008, -1016, 1016, -1032, 1024, -1048]); + // a flags 1 frame of several blocks: each block starts from its own first samples + let (first, first_samples) = dpcm_pack(&[100, -100, 300, -50, 200, 0, 1000, 500], 2); + let (second, second_samples) = dpcm_pack(&[-7000, 7000, -6000, 6500, -6100, 6400, -3000, 3000], 2); + assert_eq!(d.decode(1, &[first, second, vec![1, 2, 3]].concat()).unwrap(), [first_samples, second_samples].concat()); // steps past 16 bits stop at the ends let mut data = 30000i16.to_le_bytes().to_vec(); data.extend([0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]); @@ -183,6 +187,7 @@ fn bad_input_is_an_error() { let d = decoder(-20, 0); assert_eq!(d.decode(1, &[0; 20]), Err(Error::Invalid("a block of sound is cut short"))); assert_eq!(d.decode(4, &[0; 21]), Err(Error::Unsupported("unknown sound frame flags"))); + assert_eq!(d.decode(4, &[]), Err(Error::Unsupported("unknown sound frame flags"))); // in the file API's error: unsupported stays unsupported, the rest is malformed input assert!(matches!(AudioError::from(Error::Unsupported("x")), AudioError::Unsupported(_))); assert!(matches!(AudioError::from(Error::Invalid("x")), AudioError::Malformed(_))); diff --git a/crates/media/README.md b/crates/media/README.md index e827a3d09..8e5799ec4 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -817,7 +817,7 @@ let (num, den) = file.frame_rate(); // pictures a second, as a fraction for (i, frame) in file.frames.iter().enumerate() { let data = file.read_frame(&bytes, i)?; // one frame's data, read on demand match frame.kind { - FrameKind::Video { new_palette, .. } => { /* file.picture_rect(frame), craft_video::vmd */ } + FrameKind::Video { new_palette, .. } => { /* file.picture_rect(i), craft_video::vmd */ } FrameKind::Audio { flags } => { /* craft_audio::vmd */ } FrameKind::Other(_) => {} } @@ -838,9 +838,9 @@ for (i, frame) in file.frames.iter().enumerate() { `CodecId::VmdAudio` and the 816-byte header as `extradata`, which is what `craft_video::vmd::Decoder::new` and `craft_audio::vmd::Decoder::new` take. `header_bytes()` is the same header. -- `picture_rect(frame)` places a video frame's update in the picture. Frame coordinates are - screen coordinates; the first frame as large as the picture gives the picture's position - (`origin()`), as ffmpeg was seen to do. +- `picture_rect(index)` places a video frame's update in the picture. Frame coordinates are + screen coordinates; a frame as large as the picture that is not at the screen's corner gives + the picture's position from then on, as ffmpeg was seen to do. Gaps: only the 816-byte header is read. The later Coktel Vision revisions with a longer header or one without a palette are refused (`Error::NotVmd`). Files with 16-bit, 24-bit or Indeo 3 diff --git a/crates/media/src/vmd/mod.rs b/crates/media/src/vmd/mod.rs index 054a43052..f671e49f1 100644 --- a/crates/media/src/vmd/mod.rs +++ b/crates/media/src/vmd/mod.rs @@ -195,7 +195,8 @@ impl Header { return Err(Error::NotVmd); } let flags = u16_at(16); - // a sample rate of 0 is no sound either: ffmpeg goes by the rate alone + // the flag is the description's rule. A sample rate of 0 is no sound either: ffmpeg goes + // by the rate alone, and also plays a file that has a rate without the flag let audio = (flags & 0x1000 != 0 && u16_at(804) != 0).then(|| { let length = u16_at(806) as i16; let audio_flags = u16_at(810); @@ -280,7 +281,8 @@ pub struct VmdFile { /// The frames, block after block. pub frames: Vec, raw_header: Vec, - origin: (u16, u16), + /// For each frame, the picture's screen position when the frame is decoded. + origins: Vec<(u16, u16)>, } /// Open a VMD file: read the header and the table of contents. @@ -324,17 +326,22 @@ pub fn open(src: &S) -> Result { offset += u64::from(size); } } - // the picture's place on the screen: see `picture_rect` - let origin = frames + // the picture's place on the screen as each frame finds it: see `picture_rect` + let mut origin = (0, 0); + let origins = frames .iter() - .find_map(|f| match f.kind { - FrameKind::Video { left, top, right, bottom, .. } => (right.checked_sub(left).and_then(|w| w.checked_add(1)) == Some(header.width) - && bottom.checked_sub(top).and_then(|h| h.checked_add(1)) == Some(header.height)) - .then_some((left, top)), - _ => None, + .map(|f| { + if let FrameKind::Video { left, top, right, bottom, .. } = f.kind { + let full = right.checked_sub(left).and_then(|w| w.checked_add(1)) == Some(header.width) + && bottom.checked_sub(top).and_then(|h| h.checked_add(1)) == Some(header.height); + if full && f.size > 0 && (left, top) != (0, 0) { + origin = (left, top); + } + } + origin }) - .unwrap_or((0, 0)); - Ok(VmdFile { header, frames, raw_header: raw.to_vec(), origin }) + .collect(); + Ok(VmdFile { header, frames, raw_header: raw.to_vec(), origins }) } impl VmdFile { @@ -361,32 +368,27 @@ impl VmdFile { /// one without plays 10 pictures a second. pub fn frame_rate(&self) -> (u32, u32) { match &self.header.audio { - Some(a) if a.sample_rate > 0 && a.block_samples() > 0 => (u32::from(a.sample_rate), a.block_samples()), + Some(a) if a.block_samples() > 0 => (u32::from(a.sample_rate), a.block_samples()), _ => (10, 1), } } - /// The screen position `(left, top)` that video frame coordinates are measured from: see - /// [`VmdFile::picture_rect`]. - pub fn origin(&self) -> (u16, u16) { - self.origin - } - - /// Where a video frame's update lies in the picture: `(left, top, right, bottom)` with the + /// Where the video frame `index` updates the picture: `(left, top, right, bottom)` with the /// last column and row included, or `None` for a frame that is not video or lies outside the /// picture. /// /// Frame coordinates are screen coordinates, and a picture need not sit at the screen's - /// corner. The description does not say where the corner comes from. This does what ffmpeg - /// was seen to do: the first video frame that is exactly as large as the picture gives the - /// picture's position ([`VmdFile::origin`]), which is taken off every frame; a file without - /// such a frame has its picture at the corner. The header's own position fields are not - /// used. - pub fn picture_rect(&self, frame: &Frame) -> Option<(u16, u16, u16, u16)> { - let FrameKind::Video { left, top, right, bottom, .. } = frame.kind else { return None }; + /// corner. The description does not say where the picture's position comes from. This does + /// what ffmpeg was seen to do: the picture starts at the corner, and a video frame that has + /// data, is exactly as large as the picture and is not at the corner moves it there for that + /// frame and those after it. The position is taken off the frame's coordinates. The header's + /// own position fields are not used. + pub fn picture_rect(&self, index: usize) -> Option<(u16, u16, u16, u16)> { + let FrameKind::Video { left, top, right, bottom, .. } = self.frames.get(index)?.kind else { return None }; let h = &self.header; - let (left, right) = (left.checked_sub(self.origin.0)?, right.checked_sub(self.origin.0)?); - let (top, bottom) = (top.checked_sub(self.origin.1)?, bottom.checked_sub(self.origin.1)?); + let (x, y) = *self.origins.get(index)?; + let (left, right) = (left.checked_sub(x)?, right.checked_sub(x)?); + let (top, bottom) = (top.checked_sub(y)?, bottom.checked_sub(y)?); (left <= right && top <= bottom && right < h.width && bottom < h.height).then_some((left, top, right, bottom)) } diff --git a/crates/media/src/vmd/tests.rs b/crates/media/src/vmd/tests.rs index eb4b52bd3..88db37cdb 100644 --- a/crates/media/src/vmd/tests.rs +++ b/crates/media/src/vmd/tests.rs @@ -96,27 +96,43 @@ fn other_picture_formats_are_not_vmd_video() { assert_eq!(params(|d| d[24..28].copy_from_slice(b"iv32")).0, VideoFormat::Indeo3); } -/// The cases ffmpeg was checked on: the first frame as large as the picture places it. +/// The cases ffmpeg was checked on. The picture is 20x10 and every frame has data unless said. #[test] -fn picture_rect_takes_off_the_picture_position() { - let rects = |header_origin: (u16, u16), frames: &[[u16; 4]]| { +fn picture_rect_follows_the_picture_position() { + let rects = |header_origin: (u16, u16), frames: &[([u16; 4], usize)]| { let mut spec = Spec::new(20, 10); (spec.left, spec.top) = header_origin; - let blocks: Vec<_> = frames.iter().map(|&rect| vec![F::video(rect, false, vec![])]).collect(); + let blocks: Vec<_> = frames.iter().map(|&(rect, size)| vec![F::video(rect, false, vec![2; size])]).collect(); let f = open(&build(&spec, &blocks)).unwrap(); - (f.origin(), f.frames.iter().map(|fr| f.picture_rect(fr)).collect::>()) + (0..f.frames.len()).map(|i| f.picture_rect(i)).collect::>() }; + let at = |l, t, r, b| Some((l, t, r, b)); // a picture at the screen's corner, whatever the header says - assert_eq!(rects((10, 5), &[[0, 0, 19, 9], [12, 6, 18, 9]]), ((0, 0), vec![Some((0, 0, 19, 9)), Some((12, 6, 18, 9))])); - // a picture at (3, 2): frames left of or above it, or past its far edges, are outside + assert_eq!(rects((10, 5), &[([0, 0, 19, 9], 1), ([12, 6, 18, 9], 1)]), [at(0, 0, 19, 9), at(12, 6, 18, 9)]); + // a frame as large as the picture moves it; frames before that keep the corner + assert_eq!(rects((10, 5), &[([0, 0, 5, 5], 1), ([10, 5, 29, 14], 1), ([10, 5, 12, 7], 1)]), [at(0, 0, 5, 5), at(0, 0, 19, 9), at(0, 0, 2, 2)]); assert_eq!( - rects((0, 0), &[[3, 2, 22, 11], [3, 2, 5, 5], [0, 0, 5, 5], [3, 2, 23, 11], [3, 2, 22, 12]]), - ((3, 2), vec![Some((0, 0, 19, 9)), Some((0, 0, 2, 3)), None, None, None]) + rects((0, 0), &[([0, 0, 9, 4], 1), ([2, 2, 3, 3], 1), ([6, 4, 25, 13], 1), ([6, 4, 8, 6], 1)]), + [at(0, 0, 9, 4), at(2, 2, 3, 3), at(0, 0, 19, 9), at(0, 0, 2, 2)] + ); + // a frame without data does not move it + assert_eq!(rects((0, 0), &[([3, 2, 22, 11], 0), ([3, 2, 5, 5], 1), ([0, 0, 2, 2], 1)]), [None, at(3, 2, 5, 5), at(0, 0, 2, 2)]); + // once moved, a full frame at the corner is outside; one elsewhere moves the picture again + assert_eq!( + rects((0, 0), &[([0, 0, 19, 9], 1), ([3, 2, 22, 11], 1), ([0, 0, 19, 9], 1), ([3, 2, 5, 5], 1)]), + [at(0, 0, 19, 9), at(0, 0, 19, 9), None, at(0, 0, 2, 3)] + ); + assert_eq!( + rects((0, 0), &[([3, 2, 22, 11], 1), ([5, 5, 24, 14], 1), ([5, 5, 7, 7], 1), ([3, 0, 22, 9], 1), ([3, 2, 5, 5], 1)]), + [at(0, 0, 19, 9), at(0, 0, 19, 9), at(0, 0, 2, 2), at(0, 0, 19, 9), at(0, 2, 2, 5)] + ); + // as wide as the picture but not as high is an ordinary frame + assert_eq!(rects((0, 0), &[([3, 2, 22, 8], 1), ([3, 2, 5, 5], 1)]), [None, at(3, 2, 5, 5)]); + // inverted and oversized frames are outside + assert_eq!( + rects((0, 0), &[([2, 0, 5, 0], 1), ([5, 0, 4, 0], 1), ([0, 1, 0, 0], 1), ([0, 0, 20, 9], 1), ([0, 0, 19, 10], 1)]), + [at(2, 0, 5, 0), None, None, None, None] ); - // the placing frame need not be the first - assert_eq!(rects((0, 0), &[[4, 3, 5, 4], [4, 3, 23, 12]]), ((4, 3), vec![Some((0, 0, 1, 1)), Some((0, 0, 19, 9))])); - // no frame as large as the picture: the corner; inverted and oversized frames are outside - assert_eq!(rects((7, 7), &[[2, 0, 5, 0], [5, 0, 4, 0], [0, 1, 0, 0], [0, 0, 20, 9]]), ((0, 0), vec![Some((2, 0, 5, 0)), None, None, None])); } #[test] @@ -168,8 +184,8 @@ fn hostile_input_never_panics() { for k in [0, n / 2, n.saturating_sub(1), n, usize::MAX] { let _ = f.read_frame(d, k); } - for fr in &f.frames { - let _ = f.picture_rect(fr); + for k in [0, n / 2, n.saturating_sub(1), n, usize::MAX] { + let _ = f.picture_rect(k); } let _ = (f.frame_rate(), f.video_params(), f.audio_params()); } diff --git a/crates/video/src/vmd/mod.rs b/crates/video/src/vmd/mod.rs index a25b3a603..f171bef10 100644 --- a/crates/video/src/vmd/mod.rs +++ b/crates/video/src/vmd/mod.rs @@ -25,7 +25,7 @@ //! let mut decoder = Decoder::new(file.header_bytes())?; //! for (i, frame) in file.frames.iter().enumerate() { //! let FrameKind::Video { new_palette, .. } = frame.kind else { continue }; -//! let Some(rect) = file.picture_rect(frame) else { continue }; +//! let Some(rect) = file.picture_rect(i) else { continue }; //! decoder.decode(Rect::from(rect), new_palette, &file.read_frame(&bytes, i)?)?; //! let rgb = decoder.rgb24(); // the picture after this block //! } @@ -122,8 +122,8 @@ impl Decoder { if width == 0 || height == 0 { return Err(Error::Invalid("the picture has no pixels")); } - // the indices and an RGBA copy of them for the caller - let shape = PictureShape { width: width.into(), height: height.into(), shift_x: 0, shift_y: 0, chroma_planes: 0, bytes_per_sample: 5 }; + // the indices, an RGBA copy of them for the caller, and the unpack buffer + let shape = PictureShape { width: width.into(), height: height.into(), shift_x: 0, shift_y: 0, chroma_planes: 0, bytes_per_sample: 9 }; if !shape.fits(1, DECODE_MEMORY_BUDGET) { return Err(Error::TooLarge(width, height)); } @@ -205,8 +205,9 @@ impl Decoder { return self.render(rect, method, body); } let mut unpacked = std::mem::take(&mut self.unpacked); - // no rendering method reads more than a few bytes a pixel: unpacking stops there, so that - // a frame's cost goes by the picture's size and not by what the file says + // a frame needs at most three bytes a pixel (more only with run-length codes that + // paint nothing): unpacking stops past that, so that a frame's cost goes by the + // picture's size and not by what the file says let useful = self.indices.len().saturating_mul(4).saturating_add(1024); let result = lz_unpack(body, self.unpack_limit, useful, &mut unpacked).and_then(|()| self.render(rect, method & 0x7F, &unpacked)); self.unpacked = unpacked; diff --git a/crates/video/tests/vmd/main.rs b/crates/video/tests/vmd/main.rs index b44aa3753..02d9617f0 100644 --- a/crates/video/tests/vmd/main.rs +++ b/crates/video/tests/vmd/main.rs @@ -112,7 +112,7 @@ fn decode_all(bytes: &[u8]) -> Vec<(Vec, Vec)> { let mut out = Vec::new(); for (i, frame) in file.frames.iter().enumerate() { let FrameKind::Video { new_palette, .. } = frame.kind else { continue }; - let rect = Rect::from(file.picture_rect(frame).unwrap()); + let rect = Rect::from(file.picture_rect(i).unwrap()); decoder.decode(rect, new_palette, &file.read_frame(bytes, i).unwrap()).unwrap(); out.push((decoder.indices().to_vec(), decoder.rgb24())); } @@ -236,16 +236,17 @@ fn lz_chains() { assert_eq!(unpack(&short).unwrap(), want); // with the marker the window starts at 0x111, and a length of 18 takes one more byte: 18 + 5 let long = [32, 0, 0, 0, 0x34, 0x12, 0x78, 0x56, 0b0000_0111, 0x90, 0xA0, 0xB0, 0x11, 0x10, 0x00, 0x0F, 5]; - let mut want = vec![0x90, 0xA0, 0xB0, 0x90, 0xA0, 0xB0]; - want.resize(29, 0x20); - want.extend([0x40; 3]); - // 29 of the 32 bytes arrive: the picture's last three pixels are not painted + // 29 of the 32 bytes arrive (3 literals, 3 and 23 chained): the first row is painted, the + // second, three bytes short, is not assert_eq!(unpack(&long), Err(Error::Invalid("the frame data ends early"))); let mut d = flat(); let mut data = vec![0x82u8]; data.extend_from_slice(&long); let _ = d.decode(FULL, false, &data); - assert_eq!(d.indices()[..16], want[..16]); + let mut want = vec![0x90, 0xA0, 0xB0, 0x90, 0xA0, 0xB0]; + want.resize(16, 0x20); + want.extend([0x40; 16]); + assert_eq!(d.indices(), want); // a chain that overlaps what it writes repeats it: one literal, then 18 copies of it let overlap = [32, 0, 0, 0, 0b0000_0001, 7, 0xEE, 0xFF, 0xEE, 0xFA]; assert_eq!(unpack(&overlap).unwrap(), [7; 32]); @@ -284,6 +285,22 @@ fn lz_unpacking_stops_at_what_a_picture_can_use() { assert_eq!(d.indices(), [0x20; 32]); // 87 MB of output for each frame without the stop: seconds, not milliseconds assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed()); + + // the stop leaves room for the largest body a frame needs: every two pixels as a run-length + // run of their own, five bytes for two pixels + let (w, h) = (128, 32); + let mut d = Decoder::new(&build(&Spec::new(w, h), &[])).unwrap(); + let body: Vec = (0..w * h / 2).flat_map(|i| [0x81, 0xFF, 0x81, i as u8, (i >> 8) as u8]).collect(); + // LZ packing with literals only: tags of 0xFF, eight bytes each + let mut data = vec![0x83]; + data.extend((body.len() as u32).to_le_bytes()); + for chunk in body.chunks(8) { + data.push(0xFF); + data.extend_from_slice(chunk); + } + d.decode(Rect { left: 0, top: 0, right: w - 1, bottom: h - 1 }, false, &data).unwrap(); + let want: Vec = (0..w * h / 2).flat_map(|i| [i as u8, (i >> 8) as u8]).collect(); + assert!(d.indices() == want); } #[test] @@ -370,7 +387,7 @@ fn hostile_input_never_panics() { let Ok(data) = file.read_frame(d, i) else { continue }; // the rectangle as stored too: the decoder must refuse what does not fit let _ = decoder.decode(Rect { left, top, right, bottom }, new_palette, &data); - if let Some(rect) = file.picture_rect(frame) { + if let Some(rect) = file.picture_rect(i) { let _ = decoder.decode(rect.into(), new_palette, &data); } } @@ -419,7 +436,7 @@ fn real_files_match_ffmpeg() { if frame.size == 0 { continue; } - let rect = file.picture_rect(frame).unwrap_or_else(|| panic!("{name}: frame {i} lies outside the picture")); + let rect = file.picture_rect(i).unwrap_or_else(|| panic!("{name}: frame {i} lies outside the picture")); let data = file.read_frame(&source, i).unwrap(); decoder.decode(rect.into(), new_palette, &data).unwrap_or_else(|e| panic!("{name}: frame {i}: {e}")); theirs_out.read_exact(&mut theirs).unwrap_or_else(|e| panic!("{name}: ffmpeg has no picture for frame {i}: {e}"));