Merge remote-tracking branch 'origin/main' into fix/dsd-chunk-bounds

# Conflicts:
#	crates/audio/Cargo.toml
#	crates/audio/src/lib.rs
This commit is contained in:
Dylan M. Taylor committed 2026-11-17 09:58:22 -05:00
commit cbbba064fd
40 files changed
+5633 -22

No files matched your search

+10
View File
@@ -119,6 +119,16 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper
`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes.
## Aligned stored ZIP entries
The USDZ alignment requirement and compatibility fixture for `Writer::add_stored_aligned` come from TextureCraft `crates/formats/src/mesh_export/usd.rs`, introduced by bflatastic in `bdbb52c9` and maintained through `9eb20086` (MIT OR Apache-2.0). The shared API and alignment validation are subsequent Dylan M. Taylor work. Scene/material mapping remains in TextureCraft.
The raw gradient wire ordering in `craft-lottie::Gradient::flat_values` follows
AniCraft's Lottie exporter by Tanish Manku (`63b39355`, `b9258b7b`), MIT OR Apache-2.0.
Sanitization, animation fitting and numeric output policy remain caller-owned.
## Screen Video key frames
`crates/video/src/screen_video.rs` extracts AniCraft `crates/xfl/src/video.rs` codec-3 decoding and its synthetic partial-block fixture, introduced by Tanish Manku in `1f3e603b7ff53a3da364e41ec4da8d43dc83aab0` with pixel-loop cleanup `2b7571363b4b647266df758f95b6e397021cfd4d` (MIT OR Apache-2.0). Import commits preserve Tanish as primary author. Caller-owned bounds and neutral RGBA output separate codec work from the consuming app's FLV first-frame/report policy. Boundary tests and integration are subsequent Dylan M. Taylor changes.
## JSONC span-preserving editing
`crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported.
Generated
+7
View File
@@ -2272,6 +2272,13 @@ dependencies = [
"zune-jpeg",
]
[[package]]
name = "craft-jsonc"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]]
name = "craft-jsonrpc"
version = "0.1.0"
+1
View File
@@ -11,6 +11,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/craft-libs"
[workspace.dependencies]
craft-jsonc = { path = "crates/jsonc" }
craft-palette = { path = "crates/palette" }
craft-score = { path = "crates/score" }
craft-shx = { path = "crates/shx" }
+1 -1
View File
@@ -274,7 +274,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-math`](crates/math/README.md): equations as one tree (the Office Math object model) with its syntaxes, read and written: OMML, presentation MathML, LaTeX math and the UnicodeMath linear format.
- [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV
(`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`) and
MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and
MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, a Sierra VMD (`vmd`) demuxer, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and
video codecs will go in a separate crate.
- [`craft-lottie`](crates/lottie/README.md): Lottie (Bodymovin) JSON: the document model of
lottie-spec 1.0 (animation, assets, layers by type, shape items, masks, effects, text, markers)
+22
View File
@@ -45,6 +45,8 @@ opus-decode = []
qoa = ["qoa-decode", "qoa-encode"]
qoa-decode = []
qoa-encode = []
# ITU-T G.722 wideband sub-band ADPCM speech codec (64 kbit/s).
g722 = []
opus-encode = []
# GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own.
gsm = ["gsm-decode", "gsm-encode"]
@@ -64,8 +66,14 @@ eac3-encode = ["craft-media/bitstream"]
mp3-encode = ["craft-media/bitstream"]
# Direct Stream Digital (DSD) files: DSF and DSDIFF decoders and DSD-to-PCM decimation.
dsd = []
# MPEG-1/2 Layer II (MP2) encoder (`mpa::encoder`). It shares the polyphase analysis filter of the
# MP3 encoder and the tables of the MP1/MP2 decoder.
mpa-encode = ["mpa-decode", "mp3-encode"]
# Bluetooth Low Complexity Subband Coding (SBC) audio codec (`sbc`).
sbc = []
# Sierra VMD sound decoder (`vmd::Decoder`): 8-bit PCM and 16-bit DPCM.
vmd-decode = []
# Multi-resolution waveform overviews (`peaks`).
peaks = []
# Encode AAC channels in parallel (with `aac-encode`).
@@ -85,6 +93,8 @@ symphonia = { version = "0.6.1", optional = true, default-features = false, feat
[dev-dependencies]
craft-media-testkit = { workspace = true }
# The VMD demuxer, for the VMD sound decoder's tests.
craft-media = { workspace = true, features = ["vmd"] }
proptest = { workspace = true }
serde_json = { workspace = true }
@@ -92,10 +102,18 @@ serde_json = { workspace = true }
name = "audio"
required-features = ["decode", "lossless-encode", "peaks"]
[[test]]
name = "vmd"
required-features = ["vmd-decode"]
[[test]]
name = "codecs"
required-features = ["decode", "encode"]
[[test]]
name = "mp2_encoder_oracle"
required-features = ["mpa-encode"]
[[test]]
name = "flac_decode"
required-features = ["flac-decode", "flac-encode"]
@@ -112,6 +130,10 @@ required-features = ["qoa"]
name = "dsd_oracle"
required-features = ["dsd"]
[[test]]
name = "g722_oracle"
required-features = ["g722"]
[[test]]
name = "sbc_oracle"
required-features = ["sbc"]
+3
View File
@@ -44,7 +44,9 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou
| `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` |
| `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` |
| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` |
| `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` |
| `gsm-decode`, `gsm-encode` (`gsm`) | `gsm::Decoder`, `gsm::Encoder`, `gsm::decode`, `gsm::encode`: GSM 06.10 full-rate speech, bit-exact, raw `.gsm` and WAV (GSM 6.10) packings | none |
| `vmd-decode` | `vmd::Decoder`: Sierra VMD sound (8-bit PCM and 16-bit DPCM), frame by frame from `craft_media::vmd` | none |
| `peaks` | `peaks::Peaks` | none |
| `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` |
| `serde` | `Serialize`/`Deserialize` on the shared types | `serde` |
@@ -566,6 +568,7 @@ Each codec module's rustdoc lists the coding tools it implements.
| Opus (`opus`) | RFC 6716, 8251, 7845 | decoder: SILK, hybrid, CELT, all frame sizes, PLC and FEC, multistream (`Decoder`) and single stream (`StreamDecoder`), 8–48 kHz output; encoder (`Encoder`): SILK, hybrid, CELT, 48 kHz, 20 ms frames, mono or stereo | all 36 RFC 8251 conformance cases; encoder output through ffmpeg's two Opus decoders |
| AC-3/E-AC-3 (`ac3`) | decoder: ATSC A/52:2012; encoder/programme API: ETSI TS 102 366 V1.4.1 | single-syncframe and complete-programme decoding; packet encoding through discrete 7.1 (see below) | decoder comparisons and encoder output through ffmpeg, CRC/channel/timing/bit-budget regressions; synthetic quality limitations below |
| MP1/MP2 (`mpa`) | ISO/IEC 11172-3, 13818-3 | Layer I and II, MPEG-1/2/2.5, 8–48 kHz; also the Layer II rate/mode pairs the spec disallows (ffmpeg's default mono 384 kbit/s); no free format | ffmpeg-encoded streams, 73–84 dB SNR |
| MP2 encoder (`mpa::encoder`) | ISO/IEC 11172-3 (§2.4, Annex B and C), 13818-3 | Layer II, constant bit rate, mono or stereo (no joint stereo), 32/44.1/48 kHz at the spec's rate/mode pairs and 16/22.05/24 kHz at 8–160 kbit/s; no CRC | our decoder and ffmpeg decode the frames; SNR of 20–37 dB on tone mixes, and the 481-sample filter delay matches |
| MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) |
| MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode |
| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways |
+693
View File
@@ -0,0 +1,693 @@
//! ITU-T Recommendation G.722 wideband audio coding (64 kbit/s).
//!
//! Pure safe Rust clean-room implementation of the G.722 sub-band adaptive differential
//! pulse code modulation (SB-ADPCM) speech and audio codec.
//!
//! Input audio is 16 kHz 16-bit linear PCM. An analysis Quadrature Mirror Filter (QMF) splits
//! the 16 kHz audio into a lower sub-band (0–4 kHz) and a higher sub-band (4–8 kHz), each
//! sampled at 8 kHz. The lower sub-band is encoded at 48 kbit/s (6 bits/sample) and the higher
//! sub-band at 16 kbit/s (2 bits/sample), multiplexed into an 8-bit octet per 8 kHz cycle
//! (64 kbit/s total stream rate).
//!
//! On decoding, inverse adaptive quantizers reconstruct each sub-band signal, and a synthesis
//! QMF interpolates and combines them back to 16 kHz 16-bit linear PCM.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
/// Maximum allowed channels for multi-channel processing.
pub const MAX_CHANNELS: usize = 8;
/// Maximum input byte buffer bound to prevent memory exhaustion on hostile inputs (64 MiB).
pub const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024;
/// Maximum input sample count bound (128 million samples).
pub const MAX_SAMPLES: usize = 128 * 1024 * 1024;
/// Error conditions encountered during G.722 encoding or decoding.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum Error {
/// The channel count is invalid.
#[error("invalid channel count: {0} (must be 1..={MAX_CHANNELS})")]
InvalidChannels(usize),
/// The input size exceeds safety bounds.
#[error("input exceeds maximum size bound")]
InputTooLarge,
/// Encoding requires an even number of samples per channel (16 kHz sample pairs).
#[error("odd number of samples: {0} (G.722 encodes pairs of 16 kHz samples)")]
OddSampleCount(usize),
/// System allocation failed when reserving buffer memory.
#[error("allocation failed")]
AllocationFailed,
}
// ---------------------------------------------------------------------------
// Specification Tables from ITU-T Recommendation G.722
// ---------------------------------------------------------------------------
/// 24-tap QMF filter coefficients scaled by 2^13 (Table 11/G.722).
const H: [i16; 24] = [3, -11, -11, 53, 12, -156, 32, 362, -210, -805, 951, 3876, 3876, 951, -805, -210, 362, 32, -156, 12, 53, -11, -11, 3];
/// Lower sub-band 60-level inverse quantizer reconstruction table QQ6 (Table 14/G.722).
const QQ6: [i16; 31] = [
0, 17, 54, 91, 130, 170, 211, 254, 300, 347, 396, 447, 501, 558, 618, 682, 750, 822, 899, 982, 1072, 1170, 1279, 1399, 1535, 1689, 1873, 2088,
2376, 2738, 3101,
];
/// Lower sub-band quantizer decision levels Q6 (Table 14/G.722).
const Q6: [i16; 30] = [
0, 35, 72, 110, 150, 190, 233, 276, 323, 370, 422, 473, 530, 587, 650, 714, 786, 858, 940, 1023, 1121, 1219, 1339, 1458, 1612, 1765, 1980, 2195,
2557, 2919,
];
/// Lower sub-band 15-level inverse quantizer reconstruction table QQ4 (Table 14/G.722).
const QQ4: [i16; 8] = [0, 150, 323, 530, 786, 1121, 1612, 2557];
/// Lower sub-band logarithmic scale factor multipliers WL (Table 14/G.722).
const WL: [i16; 8] = [-60, -30, 58, 172, 334, 538, 1198, 3042];
/// Higher sub-band 4-level inverse quantizer reconstruction table QQ2 (Table 14/G.722).
const QQ2: [i16; 3] = [0, 202, 926];
/// Higher sub-band logarithmic scale factor multipliers WH (Table 14/G.722).
const WH: [i16; 3] = [0, -214, 798];
/// 32-entry inverse logarithmic scale table ILB (Table 15/G.722).
const ILB: [i32; 32] = [
2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383, 2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834, 2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371,
3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008,
];
/// Table 17/G.722: 4-bit codeword (RIL = IL >> 2) to (SIL, IL4).
const IL4_MAP: [(i16, usize); 16] =
[(0, 0), (-1, 7), (-1, 6), (-1, 5), (-1, 4), (-1, 3), (-1, 2), (-1, 1), (0, 7), (0, 6), (0, 5), (0, 4), (0, 3), (0, 2), (0, 1), (0, 0)];
/// Table 21/G.722: 2-bit codeword IH to (SIH, IH2).
const IH2_MAP: [(i16, usize); 4] = [(-1, 2), (-1, 1), (0, 2), (0, 1)];
#[inline]
fn mult(a: i16, b: i16) -> i16 {
(((a as i32) * (b as i32)) >> 15) as i16
}
#[inline]
fn scalel(nbpl: i32) -> i32 {
let wd1 = ((nbpl >> 6) & 31) as usize;
let wd2 = nbpl >> 11;
let shift = 8 - wd2;
let wd3 = if shift >= 0 { ILB[wd1] >> shift } else { ILB[wd1] << (-shift) };
wd3 << 2
}
#[inline]
fn scaleh(nbph: i32) -> i32 {
let wd1 = ((nbph >> 6) & 31) as usize;
let wd2 = nbph >> 11;
let shift = 10 - wd2;
let wd3 = if shift >= 0 { ILB[wd1] >> shift } else { ILB[wd1] << (-shift) };
wd3 << 2
}
// ---------------------------------------------------------------------------
// Sub-band ADPCM State (Pole/Zero Predictors & Adaptations)
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
struct BandState {
s: i16,
sp: i16,
sz: i16,
d: [i16; 7],
r: [i16; 3],
p: [i16; 3],
a: [i16; 3],
b: [i16; 7],
nb: i32,
det: i32,
}
impl BandState {
fn new(is_lower: bool) -> Self {
Self { s: 0, sp: 0, sz: 0, d: [0; 7], r: [0; 3], p: [0; 3], a: [0; 3], b: [0; 7], nb: 0, det: if is_lower { 32 } else { 8 } }
}
fn reset(&mut self, is_lower: bool) {
self.s = 0;
self.sp = 0;
self.sz = 0;
self.d = [0; 7];
self.r = [0; 3];
self.p = [0; 3];
self.a = [0; 3];
self.b = [0; 7];
self.nb = 0;
self.det = if is_lower { 32 } else { 8 };
}
fn update_predictor(&mut self, d: i16, p_sig: i16, r_sig: i16) {
// UPZERO: update 6th order zero predictor coefficients
let wd1: i16 = if d != 0 { 128 } else { 0 };
let sg0: i16 = if d < 0 { -1 } else { 0 };
for i in 1..=6 {
let sgi = if self.d[i] < 0 { -1 } else { 0 };
let wd2 = if sg0 == sgi { wd1 } else { wd1.saturating_neg() };
let wd3 = mult(self.b[i], 32640);
self.b[i] = wd2.saturating_add(wd3);
}
// UPPOL2: update 2nd pole coefficient
let sg0 = if p_sig < 0 { -1 } else { 0 };
let sg1 = if self.p[1] < 0 { -1 } else { 0 };
let sg2 = if self.p[2] < 0 { -1 } else { 0 };
let wd1 = self.a[1].saturating_add(self.a[1]).saturating_add(self.a[1].saturating_add(self.a[1]));
let wd2 = if sg0 == sg1 { wd1.saturating_neg() } else { wd1 } >> 7;
let wd3: i16 = if sg0 == sg2 { 128 } else { -128 };
let wd4 = wd2.saturating_add(wd3);
let wd5 = mult(self.a[2], 32512);
let apl2 = wd4.saturating_add(wd5).clamp(-12288, 12288);
// UPPOL1: update 1st pole coefficient
let wd1: i16 = if sg0 == sg1 { 192 } else { -192 };
let wd2 = mult(self.a[1], 32640);
let apl1 = wd1.saturating_add(wd2);
let wd3 = 15360 - apl2;
let apl1 = apl1.clamp(-wd3, wd3);
self.a[1] = apl1;
self.a[2] = apl2;
// Shift history delay lines
for i in (2..=6).rev() {
self.d[i] = self.d[i - 1];
}
self.d[1] = d;
self.p[2] = self.p[1];
self.p[1] = p_sig;
self.r[2] = self.r[1];
self.r[1] = r_sig;
// FILTEZ: compute zero section output
let mut sz: i16 = 0;
for i in (1..=6).rev() {
let part = mult(self.b[i], self.d[i].saturating_add(self.d[i]));
sz = sz.saturating_add(part);
}
self.sz = sz;
// FILTEP: compute pole section output
let sp1 = mult(self.a[1], self.r[1].saturating_add(self.r[1]));
let sp2 = mult(self.a[2], self.r[2].saturating_add(self.r[2]));
self.sp = sp1.saturating_add(sp2);
// PREDIC: compute full predictor output value
self.s = self.sp.saturating_add(self.sz);
}
}
// ---------------------------------------------------------------------------
// Quadrature Mirror Filters (QMF)
// ---------------------------------------------------------------------------
/// Analysis QMF (transmit filter bank): splits pairs of 16 kHz samples into lower and higher sub-bands.
#[derive(Debug, Clone, Default)]
pub struct QmfTx {
x: [i16; 24],
}
impl QmfTx {
/// Create a new analysis QMF filter.
pub fn new() -> Self {
Self { x: [0; 24] }
}
/// Reset filter history.
pub fn reset(&mut self) {
self.x = [0; 24];
}
/// Process a pair of 16 kHz input samples `(s0, s1)` into `(xl, xh)`.
pub fn filter(&mut self, s0: i16, s1: i16) -> (i16, i16) {
for i in (2..24).rev() {
self.x[i] = self.x[i - 2];
}
self.x[0] = s1 >> 1;
self.x[1] = s0 >> 1;
let mut xa: i32 = 0;
let mut xb: i32 = 0;
for i in 0..12 {
xa = xa.saturating_add((self.x[2 * i] as i32) * (H[2 * i] as i32));
xb = xb.saturating_add((self.x[2 * i + 1] as i32) * (H[2 * i + 1] as i32));
}
let xl = ((xa.saturating_add(xb)) >> 13).clamp(-16384, 16383) as i16;
let xh = ((xa.saturating_sub(xb)) >> 13).clamp(-16384, 16383) as i16;
(xl, xh)
}
}
/// Synthesis QMF (receive filter bank): synthesizes lower and higher sub-band signals into 16 kHz output.
#[derive(Debug, Clone, Default)]
pub struct QmfRx {
xd: [i16; 12],
xs: [i16; 12],
}
impl QmfRx {
/// Create a new synthesis QMF filter.
pub fn new() -> Self {
Self { xd: [0; 12], xs: [0; 12] }
}
/// Reset filter history.
pub fn reset(&mut self) {
self.xd = [0; 12];
self.xs = [0; 12];
}
/// Reconstruct a pair of 16 kHz output samples from sub-band samples `(rl, rh)`.
pub fn filter(&mut self, rl: i16, rh: i16) -> (i16, i16) {
let xd_curr = rl.saturating_sub(rh);
let xs_curr = rl.saturating_add(rh);
for i in (1..12).rev() {
self.xd[i] = self.xd[i - 1];
self.xs[i] = self.xs[i - 1];
}
self.xd[0] = xd_curr;
self.xs[0] = xs_curr;
let mut wd_c: i32 = 0;
let mut wd_d: i32 = 0;
for i in 0..12 {
wd_c = wd_c.saturating_add((self.xd[i] as i32) * (H[2 * i] as i32));
wd_d = wd_d.saturating_add((self.xs[i] as i32) * (H[2 * i + 1] as i32));
}
let xout1 = (wd_c >> 12).clamp(-16384, 16383);
let xout2 = (wd_d >> 12).clamp(-16384, 16383);
let s0 = (xout1 << 1).clamp(-32768, 32767) as i16;
let s1 = (xout2 << 1).clamp(-32768, 32767) as i16;
(s0, s1)
}
}
// ---------------------------------------------------------------------------
// G.722 Decoder & Encoder
// ---------------------------------------------------------------------------
/// ITU-T G.722 64 kbit/s single-channel decoder.
#[derive(Debug, Clone)]
pub struct Decoder {
band_l: BandState,
band_h: BandState,
qmf: QmfRx,
}
impl Default for Decoder {
fn default() -> Self {
Self::new()
}
}
impl Decoder {
/// Create a new G.722 decoder initialized to standard reset state.
pub fn new() -> Self {
Self { band_l: BandState::new(true), band_h: BandState::new(false), qmf: QmfRx::new() }
}
/// Reset decoder internal state.
pub fn reset(&mut self) {
self.band_l.reset(true);
self.band_h.reset(false);
self.qmf.reset();
}
/// Decode a single 8-bit octet into two 16 kHz 16-bit PCM samples.
pub fn decode_octet(&mut self, octet: u8) -> (i16, i16) {
let ih = ((octet >> 6) & 3) as usize;
let il = (octet & 0x3F) as usize;
// INVQBL: 6-bit lower sub-band inverse quantization
let (sil6, il6) = table18_lookup(il);
let wd1 = (QQ6[il6] as i32) << 3;
let wd2 = if sil6 == 0 { wd1 } else { -wd1 };
let dl = mult(self.band_l.det as i16, wd2 as i16);
let yl = self.band_l.s.saturating_add(dl);
let rl = yl.clamp(-16384, 16383);
// INVQAL: lower sub-band predictor update (4-bit feedback path)
let ril = il >> 2;
let (sil4, il4) = IL4_MAP[ril & 0x0F];
let wd1 = (QQ4[il4] as i32) << 3;
let wd2 = if sil4 == 0 { wd1 } else { -wd1 };
let dlt = mult(self.band_l.det as i16, wd2 as i16);
let plt = dlt.saturating_add(self.band_l.sz);
let rlt = self.band_l.s.saturating_add(dlt);
// Lower sub-band scale factor adaptation (LOGSCL)
let wd_scale = mult(self.band_l.nb as i16, 32512);
let nbpl = (wd_scale as i32 + WL[il4] as i32).clamp(0, 18432);
self.band_l.nb = nbpl;
self.band_l.det = scalel(nbpl);
self.band_l.update_predictor(dlt, plt, rlt);
// INVQAH: higher sub-band inverse quantization
let (sih_dec, ih2) = IH2_MAP[ih & 0x03];
let wd1 = (QQ2[ih2] as i32) << 3;
let wd2 = if sih_dec == 0 { wd1 } else { -wd1 };
let dh = mult(self.band_h.det as i16, wd2 as i16);
let yh = self.band_h.s.saturating_add(dh);
let rh = yh.clamp(-16384, 16383);
// Higher sub-band scale factor adaptation (LOGSCH)
let wd_scale = mult(self.band_h.nb as i16, 32512);
let nbph = (wd_scale as i32 + WH[ih2] as i32).clamp(0, 22528);
self.band_h.nb = nbph;
self.band_h.det = scaleh(nbph);
let ph = dh.saturating_add(self.band_h.sz);
self.band_h.update_predictor(dh, ph, yh);
// Synthesis QMF
self.qmf.filter(rl, rh)
}
/// Decode G.722 octets into 16 kHz 16-bit linear PCM samples, appending to `dst`.
pub fn decode(&mut self, src: &[u8], dst: &mut Vec<i16>) -> Result<(), Error> {
if src.len() > MAX_INPUT_BYTES {
return Err(Error::InputTooLarge);
}
let needed_samples = src.len().saturating_mul(2);
if needed_samples > MAX_SAMPLES {
return Err(Error::InputTooLarge);
}
dst.try_reserve(needed_samples).map_err(|_| Error::AllocationFailed)?;
for &octet in src {
let (s0, s1) = self.decode_octet(octet);
dst.push(s0);
dst.push(s1);
}
Ok(())
}
}
/// ITU-T G.722 64 kbit/s single-channel encoder.
#[derive(Debug, Clone)]
pub struct Encoder {
qmf: QmfTx,
band_l: BandState,
band_h: BandState,
}
impl Default for Encoder {
fn default() -> Self {
Self::new()
}
}
impl Encoder {
/// Create a new G.722 encoder initialized to standard reset state.
pub fn new() -> Self {
Self { qmf: QmfTx::new(), band_l: BandState::new(true), band_h: BandState::new(false) }
}
/// Reset encoder internal state.
pub fn reset(&mut self) {
self.qmf.reset();
self.band_l.reset(true);
self.band_h.reset(false);
}
/// Encode a pair of 16 kHz 16-bit PCM samples into one 8-bit G.722 octet.
pub fn encode_sample_pair(&mut self, s0: i16, s1: i16) -> u8 {
// Analysis QMF
let (xl, xh) = self.qmf.filter(s0, s1);
// Lower sub-band quantizer (QUANTL)
let el = xl.saturating_sub(self.band_l.s);
let sil = if el < 0 { -1 } else { 0 };
let wd = if sil == 0 { el } else { 32767 - (el & 32767) };
let mut mil: usize = 30;
for (k, &thresh_q) in Q6.iter().enumerate().skip(1) {
let thresh = (((thresh_q as i32) << 3) * self.band_l.det) >> 15;
if (wd as i32) < thresh {
mil = k;
break;
}
}
// Table 16 conversion to IL
let il: u8 = if sil == 0 {
(62 - mil) as u8
} else if mil == 1 {
63
} else if mil == 2 {
62
} else {
(34 - mil) as u8
};
// Lower sub-band feedback and predictor update (INVQAL)
let ril = (il >> 2) as usize;
let (sil4, il4) = IL4_MAP[ril & 0x0F];
let wd1 = (QQ4[il4] as i32) << 3;
let wd2 = if sil4 == 0 { wd1 } else { -wd1 };
let dlt = mult(self.band_l.det as i16, wd2 as i16);
let plt = dlt.saturating_add(self.band_l.sz);
let rlt = self.band_l.s.saturating_add(dlt);
// Lower sub-band scale factor adaptation (LOGSCL)
let wd_scale = mult(self.band_l.nb as i16, 32512);
let nbpl = (wd_scale as i32 + WL[il4] as i32).clamp(0, 18432);
self.band_l.nb = nbpl;
self.band_l.det = scalel(nbpl);
self.band_l.update_predictor(dlt, plt, rlt);
// Higher sub-band quantizer (QUANTH)
let eh = xh.saturating_sub(self.band_h.s);
let sih = if eh < 0 { -1 } else { 0 };
let wd = if sih == 0 { eh } else { 32767 - (eh & 32767) };
let thresh = ((564 << 3) * self.band_h.det) >> 15;
let mih = if (wd as i32) < thresh { 1 } else { 2 };
// Table 20 conversion to IH
let ih: u8 = if sih == -1 {
if mih == 2 { 0 } else { 1 }
} else if mih == 1 {
3
} else {
2
};
// Higher sub-band feedback and predictor update (INVQAH)
let (sih_dec, ih2) = IH2_MAP[ih as usize];
let wd1 = (QQ2[ih2] as i32) << 3;
let wd2 = if sih_dec == 0 { wd1 } else { -wd1 };
let dh = mult(self.band_h.det as i16, wd2 as i16);
let yh = self.band_h.s.saturating_add(dh);
// Higher sub-band scale factor adaptation (LOGSCH)
let wd_scale = mult(self.band_h.nb as i16, 32512);
let nbph = (wd_scale as i32 + WH[ih2] as i32).clamp(0, 22528);
self.band_h.nb = nbph;
self.band_h.det = scaleh(nbph);
let ph = dh.saturating_add(self.band_h.sz);
self.band_h.update_predictor(dh, ph, yh);
// Multiplexer (MUX)
(ih << 6) | (il & 0x3F)
}
/// Encode 16 kHz 16-bit linear PCM samples into G.722 octets, appending to `dst`.
pub fn encode(&mut self, src: &[i16], dst: &mut Vec<u8>) -> Result<(), Error> {
if !src.len().is_multiple_of(2) {
return Err(Error::OddSampleCount(src.len()));
}
if src.len() > MAX_SAMPLES {
return Err(Error::InputTooLarge);
}
let needed_octets = src.len() / 2;
dst.try_reserve(needed_octets).map_err(|_| Error::AllocationFailed)?;
for &[s0, s1] in src.as_chunks::<2>().0 {
let octet = self.encode_sample_pair(s0, s1);
dst.push(octet);
}
Ok(())
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
#[inline]
fn table18_lookup(il: usize) -> (i16, usize) {
let il = il & 0x3F;
if (4..=31).contains(&il) {
(-1, 34 - il)
} else if il == 62 {
(-1, 2)
} else if il == 63 {
(-1, 1)
} else if (32..=61).contains(&il) {
(0, 62 - il)
} else {
// Transmission error fallbacks (0..=3)
(-1, 1)
}
}
// ---------------------------------------------------------------------------
// Public Top-Level Functions
// ---------------------------------------------------------------------------
/// Decode a mono 64 kbit/s G.722 stream into 16 kHz 16-bit linear PCM samples.
pub fn decode(bytes: &[u8]) -> Result<Vec<i16>, Error> {
let mut decoder = Decoder::new();
let mut out = Vec::new();
decoder.decode(bytes, &mut out)?;
Ok(out)
}
/// Encode mono 16 kHz 16-bit linear PCM samples into a 64 kbit/s G.722 stream.
pub fn encode(samples: &[i16]) -> Result<Vec<u8>, Error> {
let mut encoder = Encoder::new();
let mut out = Vec::new();
encoder.encode(samples, &mut out)?;
Ok(out)
}
/// Decode an interleaved multi-channel G.722 stream into interleaved 16 kHz 16-bit PCM samples.
pub fn decode_interleaved(bytes: &[u8], channels: usize) -> Result<Vec<i16>, Error> {
if channels == 0 || channels > MAX_CHANNELS {
return Err(Error::InvalidChannels(channels));
}
if channels == 1 {
return decode(bytes);
}
if bytes.len() > MAX_INPUT_BYTES {
return Err(Error::InputTooLarge);
}
let frames = bytes.len() / channels;
let mut decoders: Vec<Decoder> = Vec::with_capacity(channels);
for _ in 0..channels {
decoders.push(Decoder::new());
}
let total_samples = frames.saturating_mul(channels).saturating_mul(2);
let mut out = Vec::new();
out.try_reserve(total_samples).map_err(|_| Error::AllocationFailed)?;
// Each frame has `channels` bytes. Decode each byte with its channel's decoder,
// producing sample 0 for each channel, then sample 1 for each channel.
for chunk in bytes.chunks_exact(channels) {
let mut pairs = [(0i16, 0i16); MAX_CHANNELS];
for (ch, &b) in chunk.iter().enumerate() {
pairs[ch] = decoders[ch].decode_octet(b);
}
for pair in pairs.iter().take(channels) {
out.push(pair.0);
}
for pair in pairs.iter().take(channels) {
out.push(pair.1);
}
}
Ok(out)
}
/// Encode interleaved 16 kHz 16-bit PCM samples into an interleaved multi-channel G.722 stream.
pub fn encode_interleaved(samples: &[i16], channels: usize) -> Result<Vec<u8>, Error> {
if channels == 0 || channels > MAX_CHANNELS {
return Err(Error::InvalidChannels(channels));
}
if channels == 1 {
return encode(samples);
}
if samples.len() > MAX_SAMPLES {
return Err(Error::InputTooLarge);
}
let frame_len = channels.saturating_mul(2);
if !samples.len().is_multiple_of(frame_len) {
return Err(Error::OddSampleCount(samples.len()));
}
let frames = samples.len() / frame_len;
let mut encoders: Vec<Encoder> = Vec::with_capacity(channels);
for _ in 0..channels {
encoders.push(Encoder::new());
}
let total_bytes = frames.saturating_mul(channels);
let mut out = Vec::new();
out.try_reserve(total_bytes).map_err(|_| Error::AllocationFailed)?;
for chunk in samples.chunks_exact(frame_len) {
for ch in 0..channels {
let s0 = chunk[ch];
let s1 = chunk[ch + channels];
out.push(encoders[ch].encode_sample_pair(s0, s1));
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reject_invalid_channels() {
assert_eq!(decode_interleaved(&[0; 4], 0), Err(Error::InvalidChannels(0)));
assert_eq!(decode_interleaved(&[0; 4], 9), Err(Error::InvalidChannels(9)));
assert_eq!(encode_interleaved(&[0; 4], 0), Err(Error::InvalidChannels(0)));
assert_eq!(encode_interleaved(&[0; 4], 9), Err(Error::InvalidChannels(9)));
}
#[test]
fn reject_odd_sample_count() {
assert_eq!(encode(&[0; 3]), Err(Error::OddSampleCount(3)));
assert_eq!(encode_interleaved(&[0; 5], 2), Err(Error::OddSampleCount(5)));
}
#[test]
fn roundtrip_silence() {
let input = vec![0i16; 320];
let encoded = encode(&input).expect("encode silence");
assert_eq!(encoded.len(), 160);
let decoded = decode(&encoded).expect("decode silence");
assert_eq!(decoded.len(), 320);
for &s in &decoded[40..] {
assert!(s.abs() <= 6, "silence sample too large: {s}");
}
}
#[test]
fn multichannel_stereo_roundtrip() {
let mut stereo_pcm = Vec::new();
for i in 0..400 {
stereo_pcm.push((i * 10) as i16);
stereo_pcm.push((-i * 10) as i16);
}
let enc = encode_interleaved(&stereo_pcm, 2).expect("encode stereo");
assert_eq!(enc.len(), 400);
let dec = decode_interleaved(&enc, 2).expect("decode stereo");
assert_eq!(dec.len(), 800);
}
#[test]
fn hostile_input_does_not_panic() {
let garbage = [0xFF, 0x00, 0x55, 0xAA, 0x12, 0x34, 0x7F, 0x80];
let dec = decode(&garbage).expect("decode garbage");
assert_eq!(dec.len(), 16);
}
#[test]
fn uppol2_overflow_does_not_panic() {
let mut state = BandState::new(true);
state.a[1] = -8192;
state.p = [0, 0, 0];
state.update_predictor(0, 0, 0);
}
}
+18 -3
View File
@@ -28,11 +28,12 @@
//! - [`peaks`] (feature `peaks`): min/max/RMS pyramid for waveform drawing.
//! - Codec modules for packet-level use, each with its own features: [`aac`] (`aac-decode`,
//! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and
//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`]
//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`]
//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder;
//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files),
//! [`dsd`] (`dsd`: DSF and DSDIFF files to PCM).
//! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech).
//! [`dsd`] (`dsd`: DSF and DSDIFF files to PCM),
//! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`:
//! Sierra VMD sound).
//!
//! The shared types below build with no features.
@@ -45,6 +46,8 @@ pub mod alac;
mod buffer;
#[cfg(feature = "dsd")]
pub mod dsd;
#[cfg(feature = "g722")]
pub mod g722;
#[cfg(any(feature = "gsm-decode", feature = "gsm-encode"))]
pub mod gsm;
mod layout;
@@ -66,6 +69,8 @@ mod read;
pub mod sbc;
#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))]
mod track;
#[cfg(feature = "vmd-decode")]
pub mod vmd;
#[cfg(feature = "vorbis-encode")]
pub mod vorbis;
#[cfg(any(feature = "decode-native", feature = "pcm-encode"))]
@@ -270,6 +275,16 @@ impl From<alac::Error> for AudioError {
}
}
#[cfg(feature = "vmd-decode")]
impl From<vmd::Error> for AudioError {
fn from(e: vmd::Error) -> Self {
match e {
vmd::Error::Unsupported(_) => AudioError::Unsupported(e.to_string()),
_ => AudioError::Malformed(e.to_string()),
}
}
}
#[cfg(feature = "opus-encode")]
impl From<opus::encoder::Error> for AudioError {
fn from(e: opus::encoder::Error) -> Self {
+2 -2
View File
@@ -39,13 +39,13 @@ mod decoder;
#[cfg(feature = "mp3-encode")]
mod encoder;
#[cfg(feature = "mp3-encode")]
mod filterbank;
pub(crate) mod filterbank;
#[cfg(feature = "mp3-encode")]
mod huffman;
mod huffman_tables;
#[cfg(feature = "mp3-encode")]
mod quantize;
mod tables;
pub(crate) mod tables;
#[cfg(feature = "mp3-decode")]
pub use decoder::{Decoder, InfoTag};
+493
View File
@@ -0,0 +1,493 @@
//! The Layer II encoder; the module docs are in `mpa/mod.rs`.
// Index loops follow the specification's pseudo-code (FilmCraft allows this lint workspace-wide).
#![allow(clippy::needless_range_loop)]
use craft_media::bitstream::BitWriter;
use super::tables::{self, AllocTable, SUBBANDS};
use crate::mp3::filterbank::Polyphase;
use crate::mp3::tables::ath_db;
/// Settings an [`Encoder`] refuses.
#[non_exhaustive]
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum EncodeError {
/// A sample rate outside [`SAMPLE_RATES`].
#[error("MP2: unsupported sample rate {0} Hz (32, 44.1, 48 kHz, or 16, 22.05, 24 kHz)")]
SampleRate(u32),
/// A bit rate that is not one of [`bitrates`] for the sample rate and channel count.
#[error("MP2: unsupported bit rate {kbps} kbit/s at {rate} Hz with {channels} channel(s)")]
Bitrate {
/// The bit rate asked for, kbit/s.
kbps: u32,
/// The sample rate, Hz.
rate: u32,
/// The channel count.
channels: usize,
},
/// More than two channels, or none.
#[error("MP2: unsupported channel count {0} (1 or 2)")]
Channels(usize),
}
/// Result with this module's [`EncodeError`].
pub type EncodeResult<T> = std::result::Result<T, EncodeError>;
/// Encoder settings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Config {
/// One of [`SAMPLE_RATES`].
pub sample_rate: u32,
/// 1 or 2. Two channels are coded as stereo (`mode` 00), each with its own allocation.
pub channels: usize,
/// One of [`bitrates`] for the sample rate and channel count, kbit/s.
pub bitrate_kbps: u32,
}
impl Config {
/// `channels` at `sample_rate`, constant `bitrate_kbps`.
pub fn cbr(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Config {
Config { sample_rate, channels, bitrate_kbps }
}
}
/// The sample rates the encoder accepts.
pub const SAMPLE_RATES: [u32; 6] = [32_000, 44_100, 48_000, 16_000, 22_050, 24_000];
/// Samples by which a standard decoder's output lags the input: the polyphase analysis and
/// synthesis filters.
pub const DELAY: u32 = 481;
/// Samples per channel in a frame.
pub const FRAME_SAMPLES: usize = 1152;
/// Bit rates ISO/IEC 11172-3 Table 3-B.2 allows for a single channel at 32 / 44.1 / 48 kHz.
const MPEG1_MONO: [u32; 10] = [32, 48, 56, 64, 80, 96, 112, 128, 160, 192];
/// Bit rates it allows for two channels.
const MPEG1_STEREO: [u32; 10] = [64, 96, 112, 128, 160, 192, 224, 256, 320, 384];
/// Whether `rate` is one of the MPEG-2 lower sampling frequencies; `None` if it is unsupported.
fn is_lsf(rate: u32) -> Option<bool> {
match rate {
32_000 | 44_100 | 48_000 => Some(false),
16_000 | 22_050 | 24_000 => Some(true),
_ => None,
}
}
/// The bit rates (kbit/s) a Layer II stream can use at `sample_rate` with `channels` channels:
/// at 32 / 44.1 / 48 kHz the combinations ISO/IEC 11172-3 allows (32-192 for one channel, 64-384
/// for two), at the lower sampling frequencies 8-160 for either. Empty for an unsupported rate.
pub fn bitrates(sample_rate: u32, channels: usize) -> &'static [u32] {
match is_lsf(sample_rate) {
Some(false) if channels == 1 => &MPEG1_MONO,
Some(false) => &MPEG1_STEREO,
Some(true) => &tables::BITRATES_LSF_L23[1..],
None => &[],
}
}
/// The highest bit rate at `sample_rate` and `channels` not above `kbps` (the lowest one when
/// `kbps` is below all of them); `None` for an unsupported rate.
pub fn nearest_bitrate(sample_rate: u32, channels: usize, kbps: u32) -> Option<u32> {
let rates = bitrates(sample_rate, channels);
rates.iter().rev().find(|&&r| r <= kbps).or(rates.first()).copied()
}
/// SNR-free noise model: the power of the error of rounding a value in ±1 to one of `steps`
/// levels spaced `2 / steps` apart, is `(2 / steps)² / 12`.
fn quantization_noise(steps: u16) -> f32 {
let d = 2.0 / f32::from(steps);
d * d / 12.0
}
/// Index of the scalefactor for a peak of `peak` (Table 3-B.1): the smallest scalefactor that is
/// at least `peak`, i.e. the largest index.
fn scalefactor_index(peak: f32) -> u32 {
if peak.is_nan() || peak <= 0.0 {
return 62;
}
let mut i = (3.0 * (1.0 - f64::from(peak).log2())).floor().clamp(0.0, 62.0) as u32;
while i > 0 && tables::scalefactor(i) < peak {
i -= 1;
}
while i < 62 && tables::scalefactor(i + 1) >= peak {
i += 1;
}
i
}
/// Which scalefactors of a subband's three parts are sent (`scfsi`, §2.4.1.6) and what they are.
fn share(sf: [u32; 3]) -> (u32, [u32; 3]) {
let near = |a: u32, b: u32| a.abs_diff(b) <= 1;
let [a, b, c] = sf;
if near(a, b) && near(b, c) && near(a, c) {
let m = a.min(b).min(c);
(2, [m, m, m])
} else if near(a, b) {
let m = a.min(b);
(1, [m, m, c])
} else if near(b, c) {
let m = b.min(c);
(3, [a, m, m])
} else {
(0, sf)
}
}
/// Scalefactors sent for an `scfsi` class.
fn scalefactors_sent(scfsi: u32) -> u64 {
match scfsi {
0 => 3,
2 => 1,
_ => 2,
}
}
/// Bits of the 12 granules of samples in a subband with `steps` quantization steps.
fn sample_bits(steps: u16) -> u64 {
12 * match tables::grouping(steps) {
Some(bits) => u64::from(bits),
None => 3 * u64::from((u32::from(steps) + 1).trailing_zeros()),
}
}
/// What the encoder decided for one channel of a frame.
#[derive(Clone)]
struct ChannelPlan {
/// The allocation value (index into the table's row) per subband.
alloc: [usize; SUBBANDS],
/// `scfsi` per subband.
scfsi: [u32; SUBBANDS],
/// The scalefactor index of each part of each subband, after sharing.
sf: [[u32; 3]; SUBBANDS],
/// Mean square of each subband's samples.
energy: [f32; SUBBANDS],
}
/// A Layer II encoder. Feed planar `f32` samples (full scale ±1) to [`Encoder::encode`]; it
/// returns whole frames as they are completed. [`Encoder::flush`] pads the end with silence and
/// returns the rest.
///
/// ```
/// use craft_audio::mpa::encoder::{Config, DELAY, Encoder};
///
/// let left: Vec<f32> = (0..48_000).map(|i| (i as f32 * 0.05).sin() * 0.5).collect();
/// let right = left.clone();
/// let mut enc = Encoder::new(Config::cbr(48_000, 2, 192))?;
/// let mut mp2 = enc.encode(&[&left, &right]); // whole frames as they complete
/// mp2.extend(enc.flush()); // pads with silence to the last input sample
/// assert_eq!(mp2.len() % 576, 0); // 192 kbit/s at 48 kHz: 576 bytes per frame
/// assert_eq!(DELAY, 481); // a decoder's output lags the input by this many samples
/// # Ok::<(), craft_audio::mpa::encoder::EncodeError>(())
/// ```
pub struct Encoder {
cfg: Config,
lsf: bool,
sr_index: u32,
br_index: u32,
table: AllocTable,
sblimit: usize,
/// The masking offset floor per subband (power), from the threshold in quiet.
ath: [f32; SUBBANDS],
poly: Vec<Polyphase>,
/// Buffered input per channel, and how much of it is consumed.
input: Vec<Vec<f32>>,
consumed: usize,
/// Remainder accumulator for the padding slot (44.1 / 22.05 kHz).
pad_acc: u64,
samples_in: u64,
frames: u64,
}
impl Encoder {
/// An encoder for `cfg`, or the setting it cannot carry.
pub fn new(cfg: Config) -> EncodeResult<Encoder> {
let lsf = is_lsf(cfg.sample_rate).ok_or(EncodeError::SampleRate(cfg.sample_rate))?;
if !(1..=2).contains(&cfg.channels) {
return Err(EncodeError::Channels(cfg.channels));
}
let bad = EncodeError::Bitrate { kbps: cfg.bitrate_kbps, rate: cfg.sample_rate, channels: cfg.channels };
if !bitrates(cfg.sample_rate, cfg.channels).contains(&cfg.bitrate_kbps) {
return Err(bad);
}
let (rates, bitrate_table): (&[u32; 3], &[u32; 15]) =
if lsf { (&[22_050, 24_000, 16_000], &tables::BITRATES_LSF_L23) } else { (&tables::SAMPLE_RATES, &tables::BITRATES_MPEG1_L2) };
let sr_index = rates.iter().position(|&r| r == cfg.sample_rate).ok_or(EncodeError::SampleRate(cfg.sample_rate))?;
let br_index = bitrate_table.iter().position(|&b| b == cfg.bitrate_kbps).ok_or(bad)?;
let per_channel = cfg.bitrate_kbps / cfg.channels as u32;
let table = AllocTable::select(lsf, cfg.sample_rate, per_channel);
let sblimit = table.sblimit().min(SUBBANDS);
let mut ath = [0f32; SUBBANDS];
for (sb, a) in ath.iter_mut().enumerate() {
let centre = (sb as f64 + 0.5) * f64::from(cfg.sample_rate) / 64.0;
// a full-scale sine has a mean square of 1/2 and plays back at about 96 dB SPL
*a = (0.5 * 10f64.powf((ath_db(centre) - 96.0) / 10.0)) as f32;
}
Ok(Encoder {
cfg,
lsf,
sr_index: sr_index as u32,
br_index: br_index as u32,
table,
sblimit,
ath,
poly: vec![Polyphase::new(); cfg.channels],
input: vec![Vec::new(); cfg.channels],
consumed: 0,
pad_acc: 0,
samples_in: 0,
frames: 0,
})
}
/// The settings.
pub fn config(&self) -> &Config {
&self.cfg
}
/// Samples per channel in a frame: 1152.
pub fn frame_samples(&self) -> usize {
FRAME_SAMPLES
}
/// Samples by which a standard decoder's output lags the input.
pub fn delay(&self) -> u32 {
DELAY
}
/// Frames written so far.
pub fn frames(&self) -> u64 {
self.frames
}
/// Encode planar samples (one slice per channel; a missing channel is silence, extra ones
/// are ignored, every channel takes the first channel's length). Returns the completed frames.
pub fn encode(&mut self, planar: &[&[f32]]) -> Vec<u8> {
let n = planar.first().map_or(0, |p| p.len());
for (c, buf) in self.input.iter_mut().enumerate() {
let src = planar.get(c).copied().unwrap_or(&[]);
buf.extend((0..n).map(|i| src.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0)));
}
self.samples_in = self.samples_in.saturating_add(n as u64);
let mut out = Vec::new();
self.drain(&mut out);
out
}
/// Encode the buffered rest padded with silence, plus enough silence that a decoder outputs
/// every input sample, and return the remaining frames.
pub fn flush(&mut self) -> Vec<u8> {
let fs = FRAME_SAMPLES as u64;
let needed = if self.samples_in == 0 { self.frames } else { self.samples_in.saturating_add(u64::from(DELAY)).div_ceil(fs) };
let have = self.input.first().map_or(0, |b| b.len().saturating_sub(self.consumed));
let want = (needed.saturating_sub(self.frames) as usize).saturating_mul(FRAME_SAMPLES);
if want > have {
for buf in &mut self.input {
buf.resize(self.consumed + want, 0.0);
}
}
let mut out = Vec::new();
self.drain(&mut out);
self.input.iter_mut().for_each(Vec::clear);
self.consumed = 0;
out
}
/// Encode every whole frame of buffered input.
fn drain(&mut self, out: &mut Vec<u8>) {
while self.input.first().is_some_and(|b| b.len() - self.consumed >= FRAME_SAMPLES) {
let mut sub = vec![[[0f32; SUBBANDS]; 36]; self.cfg.channels];
for (ch, slots) in sub.iter_mut().enumerate() {
let (Some(buf), Some(poly)) = (self.input.get(ch), self.poly.get_mut(ch)) else { continue };
let frame = buf.get(self.consumed..self.consumed + FRAME_SAMPLES).unwrap_or(&[]);
for (slot, chunk) in slots.iter_mut().zip(frame.as_chunks::<32>().0) {
poly.filter(chunk, slot);
}
}
self.consumed += FRAME_SAMPLES;
self.write_frame(&sub, out);
self.frames += 1;
}
// keep the buffer small
if self.consumed >= 1 << 16 {
for buf in &mut self.input {
buf.drain(..self.consumed);
}
self.consumed = 0;
}
}
/// The scalefactors and energies of a channel's 36 time slots.
fn analyse(&self, slots: &[[f32; SUBBANDS]; 36]) -> ChannelPlan {
let mut plan = ChannelPlan { alloc: [0; SUBBANDS], scfsi: [0; SUBBANDS], sf: [[62; 3]; SUBBANDS], energy: [0.0; SUBBANDS] };
for sb in 0..self.sblimit {
let mut sf = [62u32; 3];
for (part, s) in sf.iter_mut().enumerate() {
let peak = slots[12 * part..12 * part + 12].iter().map(|slot| slot[sb].abs()).fold(0f32, f32::max);
*s = scalefactor_index(peak);
}
(plan.scfsi[sb], plan.sf[sb]) = share(sf);
plan.energy[sb] = slots.iter().map(|slot| slot[sb] * slot[sb]).sum::<f32>() / 36.0;
}
plan
}
/// Choose the allocation of every subband of every channel with the bits the frame has.
fn allocate(&self, plans: &mut [ChannelPlan], mut bits_left: i64) {
let nch = plans.len();
// power the quantization noise of each subband may have before it is audible: a spread
// of the band energies, never below the threshold in quiet
let mut mask = vec![[0f32; SUBBANDS]; nch];
for (m, plan) in mask.iter_mut().zip(plans.iter()) {
for sb in 0..self.sblimit {
let mut level = self.ath[sb];
for j in 0..self.sblimit {
let atten_db = 14.0 + 20.0 * sb.abs_diff(j) as f32;
level = level.max(plan.energy[j] * 10f32.powf(-atten_db / 10.0));
}
m[sb] = level;
}
}
// the fixed cost: every subband's allocation field
for sb in 0..self.sblimit {
bits_left -= (nch * self.table.row(sb).len().trailing_zeros() as usize) as i64;
}
// the noise a subband has with allocation `a`: dropped, or the mean over its parts
let noise = |plan: &ChannelPlan, sb: usize, a: usize| -> f32 {
let row = self.table.row(sb);
let steps = row.get(a).copied().unwrap_or(0);
if steps == 0 {
return plan.energy[sb];
}
let mean_sf2 = plan.sf[sb].iter().map(|&i| tables::scalefactor(i).powi(2)).sum::<f32>() / 3.0;
(quantization_noise(steps) * mean_sf2).min(plan.energy[sb])
};
let cost = |plan: &ChannelPlan, sb: usize, a: usize| -> i64 {
let row = self.table.row(sb);
let step = |a: usize| row.get(a).copied().unwrap_or(0);
let (from, to) = (step(a), step(a + 1));
let mut bits = sample_bits(to) as i64 - if from == 0 { 0 } else { sample_bits(from) as i64 };
if from == 0 {
bits += 2 + 6 * scalefactors_sent(plan.scfsi[sb]) as i64;
}
bits
};
let mut blocked = vec![[false; SUBBANDS]; nch];
loop {
// the subband whose noise is furthest above its mask
let mut best: Option<(usize, usize, f32)> = None;
for (ch, plan) in plans.iter().enumerate() {
for sb in 0..self.sblimit {
let a = plan.alloc[sb];
if a + 1 >= self.table.row(sb).len() || blocked[ch][sb] || plan.energy[sb] <= 0.0 {
continue;
}
let ratio = noise(plan, sb, a) / mask[ch][sb].max(1e-20);
if ratio > 1e-3 && best.is_none_or(|(_, _, r)| ratio > r) {
best = Some((ch, sb, ratio));
}
}
}
let Some((ch, sb, _)) = best else { break };
let plan = &mut plans[ch];
let c = cost(plan, sb, plan.alloc[sb]);
if c <= bits_left {
bits_left -= c;
plan.alloc[sb] += 1;
} else {
blocked[ch][sb] = true;
}
}
}
fn write_frame(&mut self, sub: &[[[f32; SUBBANDS]; 36]], out: &mut Vec<u8>) {
let nch = self.cfg.channels;
// frame length: 144 bytes per kbit/s over the sampling rate, plus a slot when the
// remainder has added up to one
let rate = u64::from(self.cfg.sample_rate);
let exact = 144 * u64::from(self.cfg.bitrate_kbps) * 1000;
self.pad_acc += exact % rate;
let pad = self.pad_acc >= rate;
if pad {
self.pad_acc -= rate;
}
let frame_bytes = (exact / rate) as usize + usize::from(pad);
let mut plans: Vec<ChannelPlan> = sub.iter().map(|s| self.analyse(s)).collect();
self.allocate(&mut plans, frame_bytes as i64 * 8 - 32);
let mut w = BitWriter::new();
w.write_bits(0xFFF, 12);
w.write_bits(u32::from(!self.lsf), 1);
w.write_bits(0b10, 2); // Layer II
w.write_bits(1, 1); // no CRC
w.write_bits(self.br_index, 4);
w.write_bits(self.sr_index, 2);
w.write_bits(u32::from(pad), 1);
w.write_bits(0, 1); // private
w.write_bits(if nch == 1 { 3 } else { 0 }, 2); // mono or stereo
w.write_bits(0, 2); // mode extension
w.write_bits(0, 1); // copyright
w.write_bits(1, 1); // original
w.write_bits(0, 2); // emphasis
for sb in 0..self.sblimit {
let nbal = self.table.row(sb).len().trailing_zeros();
for plan in &plans {
w.write_bits(plan.alloc[sb] as u32, nbal);
}
}
for sb in 0..self.sblimit {
for plan in &plans {
if plan.alloc[sb] != 0 {
w.write_bits(plan.scfsi[sb], 2);
}
}
}
for sb in 0..self.sblimit {
for plan in &plans {
if plan.alloc[sb] == 0 {
continue;
}
let [a, b, c] = plan.sf[sb];
match plan.scfsi[sb] {
0 => [a, b, c].iter().for_each(|&s| w.write_bits(s, 6)),
1 => [a, c].iter().for_each(|&s| w.write_bits(s, 6)),
2 => w.write_bits(a, 6),
_ => [a, b].iter().for_each(|&s| w.write_bits(s, 6)),
}
}
}
for gr in 0..12 {
let part = gr / 4;
for sb in 0..self.sblimit {
for (ch, plan) in plans.iter().enumerate() {
let a = plan.alloc[sb];
let steps = self.table.row(sb).get(a).copied().unwrap_or(0);
if steps == 0 {
continue;
}
let scale = tables::scalefactor(plan.sf[sb][part]);
let n = u32::from(steps);
let code = |k: usize| -> u32 {
let x = (sub[ch][3 * gr + k][sb] / scale).clamp(-1.0, 1.0);
// the reconstruction points are (2v + 1 - n) / n
((x * n as f32 + n as f32 - 1.0) / 2.0).round().clamp(0.0, (n - 1) as f32) as u32
};
let v = [code(0), code(1), code(2)];
match tables::grouping(steps) {
Some(bits) => w.write_bits(v[0] + n * v[1] + n * n * v[2], bits),
None => {
let nb = (n + 1).trailing_zeros();
v.iter().for_each(|&x| w.write_bits(x, nb));
}
}
}
}
}
let mut bytes = w.finish();
bytes.resize(frame_bytes, 0);
out.extend_from_slice(&bytes);
}
}
+18
View File
@@ -13,12 +13,30 @@
//! format (bit rate index 0, whose frame length is only known from the next sync word) and the
//! CRC (read, not checked, like most decoders).
//!
//! # Encoder (feature `mpa-encode`)
//!
//! [`encoder::Encoder`] writes Layer II streams, written from ISO/IEC 11172-3 (§2.4.1.6 bit stream
//! syntax, Annex B tables, Annex C encoding process) and ISO/IEC 13818-3.
//!
//! - Constant bit rate: 32-192 kbit/s mono and 64-384 kbit/s stereo at 32 / 44.1 / 48 kHz (the
//! rate and mode pairs of Table 3-B.2), 8-160 kbit/s at 16 / 22.05 / 24 kHz. Mono, or stereo with
//! each channel allocated on its own (no joint stereo, no dual channel).
//! - The polyphase analysis filterbank of Annex C.1.3 (shared with the Layer III encoder), a
//! scalefactor per 12 samples with the `scfsi` sharing of §2.4.1.6, and a bit allocation chosen by
//! spending the frame's bits where the quantization noise is furthest above a simple masking
//! estimate (the band energies spread over the neighbouring subbands, never below the threshold
//! in quiet). It is not one of the psychoacoustic models of Annex D.
//! - Output: frames only, no CRC, no ID3 tag. Frames written one after another are a playable
//! `.mp2` file. A decoder's output lags the input by [`encoder::DELAY`] samples.
//!
//! From FilmCraft's `filmcraft-mpa` (storytold/filmcraft@8fda2f2). Public items keep their names, so
//! FilmCraft can re-export this module.
// Index loops follow the specification's pseudo-code (FilmCraft allows this lint workspace-wide).
#![allow(clippy::needless_range_loop)]
#[cfg(feature = "mpa-encode")]
pub mod encoder;
pub(crate) mod tables;
use craft_media::bitstream::BitReader;
+192
View File
@@ -0,0 +1,192 @@
//! Sierra VMD sound decoder (feature `vmd-decode`): the 8-bit PCM and 16-bit DPCM sound of VMD
//! (Video and Music Data) files, as in Sierra's and Coktel Vision's 1990s games.
//!
//! Clean-room, from the public format description at <https://wiki.multimedia.cx/index.php/VMD>
//! ("Description of the Sierra Video and Music Data (VMD) Format", Mike Melanson and Vladimir
//! Gneushev). The description gives the coding but not the size of a block; the sizes here are
//! what ffmpeg was seen to expect of files made by this crate's tests:
//!
//! | Sound | Bytes in a block of `n` samples a channel |
//! |---|---|
//! | 8-bit | `n` for each channel, interleaved |
//! | 16-bit | 2 for each channel's first sample, then one code for each further sample, interleaved |
//!
//! The header's frame length is `n`, except in old-style stereo (audio flag 0x8000), where it
//! counts both channels. Old-style 16-bit stereo blocks begin with their first samples like the
//! others, which is what ffmpeg reads; the description says they carry the last block's samples
//! over instead. No such file was at hand to settle it.
//!
//! A [`Decoder`] is made from the 816-byte file header. [`Decoder::decode`] takes a sound
//! frame's flags (from its record in the file's table of contents; `craft_media::vmd` reads it)
//! and its data, and returns interleaved `i16` samples: one block of sound or silence, or, for a
//! frame with a silence mask (the first sound frame of a file), several. 8-bit samples are widened to 16 bits. Blocks do not depend
//! on each other, so decoding can start at any frame.
//!
//! 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 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)]
/// Bytes of the VMD file header a [`Decoder`] is made from.
pub const HEADER_LEN: usize = 816;
/// Errors from decoding VMD sound.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
/// The header or a frame is not valid.
#[error("invalid VMD sound: {0}")]
Invalid(&'static str),
/// Valid, but not something this decoder handles.
#[error("unsupported VMD sound: {0}")]
Unsupported(&'static str),
}
/// The steps of the 16-bit coding: a code's low seven bits pick one, its top bit the sign.
const STEPS: [u16; 128] = [
0, 8, 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 256, 272, 288, 304, 320, 336, 352, 368, 384, 400, 416, 432, 448, 464,
480, 496, 512, 520, 528, 536, 544, 552, 560, 568, 576, 584, 592, 600, 608, 616, 624, 632, 640, 648, 656, 664, 672, 680, 688, 696, 704, 712, 720,
728, 736, 744, 752, 760, 768, 776, 784, 792, 800, 808, 816, 824, 832, 840, 848, 856, 864, 872, 880, 888, 896, 904, 912, 920, 928, 936, 944, 952,
960, 968, 976, 984, 992, 1000, 1008, 1016, 1024, 1088, 1152, 1216, 1280, 1344, 1408, 1472, 1536, 1600, 1664, 1728, 1792, 1856, 1920, 1984, 2048,
2304, 2560, 2816, 3072, 3328, 3584, 3840, 4096, 5120, 6144, 7168, 8192, 12288, 16384,
];
/// A VMD sound decoder.
#[derive(Clone, Debug)]
pub struct Decoder {
sample_rate: u32,
channels: usize,
sixteen_bit: bool,
/// Samples of one block, all channels counted.
block_total: usize,
}
impl Decoder {
/// A decoder for the file whose header is `header` (its first 816 bytes; more are ignored).
pub fn new(header: &[u8]) -> Result<Decoder, Error> {
let h = header.get(..HEADER_LEN).ok_or(Error::Invalid("the header is shorter than 816 bytes"))?;
let u16_at = |at: usize| u16::from_le_bytes([h[at], h[at + 1]]);
if usize::from(u16_at(0)) != HEADER_LEN - 2 {
return Err(Error::Invalid("not a VMD header"));
}
if u16_at(16) & 0x1000 == 0 || u16_at(804) == 0 {
return Err(Error::Invalid("the file has no sound"));
}
let flags = u16_at(810);
if flags & 0x10 != 0 {
return Err(Error::Unsupported("IMA ADPCM sound"));
}
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_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_total })
}
/// Samples a second.
pub fn sample_rate(&self) -> u32 {
self.sample_rate
}
/// 1 or 2.
pub fn channels(&self) -> usize {
self.channels
}
/// Bits a sample in the file: 8 (PCM) or 16 (DPCM). The decoder returns `i16` for both.
pub fn bits(&self) -> u8 {
if self.sixteen_bit { 16 } else { 8 }
}
/// Samples of one block for each channel.
pub fn block_samples(&self) -> usize {
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_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
/// frame data. Returns interleaved samples, [`Decoder::block_samples`] for each channel and
/// block.
///
/// - flags 1: one block of sound (every whole block, if the frame holds more);
/// - flags 2: a 32-bit mask, then blocks of sound: the sound a player loads ahead at the
/// start of a file. From bit 0 up, a set bit is a block of silence and a clear bit the next
/// block of data, while there is one. ffmpeg plays the silent blocks first instead;
/// the order here is the description's;
/// - flags 3: one block of silence.
///
/// 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<Vec<i16>, Error> {
let mut out = Vec::new();
match flags {
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)?;
let size = self.block_bytes();
if size > 0 {
for more in data[size..].chunks_exact(size) {
self.block(more, &mut out)?;
}
}
}
2 => {
let (mask, mut data) = data.split_first_chunk::<4>().ok_or(Error::Invalid("the silence mask is cut short"))?;
let mask = u32::from_le_bytes(*mask);
// bit by bit: a set bit is a silent block, a clear one takes the next block of data
// while there is one. The header's buffer count is not needed: game files hold
// one block fewer than it says.
for i in 0..32 {
if mask >> i & 1 == 1 {
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()..];
}
}
}
_ => return Err(Error::Unsupported("unknown sound frame flags")),
}
Ok(out)
}
/// Decode the block at the start of `data` onto `out`.
fn block(&self, data: &[u8], out: &mut Vec<i16>) -> Result<(), Error> {
let data = data.get(..self.block_bytes()).ok_or(Error::Invalid("a block of sound is cut short"))?;
if !self.sixteen_bit {
out.extend(data.iter().map(|&b| (i16::from(b) - 0x80) << 8));
return Ok(());
}
// each channel's first sample as it is, then a signed step for each further sample
let mut last = [0i32; 2];
let Some((first, codes)) = data.split_at_checked(self.channels * 2) else { return Ok(()) };
for (ch, s) in first.as_chunks::<2>().0.iter().enumerate() {
last[ch] = i32::from(i16::from_le_bytes(*s));
out.push(last[ch] as i16);
}
for (i, &code) in codes.iter().enumerate() {
let ch = i % self.channels;
let step = i32::from(STEPS[usize::from(code & 0x7F)]);
last[ch] = (if code & 0x80 != 0 { last[ch] - step } else { last[ch] + step }).clamp(-32768, 32767);
out.push(last[ch] as i16);
}
Ok(())
}
}
+201
View File
@@ -0,0 +1,201 @@
//! ITU-T G.722 SB-ADPCM tests and FFmpeg oracle comparisons.
//!
//! Skipped when FFmpeg is not found, unless `CRAFT_MEDIA_REQUIRE_ORACLES=1` is set.
use craft_audio::g722::{Decoder, Encoder, Error, decode, decode_interleaved, encode, encode_interleaved};
use std::process::Command;
fn generate_signal(samples: usize, freq: f64) -> Vec<i16> {
(0..samples)
.map(|i| {
let t = i as f64 / 16000.0;
let val = (2.0 * std::f64::consts::PI * freq * t).sin() * 10000.0;
val as i16
})
.collect()
}
#[test]
fn test_silence_roundtrip() {
let pcm = vec![0i16; 640];
let encoded = encode(&pcm).expect("encode");
assert_eq!(encoded.len(), 320);
let decoded = decode(&encoded).expect("decode");
assert_eq!(decoded.len(), 640);
for &s in &decoded[40..] {
assert!(s.abs() <= 6, "silence sample out of bounds: {s}");
}
}
#[test]
fn test_sine_wave_roundtrip_fidelity() {
let pcm = generate_signal(1600, 1000.0);
let encoded = encode(&pcm).expect("encode");
let decoded = decode(&encoded).expect("decode");
assert_eq!(decoded.len(), pcm.len());
// Compute normalized cross-correlation accounting for filter group delay (approx 22 samples)
let delay = 22;
let mut num = 0.0;
let mut den_orig = 0.0;
let mut den_dec = 0.0;
for i in 0..(pcm.len() - delay) {
let o = pcm[i] as f64;
let d = decoded[i + delay] as f64;
num += o * d;
den_orig += o * o;
den_dec += d * d;
}
let corr = num / (den_orig.sqrt() * den_dec.sqrt());
assert!(corr > 0.98, "reconstructed sine wave correlation too low: {corr}");
}
#[test]
fn test_stereo_multichannel_roundtrip() {
let left = generate_signal(800, 440.0);
let right = generate_signal(800, 880.0);
let mut interleaved = Vec::with_capacity(1600);
for i in 0..800 {
interleaved.push(left[i]);
interleaved.push(right[i]);
}
let encoded = encode_interleaved(&interleaved, 2).expect("encode stereo");
assert_eq!(encoded.len(), 800);
let decoded = decode_interleaved(&encoded, 2).expect("decode stereo");
assert_eq!(decoded.len(), 1600);
}
#[test]
fn test_hostile_inputs_do_not_crash() {
let garbage = [0xFF, 0x00, 0xAA, 0x55, 0x12, 0x34, 0x89, 0xFE];
let decoded = decode(&garbage).expect("decode garbage");
assert_eq!(decoded.len(), 16);
assert_eq!(encode(&[1, 2, 3]), Err(Error::OddSampleCount(3)));
assert_eq!(decode_interleaved(&[0; 8], 0), Err(Error::InvalidChannels(0)));
assert_eq!(decode_interleaved(&[0; 8], 9), Err(Error::InvalidChannels(9)));
}
#[test]
fn test_encoder_and_decoder_reset() {
let mut enc = Encoder::new();
let mut dec = Decoder::new();
let pcm = generate_signal(200, 1000.0);
let mut out1 = Vec::new();
enc.encode(&pcm, &mut out1).expect("enc 1");
let mut dec1 = Vec::new();
dec.decode(&out1, &mut dec1).expect("dec 1");
enc.reset();
dec.reset();
let mut out2 = Vec::new();
enc.encode(&pcm, &mut out2).expect("enc 2");
let mut dec2 = Vec::new();
dec.decode(&out2, &mut dec2).expect("dec 2");
assert_eq!(out1, out2);
assert_eq!(dec1, dec2);
}
#[test]
fn test_ffmpeg_g722_oracle_encoder_and_decoder() {
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
let dir = craft_media_testkit::fixture_subdir("g722_oracle");
// 1. Generate test 1000 Hz tone at 16 kHz mono (800 samples = 0.05s)
let pcm = generate_signal(800, 1000.0);
let pcm_path = dir.join("input.s16le");
let mut pcm_bytes = Vec::with_capacity(pcm.len() * 2);
for &s in &pcm {
pcm_bytes.extend_from_slice(&s.to_le_bytes());
}
std::fs::write(&pcm_path, &pcm_bytes).expect("write pcm");
// 2. FFmpeg encodes the PCM to G.722
let ff_g722_path = dir.join("ffmpeg.g722");
let out = Command::new(&ff)
.args(["-y", "-f", "s16le", "-ar", "16000", "-ac", "1", "-i"])
.arg(&pcm_path)
.args(["-f", "g722"])
.arg(&ff_g722_path)
.output()
.expect("ffmpeg encode");
assert!(out.status.success(), "ffmpeg encode failed: {}", String::from_utf8_lossy(&out.stderr));
let ff_g722_bytes = std::fs::read(&ff_g722_path).expect("read ff g722");
// 3. FFmpeg decodes its own G.722 back to PCM
let ff_pcm_back_path = dir.join("ff_back.s16le");
let out = Command::new(&ff)
.args(["-y", "-f", "g722", "-i"])
.arg(&ff_g722_path)
.args(["-f", "s16le", "-ar", "16000", "-ac", "1"])
.arg(&ff_pcm_back_path)
.output()
.expect("ffmpeg decode");
assert!(out.status.success(), "ffmpeg decode failed: {}", String::from_utf8_lossy(&out.stderr));
let ff_back_bytes = std::fs::read(&ff_pcm_back_path).expect("read ff back pcm");
let ff_back_samples: Vec<i16> = ff_back_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect();
// 4. Our decoder decodes FFmpeg's G.722 stream
let our_decoded_from_ff = decode(&ff_g722_bytes).expect("our decode of ff stream");
assert_eq!(our_decoded_from_ff.len(), ff_back_samples.len());
// Verify sample-by-sample match against FFmpeg decoder: within ±1 LSB tolerance
let mut max_diff: i32 = 0;
for (i, (&ours, &theirs)) in our_decoded_from_ff.iter().zip(&ff_back_samples).enumerate() {
let diff = (ours as i32 - theirs as i32).abs();
if diff > max_diff {
max_diff = diff;
}
assert!(diff <= 1, "sample {i} mismatch between our decoder and FFmpeg decoder: ours {ours}, theirs {theirs}");
}
assert!(max_diff <= 1, "max diff {max_diff} exceeded tolerance");
// 5. Our encoder encodes the PCM to G.722
let our_encoded_bytes = encode(&pcm).expect("our encode");
let our_g722_path = dir.join("ours.g722");
std::fs::write(&our_g722_path, &our_encoded_bytes).expect("write our g722");
// 6. FFmpeg decodes our encoded G.722 stream
let our_decoded_by_ff_path = dir.join("our_by_ff.s16le");
let out = Command::new(&ff)
.args(["-y", "-f", "g722", "-i"])
.arg(&our_g722_path)
.args(["-f", "s16le", "-ar", "16000", "-ac", "1"])
.arg(&our_decoded_by_ff_path)
.output()
.expect("ffmpeg decode of our stream");
assert!(out.status.success(), "ffmpeg decode of our stream failed: {}", String::from_utf8_lossy(&out.stderr));
let our_by_ff_bytes = std::fs::read(&our_decoded_by_ff_path).expect("read our by ff pcm");
let our_by_ff_samples: Vec<i16> = our_by_ff_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect();
// Verify that our decoder and FFmpeg decoder produce identical samples on our stream
let our_decoded_from_ours = decode(&our_encoded_bytes).expect("our decode of our stream");
assert_eq!(our_decoded_from_ours.len(), our_by_ff_samples.len());
let mut max_diff_ours: i32 = 0;
for (i, (&ours, &theirs)) in our_decoded_from_ours.iter().zip(&our_by_ff_samples).enumerate() {
let diff = (ours as i32 - theirs as i32).abs();
if diff > max_diff_ours {
max_diff_ours = diff;
}
assert!(diff <= 1, "sample {i} on our stream mismatch between our decoder and FFmpeg decoder: ours {ours}, theirs {theirs}");
}
assert!(max_diff_ours <= 1, "max diff {max_diff_ours} exceeded tolerance");
// Also check high fidelity correlation of our stream decoded by FFmpeg to original signal
let delay = 22;
let mut num = 0.0;
let mut den_orig = 0.0;
let mut den_dec = 0.0;
for i in 0..(pcm.len() - delay) {
let o = pcm[i] as f64;
let d = our_by_ff_samples[i + delay] as f64;
num += o * d;
den_orig += o * o;
den_dec += d * d;
}
let corr = num / (den_orig.sqrt() * den_dec.sqrt());
assert!(corr > 0.98, "correlation of our encoded stream decoded by FFmpeg is too low: {corr}");
}
+228
View File
@@ -0,0 +1,228 @@
//! The Layer II encoder (feature `mpa-encode`): every frame has the header and size its settings
//! give and decodes with our decoder; ffmpeg as an external decoder (skipped without ffmpeg, a
//! failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`) decodes the stream without a complaint, to the
//! right length, and its output, aligned by [`DELAY`], matches the input within a signal-to-noise
//! ratio per bit rate. The bounds sit well under what the encoder reaches today; white noise loses
//! the subbands above the table's last one (a sixth of it at 48 kHz), so its bound is low.
use std::path::Path;
use std::process::{Command, Stdio};
use craft_audio::mpa::encoder::{Config, DELAY, EncodeError, Encoder, bitrates, nearest_bitrate};
use craft_audio::mpa::{Decoder, Mode, Version, parse_header};
fn chords(rate: u32, n: usize, detune: f32) -> Vec<f32> {
let f = [220.0, 277.18, 329.63, 440.0, 1318.5, 3520.0];
let a = [0.2, 0.15, 0.12, 0.1, 0.05, 0.02];
(0..n)
.map(|i| {
let t = i as f32 / rate as f32;
f.iter().zip(a).map(|(f, a)| a * (2.0 * std::f32::consts::PI * f * (1.0 + detune) * t).sin()).sum::<f32>()
})
.collect()
}
fn noise(n: usize, amp: f32, seed: u64) -> Vec<f32> {
let mut s = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
(0..n)
.map(|_| {
s ^= s << 13;
s ^= s >> 7;
s ^= s << 17;
((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * amp
})
.collect()
}
fn encode(cfg: Config, input: &[Vec<f32>], chunk: usize) -> Vec<u8> {
let mut enc = Encoder::new(cfg).expect("encoder");
let mut out = Vec::new();
let n = input[0].len();
let mut pos = 0;
while pos < n {
let end = (pos + chunk).min(n);
let planes: Vec<&[f32]> = input.iter().map(|c| &c[pos..end]).collect();
out.extend(enc.encode(&planes));
pos = end;
}
out.extend(enc.flush());
out
}
/// Split a stream into frames by its headers; every header must be one the settings give.
fn frames<'a>(bytes: &'a [u8], cfg: &Config) -> Vec<&'a [u8]> {
let mut out = Vec::new();
let mut pos = 0;
while pos < bytes.len() {
let h = parse_header(&bytes[pos..]).unwrap_or_else(|e| panic!("frame {} at byte {pos}: {e}", out.len()));
assert_eq!(h.layer, 2);
assert_eq!(h.version, if cfg.sample_rate >= 32_000 { Version::Mpeg1 } else { Version::Mpeg2 });
assert_eq!((h.sample_rate, h.bitrate_kbps), (cfg.sample_rate, cfg.bitrate_kbps));
assert_eq!(h.mode, if cfg.channels == 1 { Mode::Mono } else { Mode::Stereo });
assert!(!h.crc);
out.push(&bytes[pos..pos + h.frame_bytes]);
pos += h.frame_bytes;
}
assert_eq!(pos, bytes.len(), "the stream ends on a frame boundary");
out
}
fn snr(input: &[f32], dec: &[f32]) -> f64 {
let (mut s, mut n) = (0f64, 0f64);
for (a, b) in input.iter().zip(dec) {
s += f64::from(*a) * f64::from(*a);
n += f64::from(a - b) * f64::from(a - b);
}
10.0 * (s / n.max(1e-30)).log10()
}
struct Case {
name: &'static str,
rate: u32,
channels: usize,
kbps: u32,
signal: fn(u32, usize, usize) -> Vec<f32>,
min_snr: f64,
}
fn sig_chords(rate: u32, n: usize, c: usize) -> Vec<f32> {
chords(rate, n, 0.003 * c as f32)
}
fn sig_noise(_rate: u32, n: usize, c: usize) -> Vec<f32> {
noise(n, 0.25, 11 + c as u64)
}
const CASES: &[Case] = &[
Case { name: "chords", rate: 48_000, channels: 2, kbps: 192, signal: sig_chords, min_snr: 30.0 },
Case { name: "chords", rate: 44_100, channels: 2, kbps: 128, signal: sig_chords, min_snr: 25.0 },
Case { name: "chords", rate: 44_100, channels: 1, kbps: 64, signal: sig_chords, min_snr: 25.0 },
Case { name: "chords", rate: 32_000, channels: 2, kbps: 96, signal: sig_chords, min_snr: 20.0 },
Case { name: "chords", rate: 22_050, channels: 2, kbps: 64, signal: sig_chords, min_snr: 20.0 },
Case { name: "chords", rate: 24_000, channels: 1, kbps: 32, signal: sig_chords, min_snr: 18.0 },
Case { name: "noise", rate: 48_000, channels: 2, kbps: 384, signal: sig_noise, min_snr: 4.0 },
Case { name: "noise", rate: 44_100, channels: 2, kbps: 256, signal: sig_noise, min_snr: 4.0 },
];
fn inputs(c: &Case, n: usize) -> Vec<Vec<f32>> {
(0..c.channels).map(|ch| (c.signal)(c.rate, n, ch)).collect()
}
#[test]
fn frames_have_the_size_and_header_their_settings_give_and_decode_with_our_decoder() {
for c in CASES {
let n = c.rate as usize * 2 + 777;
let cfg = Config::cbr(c.rate, c.channels, c.kbps);
let bytes = encode(cfg, &inputs(c, n), 1000);
let frames = frames(&bytes, &cfg);
// every input sample and the filter delay fit in the frames, and no more than one frame more
let covered = frames.len() * 1152;
assert!(covered >= n + DELAY as usize && covered < n + DELAY as usize + 1152, "{}: {} frames for {n} samples", c.name, frames.len());
// 144 kbit/s-slots per frame, the padding slots adding up to the exact rate
let nominal = f64::from(c.kbps) * 125.0 * covered as f64 / f64::from(c.rate);
assert!((bytes.len() as f64 - nominal).abs() < 1.0 + f64::from(c.rate) / 1000.0, "{}: {} bytes against {nominal}", c.name, bytes.len());
let mut dec = Decoder::new();
let mut out = vec![Vec::new(); c.channels];
for f in frames {
let frame = dec.decode(f).unwrap_or_else(|e| panic!("{}: {e}", c.name));
for (o, ch) in out.iter_mut().zip(frame.channels) {
o.extend(ch);
}
}
let d = DELAY as usize;
for (ch, input) in inputs(c, n).iter().enumerate() {
let s = snr(input, &out[ch][d..d + n]);
println!("{:<7} {:>5} Hz {}ch {:>3} kbps: SNR {s:.2} dB (our decoder)", c.name, c.rate, c.channels, c.kbps);
assert!(s >= c.min_snr, "{} {} Hz {}ch {} kbps: SNR {s:.2} dB under {}", c.name, c.rate, c.channels, c.kbps, c.min_snr);
}
}
}
#[test]
fn the_stream_does_not_depend_on_how_the_input_is_chunked() {
let c = &CASES[1];
let n = 44_100 + 333;
let cfg = Config::cbr(c.rate, c.channels, c.kbps);
let input = inputs(c, n);
let whole = encode(cfg, &input, n);
for chunk in [1, 7, 1152, 5000] {
assert_eq!(encode(cfg, &input, chunk), whole, "chunk {chunk}");
}
}
#[test]
fn silence_and_nothing_encode_to_valid_frames() {
let cfg = Config::cbr(48_000, 2, 128);
let silent = vec![vec![0f32; 5000]; 2];
let bytes = encode(cfg, &silent, 5000);
let fs = frames(&bytes, &cfg);
let mut dec = Decoder::new();
for f in fs {
let frame = dec.decode(f).expect("decode");
assert!(frame.channels.iter().flatten().all(|v| v.abs() < 1e-6));
}
assert!(Encoder::new(cfg).expect("encoder").flush().is_empty(), "no input, no frames");
}
#[test]
fn hostile_samples_are_tamed() {
let cfg = Config::cbr(44_100, 2, 192);
let mut x = vec![0f32; 4000];
for (i, v) in x.iter_mut().enumerate() {
*v = [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30, 3.0, 0.5][i % 7];
}
let bytes = encode(cfg, &[x.clone(), x], 4000);
let mut dec = Decoder::new();
for f in frames(&bytes, &cfg) {
dec.decode(f).expect("decode");
}
}
#[test]
fn settings_that_cannot_be_carried_are_refused() {
assert_eq!(Encoder::new(Config::cbr(44_000, 2, 128)).err(), Some(EncodeError::SampleRate(44_000)));
assert_eq!(Encoder::new(Config::cbr(44_100, 3, 128)).err(), Some(EncodeError::Channels(3)));
assert_eq!(Encoder::new(Config::cbr(44_100, 0, 128)).err(), Some(EncodeError::Channels(0)));
// ISO/IEC 11172-3 allows neither 32 kbit/s for two channels nor 224 for one
assert!(matches!(Encoder::new(Config::cbr(44_100, 2, 32)), Err(EncodeError::Bitrate { .. })));
assert!(matches!(Encoder::new(Config::cbr(44_100, 1, 224)), Err(EncodeError::Bitrate { .. })));
assert!(matches!(Encoder::new(Config::cbr(44_100, 2, 130)), Err(EncodeError::Bitrate { .. })));
assert_eq!(bitrates(44_100, 1).len(), 10);
assert_eq!(bitrates(22_050, 2).first(), Some(&8));
assert!(bitrates(8_000, 2).is_empty());
assert_eq!(nearest_bitrate(44_100, 2, 100), Some(96));
assert_eq!(nearest_bitrate(44_100, 2, 1), Some(64));
assert_eq!(nearest_bitrate(8_000, 2, 100), None);
}
fn ffmpeg_decode(ff: &Path, path: &Path, channels: usize) -> (Vec<Vec<f32>>, String) {
let out = Command::new(ff)
.args(["-v", "error", "-nostdin", "-i"])
.arg(path)
.args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
.stdin(Stdio::null())
.output()
.expect("run ffmpeg");
let samples: Vec<f32> = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
let planar = (0..channels).map(|c| samples.iter().skip(c).step_by(channels).copied().collect()).collect();
(planar, String::from_utf8_lossy(&out.stderr).into_owned())
}
#[test]
fn ffmpeg_decodes_our_streams_to_the_input() {
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
let dir = craft_media_testkit::fixture_subdir("mp2enc");
for c in CASES {
let n = c.rate as usize * 2 + 777;
let input = inputs(c, n);
let bytes = encode(Config::cbr(c.rate, c.channels, c.kbps), &input, 1000);
let path = dir.join(format!("{}_{}_{}ch_{}k.mp2", c.name, c.rate, c.channels, c.kbps));
std::fs::write(&path, &bytes).expect("write");
let (dec, err) = ffmpeg_decode(&ff, &path, c.channels);
assert!(err.trim().is_empty(), "{}: ffmpeg reported: {err}", path.display());
let d = DELAY as usize;
assert!(dec[0].len() >= n + d, "{}: decoded {} samples, need {}", c.name, dec[0].len(), n + d);
let s = (0..c.channels).map(|ch| snr(&input[ch], &dec[ch][d..d + n])).sum::<f64>() / c.channels as f64;
println!("{:<7} {:>5} Hz {}ch {:>3} kbps: SNR {s:.2} dB (ffmpeg)", c.name, c.rate, c.channels, c.kbps);
assert!(s >= c.min_snr, "{} {} Hz {}ch {} kbps: SNR {s:.2} dB under {}", c.name, c.rate, c.channels, c.kbps, c.min_snr);
}
}
+280
View File
@@ -0,0 +1,280 @@
//! VMD sound decoder tests. ffmpeg reads VMD but cannot write it, so the files come from the
//! test kit's VMD writer. The decoder must return the samples that were packed, and the same
//! samples as ffmpeg (skipped without ffmpeg).
use std::process::Command;
use craft_audio::AudioError;
use craft_audio::vmd::{Decoder, Error};
use craft_media::vmd::{FrameKind, open};
use craft_media_testkit::hostile::Rng;
use craft_media_testkit::vmd::{Audio, Frame, Spec, build, dpcm_pack};
/// (frame length field, audio flags, channels, 16-bit): every layout the decoder handles.
const FORMATS: [(i16, u16, usize, bool); 6] =
[(50, 0, 1, false), (50, 0x200, 2, false), (50, 0x8000, 2, false), (-50, 0, 1, true), (-50, 0x200, 2, true), (-50, 0x8000, 2, true)];
fn spec(frame_length: i16, flags: u16) -> Spec {
let mut spec = Spec::new(4, 4);
spec.audio = Some(Audio { sample_rate: 22050, frame_length, buffers: 5, flags });
spec
}
fn decoder(frame_length: i16, flags: u16) -> Decoder {
Decoder::new(&build(&spec(frame_length, flags), &[])).unwrap()
}
/// One block of random sound: its bytes in the file and the samples it decodes to.
fn block(rng: &mut Rng, d: &Decoder) -> (Vec<u8>, Vec<i16>) {
let n = d.block_samples() * d.channels();
if d.bits() == 8 {
let bytes: Vec<u8> = (0..n).map(|_| rng.next_u64() as u8).collect();
let samples = bytes.iter().map(|&b| (i16::from(b) - 0x80) << 8).collect();
return (bytes, samples);
}
// a random walk, so that the steps are of every size
let mut last = [0i32; 2];
let samples: Vec<i16> = (0..n)
.map(|i| {
let bits = 1 + rng.below(15);
let step = rng.below(1 << bits) as i32 - (1 << (bits - 1));
let s = &mut last[i % d.channels()];
*s = (*s + step).clamp(-32768, 32767);
*s as i16
})
.collect();
dpcm_pack(&samples, d.channels())
}
/// A file of sound frames (with a small picture each, as ffmpeg expects video) and the samples
/// expected of it. The first frame is a mask frame: one silent block, then four of sound.
fn movie(seed: u64, frame_length: i16, flags: u16) -> (Vec<u8>, Vec<i16>) {
let spec = spec(frame_length, flags);
let d = decoder(frame_length, flags);
let mut rng = Rng(seed | 1);
let mut picture = vec![2u8];
picture.extend([9; 16]);
let silence = vec![0i16; d.block_samples() * d.channels()];
let mut want = Vec::new();
let mut blocks = Vec::new();
for n in 0..12 {
let sound = match n {
0 => {
let mut data = 1u32.to_le_bytes().to_vec();
want.extend_from_slice(&silence);
for _ in 0..4 {
let (bytes, samples) = block(&mut rng, &d);
data.extend_from_slice(&bytes);
want.extend_from_slice(&samples);
}
Frame::audio(2, data)
}
_ if rng.below(4) == 0 => {
want.extend_from_slice(&silence);
Frame::audio(3, vec![])
}
_ => {
let (bytes, samples) = block(&mut rng, &d);
want.extend_from_slice(&samples);
Frame::audio(1, bytes)
}
};
blocks.push(vec![sound, Frame::video([0, 0, 3, 3], false, picture.clone())]);
}
(build(&spec, &blocks), want)
}
fn decode_all(bytes: &[u8]) -> Vec<i16> {
let file = open(bytes).unwrap();
let d = Decoder::new(file.header_bytes()).unwrap();
let mut out = Vec::new();
for (i, frame) in file.frames.iter().enumerate() {
if let FrameKind::Audio { flags } = frame.kind {
out.extend(d.decode(flags, &file.read_frame(bytes, i).unwrap()).unwrap());
}
}
out
}
#[test]
fn decodes_the_samples_that_were_packed() {
for (i, (frame_length, flags, channels, sixteen)) in FORMATS.into_iter().enumerate() {
let d = decoder(frame_length, flags);
assert_eq!((d.channels(), d.bits(), d.sample_rate()), (channels, if sixteen { 16 } else { 8 }, 22050), "format {i}");
// old-style stereo counts both channels in the frame length
assert_eq!(d.block_samples(), if flags & 0x8000 != 0 { 25 } else { 50 }, "format {i}");
let (bytes, want) = movie(i as u64 + 1, frame_length, flags);
assert_eq!(want.len(), 16 * d.block_samples() * channels);
assert!(decode_all(&bytes) == want, "format {i}");
}
}
#[test]
fn matches_ffmpeg() {
let Some(ffmpeg) = craft_media_testkit::ffmpeg_or_skip("vmd sound oracle") else { return };
let dir = craft_media_testkit::private_dir("vmd-sound");
for (i, (frame_length, flags, ..)) in FORMATS.into_iter().enumerate() {
let (bytes, _) = movie(i as u64 + 1, frame_length, flags);
let path = dir.join(format!("sound{i}.vmd"));
std::fs::write(&path, &bytes).unwrap();
let out = Command::new(&ffmpeg).args(["-v", "error", "-i"]).arg(&path).args(["-vn", "-f", "s16le", "-"]).output().unwrap();
assert!(out.status.success() && out.stderr.is_empty(), "format {i}: ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
let theirs: Vec<i16> = out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect();
assert!(theirs == decode_all(&bytes), "format {i} differs from ffmpeg");
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn sixteen_bit_steps() {
// values ffmpeg gave for this block: the first sample, then signed steps from the table
let mut data = 1000i16.to_le_bytes().to_vec();
data.extend([1, 1, 1, 0x81, 0x81, 2, 3, 0x7F, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
let d = decoder(-20, 0);
assert_eq!(d.block_bytes(), 21);
assert_eq!(
d.decode(1, &data).unwrap(),
[1000, 1008, 1016, 1024, 1016, 1008, 1024, 1056, 17440, 1056, 1056, 1056, 1056, 1056, 1056, 1056, 1056, 1056, 1056, 1064]
);
// stereo: the channels take turns
let mut data = [1000i16.to_le_bytes(), (-1000i16).to_le_bytes()].concat();
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]);
assert_eq!(decoder(-7, 0).decode(1, &data).unwrap(), [30000, 32767, 16383, -1, -16385, -32768, -32768]);
}
#[test]
fn eight_bit_and_silence() {
let d = decoder(4, 0);
assert_eq!(d.decode(1, &[0x80, 0x00, 0xFF, 0x70]).unwrap(), [0, -32768, 0x7F00, -0x1000]);
assert_eq!(d.decode(3, &[]).unwrap(), [0; 4]);
assert_eq!(d.decode(1, &[]).unwrap(), [0i16; 0]);
assert_eq!(decoder(4, 0x200).decode(3, &[]).unwrap(), [0; 8]);
// a flags 1 frame of more than one block plays every whole block
assert_eq!(
d.decode(1, &[0x80, 0x81, 0x82, 0x83, 0x90, 0x91, 0x92, 0x93, 0xA0]).unwrap(),
[0, 0x100, 0x200, 0x300, 0x1000, 0x1100, 0x1200, 0x1300]
);
assert_eq!(decoder(-4, 0x8000).decode(3, &[]).unwrap(), [0; 4]);
}
#[test]
fn silence_mask_runs_bit_by_bit() {
let d = decoder(2, 0);
let frame = |mask: u32, data: &[u8]| d.decode(2, &[&mask.to_le_bytes()[..], data].concat());
let (a, b) = ([0x90, 0x91], [0xA0, 0xA1]);
let (sa, sb) = ([0x1000, 0x1100], [0x2000, 0x2100]);
assert_eq!(frame(0, &[a, b].concat()).unwrap(), [sa, sb].concat());
// silent, sound, silent, sound
assert_eq!(frame(0b0101, &[a, b].concat()).unwrap(), [[0, 0], sa, [0, 0], sb].concat());
// game files set a bit for every block when all are silent
assert_eq!(frame(0b0111, &[]).unwrap(), [0; 6]);
// a trailing part of a block is left out
assert_eq!(frame(0, &[0x90, 0x91, 0xA0]).unwrap(), sa);
assert_eq!(d.decode(2, &[0, 0, 0]), Err(Error::Invalid("the silence mask is cut short")));
}
#[test]
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(_)));
let good = build(&spec(20, 0), &[]);
let with = |patch: &dyn Fn(&mut Vec<u8>)| {
let mut h = good.clone();
patch(&mut h);
Decoder::new(&h).err()
};
assert_eq!(with(&|_| {}), None);
assert_eq!(with(&|h| h.truncate(815)), Some(Error::Invalid("the header is shorter than 816 bytes")));
assert_eq!(with(&|h| h[0] = 0), Some(Error::Invalid("not a VMD header")));
assert_eq!(with(&|h| h[17] = 0), Some(Error::Invalid("the file has no sound")));
assert_eq!(with(&|h| h[804..806].fill(0)), Some(Error::Invalid("the file has no sound")));
assert_eq!(with(&|h| h[810] = 0x10), Some(Error::Unsupported("IMA ADPCM sound")));
// a frame length of nothing decodes to nothing
let mut empty = good.clone();
empty[806..808].fill(0);
let d = Decoder::new(&empty).unwrap();
assert_eq!(d.decode(1, &[1, 2, 3]).unwrap(), [0i16; 0]);
assert_eq!(d.decode(2, &[0, 0, 0, 0, 1, 2]).unwrap(), [0i16; 0]);
}
#[test]
fn hostile_input_never_panics() {
for (i, (frame_length, flags, ..)) in FORMATS.into_iter().enumerate() {
let (bytes, _) = movie(i as u64 + 1, frame_length, flags);
craft_media_testkit::hostile::hammer(&format!("vmd sound format {i}"), &bytes, 10_000, |d| {
let Ok(file) = open(d) else { return };
let Ok(decoder) = Decoder::new(file.header_bytes()) else { return };
for (i, frame) in file.frames.iter().enumerate() {
let FrameKind::Audio { flags } = frame.kind else { continue };
if let Ok(data) = file.read_frame(d, i) {
let _ = decoder.decode(flags, &data);
}
}
});
}
}
/// Real files, for whoever has some: the sound of every `.vmd` in the directory
/// `CRAFT_MEDIA_VMD_SAMPLES` names must decode to the samples ffmpeg gets. Game files are not
/// redistributable, so none are in the repository and the test is skipped without the variable.
#[test]
fn real_files_match_ffmpeg() {
let Some(dir) = std::env::var_os("CRAFT_MEDIA_VMD_SAMPLES").filter(|d| !d.is_empty()) else {
craft_media_testkit::skip_test("vmd samples", "CRAFT_MEDIA_VMD_SAMPLES is not set");
return;
};
let Some(ffmpeg) = craft_media_testkit::ffmpeg_or_skip("vmd sound samples") else { return };
let mut paths: Vec<_> = std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| Some(e.ok()?.path()))
.filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("vmd")))
.collect();
paths.sort();
assert!(!paths.is_empty(), "no .vmd files in CRAFT_MEDIA_VMD_SAMPLES");
let (mut files, mut samples) = (0, 0);
for path in &paths {
let name = path.display();
let source = std::fs::File::open(path).unwrap();
let file = open(&source).unwrap();
if file.audio_params().is_none() {
continue;
}
let d = Decoder::new(file.header_bytes()).unwrap();
let mut ours = Vec::new();
for (i, frame) in file.frames.iter().enumerate() {
let FrameKind::Audio { flags } = frame.kind else { continue };
let mut data = file.read_frame(&source, i).unwrap();
if flags == 2 && data.len() >= 4 {
// ffmpeg plays a mask frame's silent blocks before its sound; put ours in that
// order to compare
let silent = u32::from_le_bytes([data[0], data[1], data[2], data[3]]).count_ones() as usize;
ours.resize(ours.len() + silent * d.block_samples() * d.channels(), 0);
data[..4].fill(0);
}
ours.extend(d.decode(flags, &data).unwrap_or_else(|e| panic!("{name}: frame {i}: {e}")));
}
let out = Command::new(&ffmpeg).args(["-v", "quiet", "-i"]).arg(path).args(["-vn", "-f", "s16le", "-"]).output().unwrap();
let theirs: Vec<i16> = out.stdout.as_chunks::<2>().0.iter().map(|b| i16::from_le_bytes(*b)).collect();
if let Some(at) = (0..ours.len().max(theirs.len())).find(|&i| ours.get(i) != theirs.get(i)) {
panic!("{name}: sample {at} differs from ffmpeg ({} samples here, {} there)", ours.len(), theirs.len());
}
files += 1;
samples += ours.len();
}
println!("{files} files, {samples} samples match ffmpeg");
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "craft-jsonc"
description = "Span-preserving JSON/JSONC object editor with strict mode and caller-controlled input admission"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
serde_json = { workspace = true }
+619
View File
@@ -0,0 +1,619 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
//! A small JSON-with-comments editor that changes only the bytes it must.
//!
//! The text is tokenized (comments and trailing commas tolerated), parsed into a tree that keeps
//! every value's byte span, and edits are applied by splicing new text into the original. Comments,
//! formatting and key order elsewhere in the file are untouched. In strict mode comments and
//! trailing commas are rejected (for clients whose own parser is strict JSON).
use serde_json::{Map, Value};
/// Deepest nesting accepted (hostile files must not blow the stack).
const MAX_DEPTH: usize = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Tok {
LBrace,
RBrace,
LBracket,
RBracket,
Colon,
Comma,
Str,
Scalar,
}
#[derive(Debug, Clone, Copy)]
struct Token {
kind: Tok,
start: usize,
end: usize,
}
/// A parsed value with its span in the source.
#[derive(Debug, Clone)]
pub struct Node {
pub start: usize,
pub end: usize,
pub kind: NodeKind,
}
#[derive(Debug, Clone)]
pub enum NodeKind {
Object { members: Vec<Member>, trailing_comma: bool },
Array(Vec<Node>),
Scalar(Value),
}
#[derive(Debug, Clone)]
pub struct Member {
pub key: String,
pub key_start: usize,
pub value: Node,
}
/// A parsed document: the original text plus the tree.
#[derive(Debug, Clone)]
pub struct Doc {
pub text: String,
/// `None` for an empty (or whitespace/comment-only) file.
pub root: Option<Node>,
tokens: Vec<Token>,
}
fn tokenize(text: &str, strict: bool) -> Result<Vec<Token>, String> {
let b = text.as_bytes();
let mut i = 0usize;
if text.starts_with('\u{feff}') {
if strict {
return Err("byte-order mark is not allowed".into());
}
i = 3;
}
let mut out = Vec::new();
while let Some(&c) = b.get(i) {
match c {
b' ' | b'\t' | b'\r' | b'\n' => i += 1,
b'/' if b.get(i + 1) == Some(&b'/') => {
if strict {
return Err(format!("comment at byte {i} is not allowed in strict JSON"));
}
while let Some(&c) = b.get(i) {
if matches!(c, b'\r' | b'\n') {
break;
}
i += 1;
}
}
b'/' if b.get(i + 1) == Some(&b'*') => {
if strict {
return Err(format!("comment at byte {i} is not allowed in strict JSON"));
}
let start = i;
i += 2;
loop {
match b.get(i) {
None => return Err(format!("unterminated comment starting at byte {start}")),
Some(b'*') if b.get(i + 1) == Some(&b'/') => {
i += 2;
break;
}
Some(_) => i += 1,
}
}
}
b'{' | b'}' | b'[' | b']' | b':' | b',' => {
let kind = match c {
b'{' => Tok::LBrace,
b'}' => Tok::RBrace,
b'[' => Tok::LBracket,
b']' => Tok::RBracket,
b':' => Tok::Colon,
_ => Tok::Comma,
};
out.push(Token { kind, start: i, end: i + 1 });
i += 1;
}
b'"' => {
let start = i;
i += 1;
loop {
match b.get(i) {
None => return Err(format!("unterminated string starting at byte {start}")),
Some(b'\\') => i += 2,
Some(b'"') => {
i += 1;
break;
}
Some(b'\n') => return Err(format!("line break inside string at byte {i}")),
Some(_) => i += 1,
}
}
out.push(Token { kind: Tok::Str, start, end: i });
}
c if c == b'-' || c.is_ascii_alphanumeric() || c == b'.' || c == b'+' => {
let start = i;
while let Some(&c) = b.get(i) {
if c == b'-' || c.is_ascii_alphanumeric() || c == b'.' || c == b'+' {
i += 1;
} else {
break;
}
}
out.push(Token { kind: Tok::Scalar, start, end: i });
}
_ => return Err(format!("unexpected character at byte {i}")),
}
}
Ok(out)
}
struct Parser<'a> {
text: &'a str,
toks: &'a [Token],
pos: usize,
strict: bool,
}
impl Parser<'_> {
fn peek(&self) -> Option<Token> {
self.toks.get(self.pos).copied()
}
fn next(&mut self) -> Result<Token, String> {
let t = self.peek().ok_or_else(|| "unexpected end of file".to_string())?;
self.pos += 1;
Ok(t)
}
fn slice(&self, t: Token) -> &str {
self.text.get(t.start..t.end).unwrap_or_default()
}
fn value(&mut self, depth: usize) -> Result<Node, String> {
if depth > MAX_DEPTH {
return Err("nested too deeply".into());
}
let t = self.next()?;
match t.kind {
Tok::LBrace => {
let mut members = Vec::new();
let mut trailing_comma = false;
loop {
let n = self.peek().ok_or("unterminated object")?;
if n.kind == Tok::RBrace {
self.pos += 1;
if trailing_comma && self.strict {
return Err(format!("trailing comma before byte {}", n.start));
}
return Ok(Node { start: t.start, end: n.end, kind: NodeKind::Object { members, trailing_comma } });
}
if !members.is_empty() && !trailing_comma {
return Err(format!("expected , or }} at byte {}", n.start));
}
let k = self.next()?;
if k.kind != Tok::Str {
return Err(format!("expected a key at byte {}", k.start));
}
let key: String = serde_json::from_str(self.slice(k)).map_err(|e| format!("bad key at byte {}: {e}", k.start))?;
let c = self.next()?;
if c.kind != Tok::Colon {
return Err(format!("expected : at byte {}", c.start));
}
let value = self.value(depth + 1)?;
members.push(Member { key, key_start: k.start, value });
trailing_comma = false;
if self.peek().is_some_and(|t| t.kind == Tok::Comma) {
self.pos += 1;
trailing_comma = true;
}
}
}
Tok::LBracket => {
let mut items = Vec::new();
let mut comma = false;
loop {
let n = self.peek().ok_or("unterminated array")?;
if n.kind == Tok::RBracket {
self.pos += 1;
if comma && self.strict {
return Err(format!("trailing comma before byte {}", n.start));
}
return Ok(Node { start: t.start, end: n.end, kind: NodeKind::Array(items) });
}
if !items.is_empty() && !comma {
return Err(format!("expected , or ] at byte {}", n.start));
}
items.push(self.value(depth + 1)?);
comma = false;
if self.peek().is_some_and(|t| t.kind == Tok::Comma) {
self.pos += 1;
comma = true;
}
}
}
Tok::Str | Tok::Scalar => {
let v: Value = serde_json::from_str(self.slice(t)).map_err(|_| format!("bad value at byte {}", t.start))?;
Ok(Node { start: t.start, end: t.end, kind: NodeKind::Scalar(v) })
}
_ => Err(format!("unexpected token at byte {}", t.start)),
}
}
}
impl Node {
pub fn to_value(&self) -> Value {
match &self.kind {
NodeKind::Scalar(v) => v.clone(),
NodeKind::Array(items) => Value::Array(items.iter().map(Node::to_value).collect()),
NodeKind::Object { members, .. } => {
let mut m = Map::new();
for mem in members {
m.insert(mem.key.clone(), mem.value.to_value());
}
Value::Object(m)
}
}
}
fn member(&self, key: &str) -> Option<&Member> {
match &self.kind {
NodeKind::Object { members, .. } => members.iter().rev().find(|m| m.key == key),
_ => None,
}
}
}
/// Parse `text`. `strict` rejects comments, trailing commas and a BOM.
///
/// Compatibility entry point: no implicit byte cap. Callers must bound input and
/// edit values according to their context. Nesting is capped at 128; token/tree
/// storage scales with input. Use [`parse_bounded`] to reject oversized text
/// before tokenization. This does not impose an edit-output budget.
pub fn parse(text: &str, strict: bool) -> Result<Doc, String> {
let tokens = tokenize(text, strict)?;
if tokens.is_empty() {
return Ok(Doc { text: text.to_string(), root: None, tokens });
}
let mut p = Parser { text, toks: &tokens, pos: 0, strict };
let root = p.value(0)?;
if p.pos != tokens.len() {
return Err("extra content after the top-level value".into());
}
if !matches!(root.kind, NodeKind::Object { .. }) {
return Err("the top level must be an object".into());
}
Ok(Doc { text: text.to_string(), root: Some(root), tokens })
}
impl Doc {
pub fn to_value(&self) -> Value {
self.root.as_ref().map(Node::to_value).unwrap_or_else(|| Value::Object(Map::new()))
}
/// The value at `path` (object keys only).
pub fn get(&self, path: &[&str]) -> Option<Value> {
let mut node = self.root.as_ref()?;
for k in path {
node = &node.member(k)?.value;
}
Some(node.to_value())
}
fn line_start(&self, pos: usize) -> usize {
self.text.get(..pos).and_then(|s| s.rfind(['\r', '\n'])).map(|i| i + 1).unwrap_or(0)
}
fn indent_at(&self, pos: usize) -> String {
let ls = self.line_start(pos);
self.text.get(ls..).unwrap_or_default().chars().take_while(|c| *c == ' ' || *c == '\t').collect()
}
/// True when only whitespace precedes `pos` on its line.
fn first_on_line(&self, pos: usize) -> bool {
let ls = self.line_start(pos);
self.text.get(ls..pos).is_some_and(|s| s.trim().is_empty())
}
/// Set `path` to `value`, creating intermediate objects. Returns the new text.
pub fn set(&self, path: &[&str], value: &Value) -> Result<String, String> {
let Some((last, parents)) = path.split_last() else { return Err("empty path".into()) };
let Some(root) = &self.root else {
// No object yet: retain comments, whitespace and an optional BOM before the new one.
let mut v = value.clone();
for k in path.iter().rev() {
let mut m = Map::new();
m.insert((*k).to_string(), v);
v = Value::Object(m);
}
let mut s = self.text.clone();
let eol = self.eol();
if !s.is_empty() && !s.ends_with(['\r', '\n']) {
s.push_str(eol);
}
s.push_str(&render(&v, "", eol));
s.push_str(eol);
return Ok(s);
};
// Walk down as far as the path exists.
let mut node = root;
let mut depth = 0;
for k in parents {
match node.member(k) {
Some(m) if matches!(m.value.kind, NodeKind::Object { .. }) => {
node = &m.value;
depth += 1;
}
Some(_) => return Err(format!("\"{k}\" exists but is not an object")),
None => break,
}
}
if depth == parents.len()
&& let Some(m) = node.member(last)
{
// Replace the existing value in place.
let indent = self.indent_at(m.key_start);
let rendered = render(value, &indent, self.eol());
return Ok(splice(&self.text, &[(m.value.start, m.value.end, rendered)]));
}
// Insert a new member (holding the rest of the path) into `node`.
let rest = path.get(depth..).unwrap_or_default();
let Some((first, tail)) = rest.split_first() else { return Err("empty path".into()) };
let mut v = value.clone();
for k in tail.iter().rev() {
let mut m = Map::new();
m.insert((*k).to_string(), v);
v = Value::Object(m);
}
self.insert_member(node, first, &v)
}
/// Preserve CRLF and CR-only documents; otherwise use LF.
fn eol(&self) -> &'static str {
if self.text.contains("\r\n") {
"\r\n"
} else if self.text.contains('\r') && !self.text.contains('\n') {
"\r"
} else {
"\n"
}
}
/// Add `key: value` as the last member of `obj`, indented like the members already there.
fn insert_member(&self, obj: &Node, key: &str, value: &Value) -> Result<String, String> {
let NodeKind::Object { members, trailing_comma } = &obj.kind else { return Err("not an object".into()) };
let close = obj.end.saturating_sub(1);
let close_indent = self.indent_at(obj.start);
let indent = match members.first() {
Some(m) if self.first_on_line(m.key_start) => self.indent_at(m.key_start),
_ => format!("{close_indent} "),
};
let eol = self.eol();
let key_json = serde_json::to_string(key).map_err(|e| e.to_string())?;
// An object whose members all end in a comma gets a new member that does too.
let comma = if *trailing_comma { "," } else { "" };
let member = format!("{indent}{key_json}: {}{comma}", render(value, &indent, eol));
let mut edits = Vec::new();
if let Some(last) = members.last()
&& !trailing_comma
{
edits.push((last.value.end, last.value.end, ",".to_string()));
}
if self.first_on_line(close) && !members.is_empty() {
let ls = self.line_start(close);
edits.push((ls, ls, format!("{member}{eol}")));
} else {
// `{}` or `{ "a": 1 }` on one line: open it up.
let inner_end = close;
let before = self.text.get(..inner_end).unwrap_or_default();
let trimmed_end = before.trim_end().len().max(obj.start + 1);
edits.push((trimmed_end, inner_end, format!("{eol}{member}{eol}{close_indent}")));
}
Ok(splice(&self.text, &edits))
}
/// Remove every member at `path`. Returns the new text, or `None` if it was not there.
pub fn remove(&self, path: &[&str]) -> Option<String> {
let (last, parents) = path.split_last()?;
let mut node = self.root.as_ref()?;
for k in parents {
node = &node.member(k)?.value;
}
let NodeKind::Object { members, .. } = &node.kind else { return None };
let mut edits = Vec::new();
// Remove members separately so comments between duplicates survive.
// A final run's leading comma is a separate edit for the same reason.
for run in members.split(|m| m.key != *last) {
let Some(first) = run.first() else { continue };
let before_idx = self.tokens.partition_point(|t| t.end <= first.key_start);
let before = before_idx.checked_sub(1).and_then(|i| self.tokens.get(i)).copied().filter(|t| t.kind == Tok::Comma);
for member in run {
let after_idx = self.tokens.partition_point(|t| t.start < member.value.end);
let after = self.tokens.get(after_idx).copied().filter(|t| t.kind == Tok::Comma);
let with_comma = after.is_none_or(|c| self.text.get(member.value.end..c.start).is_some_and(|gap| gap.trim().is_empty()));
let member_end = if with_comma { after.map(|t| t.end).unwrap_or(member.value.end) } else { member.value.end };
let rest = self.text.get(member_end..).unwrap_or_default();
let line_rest = rest.split(['\r', '\n']).next().unwrap_or_default();
let own_lines = self.first_on_line(member.key_start) && line_rest.trim().is_empty();
let (start, end) = if own_lines {
let line_end = member_end + line_rest.len();
let eol_len =
if self.text.get(line_end..).is_some_and(|s| s.starts_with("\r\n")) { 2 } else { usize::from(rest.len() > line_rest.len()) };
(self.line_start(member.key_start), line_end + eol_len)
} else {
(member.key_start, member_end)
};
edits.push((start, end, String::new()));
if !with_comma && let Some(c) = after {
edits.push((c.start, c.end, String::new()));
}
// The last member had no comma after it, so the one before it goes: leaving it
// would add a trailing comma the file didn't have, which plain JSON readers refuse.
if after.is_none()
&& let Some(c) = before
{
edits.push((c.start, c.end, String::new()));
}
}
}
(!edits.is_empty()).then(|| splice(&self.text, &edits))
}
}
/// Pretty-print `value` with continuation lines indented by `indent`.
fn render(value: &Value, indent: &str, eol: &str) -> String {
let s = serde_json::to_string_pretty(value).unwrap_or_else(|_| "null".into());
let mut out = String::new();
for (i, line) in s.lines().enumerate() {
if i > 0 {
out.push_str(eol);
out.push_str(indent);
}
out.push_str(line);
}
out
}
/// Apply non-overlapping edits `(start, end, replacement)`.
fn splice(text: &str, edits: &[(usize, usize, String)]) -> String {
let mut sorted: Vec<&(usize, usize, String)> = edits.iter().collect();
sorted.sort_by_key(|e| (e.0, e.1));
let mut out = String::with_capacity(text.len() + 256);
let mut pos = 0;
for (s, e, r) in sorted {
if *s < pos {
continue;
}
out.push_str(text.get(pos..*s).unwrap_or_default());
out.push_str(r);
pos = *e;
}
out.push_str(text.get(pos..).unwrap_or_default());
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
const FIXTURE: &str = r#"// user settings
{
/* theme */
"theme": "dark", // trailing note
"mcpServers": {
"other": { "command": "x" }, // keep me
},
}
"#;
#[test]
fn set_keeps_crlf_line_endings() {
for src in ["{\r\n \"a\": 1\r\n}\r\n", "{}\r\n"] {
let d = parse(src, true).unwrap();
let out = d.set(&["z"], &json!({"k": [1]})).unwrap();
assert_eq!(out.matches('\n').count(), out.matches("\r\n").count(), "mixed line endings: {out:?}");
assert_eq!(parse(&out, true).unwrap().get(&["z", "k"]), Some(json!([1])));
}
}
#[test]
fn a_carriage_return_ends_a_line_comment() {
let text = "// editor settings\r{\r \"keep\": 1, // explanation\r \"port\": 2\r}\r";
let doc = parse(text, false).unwrap();
assert_eq!(doc.get(&["keep"]), Some(json!(1)));
let updated = doc.set(&["port"], &json!(3)).unwrap();
assert_eq!(updated, text.replace('2', "3"));
assert_eq!(parse(&updated, false).unwrap().get(&["port"]), Some(json!(3)));
assert!(parse(text, true).is_err());
}
#[test]
fn parses_comments_and_trailing_commas() {
let d = parse(FIXTURE, false).unwrap();
assert_eq!(d.get(&["mcpServers", "other", "command"]), Some(json!("x")));
assert!(parse(FIXTURE, true).is_err());
assert!(parse("{\"a\": 1,}", true).is_err());
assert!(parse("{\"a\": 1}", true).is_ok());
assert!(parse("[1]", false).is_err());
assert!(parse("{", false).is_err());
assert!(parse("", false).unwrap().root.is_none());
}
#[test]
fn insert_keeps_comments_and_reparses() {
let d = parse(FIXTURE, false).unwrap();
let new = d.set(&["mcpServers", "craft-anything"], &json!({"command": "/x/craft-anything-cli", "args": ["mcp"]})).unwrap();
assert!(new.contains("// keep me") && new.contains("/* theme */") && new.contains("// user settings"));
let d2 = parse(&new, false).unwrap();
assert_eq!(d2.get(&["mcpServers", "craft-anything", "args"]), Some(json!(["mcp"])));
assert_eq!(d2.get(&["mcpServers", "other", "command"]), Some(json!("x")));
// replace in place
let new2 = d2.set(&["mcpServers", "craft-anything"], &json!({"command": "y"})).unwrap();
let d3 = parse(&new2, false).unwrap();
assert_eq!(d3.get(&["mcpServers", "craft-anything"]), Some(json!({"command": "y"})));
// remove restores the original exactly
assert_eq!(d3.remove(&["mcpServers", "craft-anything"]).unwrap(), FIXTURE);
}
#[test]
fn creates_missing_tables_and_handles_empty() {
let d = parse("{}", true).unwrap();
let new = d.set(&["mcp", "servers", "k"], &json!(1)).unwrap();
assert_eq!(parse(&new, true).unwrap().get(&["mcp", "servers", "k"]), Some(json!(1)));
let d = parse("{\n \"a\": 1\n}\n", true).unwrap();
let new = d.set(&["s", "k"], &json!(true)).unwrap();
assert_eq!(new, "{\n \"a\": 1,\n \"s\": {\n \"k\": true\n }\n}\n");
let empty = parse(" \n", false).unwrap().set(&["s", "k"], &json!(2)).unwrap();
assert_eq!(parse(&empty, true).unwrap().get(&["s", "k"]), Some(json!(2)));
let one_line = parse(r#"{"a": {"b": 1}}"#, true).unwrap().set(&["a", "c"], &json!(2)).unwrap();
assert_eq!(parse(&one_line, true).unwrap().to_value(), json!({"a": {"b": 1, "c": 2}}));
}
#[test]
fn remove_first_middle_last() {
let text = "{\n \"a\": 1,\n \"b\": 2,\n \"c\": 3\n}\n";
let d = parse(text, true).unwrap();
for (k, rest) in [("a", json!({"b":2,"c":3})), ("b", json!({"a":1,"c":3})), ("c", json!({"a":1,"b":2}))] {
let t = d.remove(&[k]).unwrap();
assert_eq!(parse(&t, true).unwrap().to_value(), rest, "{t}");
}
assert!(d.remove(&["zz"]).is_none());
let single = parse("{\"a\": 1}", true).unwrap().remove(&["a"]).unwrap();
assert_eq!(parse(&single, true).unwrap().to_value(), json!({}));
}
#[test]
fn hostile_input_never_panics() {
for s in ["{\"a\":", "{\"a\" 1}", "{,}", "\"\\", "/*", "{\"a\":[1,,2]}", "{\"a\":1}}", &"[".repeat(1000), "\u{feff}{}"] {
let _ = parse(s, false);
let _ = parse(s, true);
}
assert!(parse("\u{feff}{}", false).is_ok());
}
}
/// Reject input larger than `max_bytes` before tokenizing, then use [`parse`].
/// This bounds admitted input, not allocator overhead or subsequent edit output.
pub fn parse_bounded(text: &str, strict: bool, max_bytes: usize) -> Result<Doc, String> {
if text.len() > max_bytes {
return Err(format!("JSONC input exceeds {max_bytes} bytes"));
}
parse(text, strict)
}
#[cfg(test)]
mod admission_tests {
use super::*;
#[test]
fn byte_limit_is_explicit_and_precedes_syntax_work() {
assert!(parse_bounded("{}", false, 2).is_ok());
assert_eq!(parse_bounded("{", false, 0).unwrap_err(), "JSONC input exceeds 0 bytes");
assert!(parse_bounded("", false, 0).is_ok());
let text = "{\"é\":1}";
assert!(parse_bounded(text, false, text.len() - 1).is_err());
assert_eq!(parse_bounded(text, false, text.len()).unwrap().to_value(), parse(text, false).unwrap().to_value());
}
}
+45
View File
@@ -4,6 +4,18 @@ use serde_json::json;
use crate::{Json, nums, round6};
/// Raw gradient wire values from borrowed or mapped stops, without intermediate allocation.
///
/// Yields color groups (`position, r, g, b`) then every opacity pair (`position, alpha`).
/// Input order and all values, including non-finite values and opaque alpha, are preserved.
/// Sanitization, rounding, and input/output size budgets remain the caller's responsibility.
pub fn flat_gradient_values(
colors: impl IntoIterator<Item = (f64, [f64; 3])>,
opacities: impl IntoIterator<Item = (f64, f64)>,
) -> impl Iterator<Item = f64> {
colors.into_iter().flat_map(|(p, [r, g, b])| [p, r, g, b]).chain(opacities.into_iter().flat_map(|(p, a)| [p, a]))
}
/// A gradient: colour stops and opacity stops, each at a position in 0..=1.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Gradient {
@@ -29,6 +41,17 @@ impl Gradient {
Some(Self { colors, opacities })
}
/// Raw color groups (`position, r, g, b`), followed by all opacity pairs
/// (`position, alpha`), in input order. No rounding, clamping, or opacity elision.
///
/// This allocation-free view lets callers fit or interpolate equal-sized animated
/// values before applying their own numeric policy. In particular, opaque alpha
/// stops remain present so an opaque frame can interpolate to a translucent one.
/// Non-finite values are preserved; callers must sanitize them before JSON output.
pub fn flat_values(&self) -> impl Iterator<Item = f64> + '_ {
flat_gradient_values(self.colors.iter().copied(), self.opacities.iter().copied())
}
/// The flat list, rounded to six decimals. The alpha pairs are left out when every stop is
/// opaque.
pub fn to_flat(&self) -> Json {
@@ -44,3 +67,25 @@ impl Gradient {
json!(out)
}
}
#[cfg(test)]
mod raw_tests {
use super::*;
#[test]
fn raw_values_keep_order_precision_and_opaque_alpha() {
let g = Gradient { colors: vec![(0.123456789, [0.2, 0.3, 0.4]), (1.0, [0.5, 0.6, 0.7])], opacities: vec![(0.0, 1.0), (1.0, 1.0)] };
assert_eq!(g.flat_values().collect::<Vec<_>>(), vec![0.123456789, 0.2, 0.3, 0.4, 1.0, 0.5, 0.6, 0.7, 0.0, 1.0, 1.0, 1.0]);
assert_eq!(g.to_flat(), json!([0.123457, 0.2, 0.3, 0.4, 1.0, 0.5, 0.6, 0.7]));
}
#[test]
fn raw_values_keep_nonfinite_signed_zero_and_unpaired_lists() {
let g = Gradient { colors: vec![], opacities: vec![(-0.0, f64::NAN), (f64::INFINITY, f64::NEG_INFINITY)] };
let bits: Vec<_> = g.flat_values().map(f64::to_bits).collect();
assert_eq!(bits, [-0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY].map(f64::to_bits));
assert_eq!(Gradient::default().flat_values().count(), 0);
let g = Gradient { colors: vec![(1e303, [1.0, 0.0, 0.0])], opacities: vec![] };
assert_eq!(g.flat_values().collect::<Vec<_>>(), [1e303, 1.0, 0.0, 0.0]);
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ mod prop;
mod value;
pub mod zip;
pub use gradient::Gradient;
pub use gradient::{Gradient, flat_gradient_values};
pub use model::{Animated, Animation, Layer, LayerContent, Limits, Shape, ShapeKind};
pub use path::Bezier;
pub use prop::{Ease, Key, KeyOut, Prop, PropValue, Tangents, is_animated, read_prop, tangent, write_keys, write_prop};
+2
View File
@@ -14,11 +14,13 @@
//! [`hostile::hammer`] runs a parser over every truncation and mutations of a valid input and fails
//! on a panic or a case that does not finish in time; `CRAFT_MEDIA_HOSTILE_MULT=10` runs ten times
//! the iterations. It and [`with_deadline`] call `craft_testkit`.
//! [`vmd`] writes Sierra VMD fixtures, which ffmpeg can read but not write.
//!
//! Failing loudly is what a test helper is for: a wrong `CRAFT_MEDIA_*` setting or an unwritable
//! fixture directory panics, which fails the test that asked.
pub mod hostile;
pub mod vmd;
use std::path::{Path, PathBuf};
use std::process::Command;
+343
View File
@@ -0,0 +1,343 @@
//! Sierra VMD fixture writer. ffmpeg reads VMD but cannot write it, so the VMD tests build their
//! files here and use ffmpeg only to decode them. Written from the public format description
//! (<https://wiki.multimedia.cx/index.php/VMD>); the packers favour coverage of every coding
//! mode over compression.
use crate::hostile::Rng;
/// Bytes of the file header.
pub const HEADER_LEN: usize = 816;
/// The audio fields of the header.
#[derive(Clone, Copy, Debug)]
pub struct Audio {
/// Samples per second.
pub sample_rate: u16,
/// The frame length field as stored: negative for 16-bit sound.
pub frame_length: i16,
/// Number of sound buffers.
pub buffers: u16,
/// Audio flags (0x8000 old stereo, 0x200 new stereo).
pub flags: u16,
}
/// What the header says.
#[derive(Clone, Debug)]
pub struct Spec {
/// Picture width in pixels.
pub width: u16,
/// Picture height in pixels.
pub height: u16,
/// Left coordinate of the picture.
pub left: u16,
/// Top coordinate of the picture.
pub top: u16,
/// 256 R-G-B triplets of 6-bit components.
pub palette: [u8; 768],
/// Size of the unpack buffer for LZ-packed frames.
pub unpack: u32,
/// Video codec version (header bytes 4-5).
pub codec_version: u16,
/// The sound, if the file has any.
pub audio: Option<Audio>,
}
impl Spec {
/// A silent file of `width` x `height` with a grey ramp palette.
pub fn new(width: u16, height: u16) -> Spec {
let mut palette = [0; 768];
for (i, p) in palette.iter_mut().enumerate() {
*p = (i / 3 / 4) as u8;
}
Spec { width, height, left: 0, top: 0, palette, unpack: 1 << 20, codec_version: 0, audio: None }
}
}
/// One frame of a block: its 16-byte record and its data.
#[derive(Clone, Debug)]
pub struct Frame {
/// Frame type: 1 audio, 2 video.
pub kind: u8,
/// Bytes 6 to 15 of the frame record.
pub tail: [u8; 10],
/// The frame data.
pub data: Vec<u8>,
}
impl Frame {
/// A video frame updating `rect` (left, top, right, bottom; inclusive).
pub fn video(rect: [u16; 4], new_palette: bool, data: Vec<u8>) -> Frame {
let mut tail = [0; 10];
for (i, v) in rect.iter().enumerate() {
tail[i * 2..i * 2 + 2].copy_from_slice(&v.to_le_bytes());
}
tail[9] = if new_palette { 2 } else { 0 };
Frame { kind: 2, tail, data }
}
/// An audio frame with the given block flags (1 sound, 2 mask and blocks, 3 silence).
pub fn audio(flags: u8, data: Vec<u8>) -> Frame {
let mut tail = [0; 10];
tail[0] = flags;
Frame { kind: 1, tail, data }
}
}
/// A whole file: header, frame data, then the table of contents. Every block must hold the same
/// number of frames.
#[allow(clippy::panic)]
pub fn build(spec: &Spec, blocks: &[Vec<Frame>]) -> Vec<u8> {
let per_block = blocks.first().map_or(0, Vec::len);
assert!(blocks.iter().all(|b| b.len() == per_block), "every block holds the same number of frames");
let mut data = Vec::new();
let mut offsets = Vec::new();
let mut records = Vec::new();
for block in blocks {
offsets.push((HEADER_LEN + data.len()) as u32);
for f in block {
records.push(f.kind);
records.push(0);
records.extend_from_slice(&(f.data.len() as u32).to_le_bytes());
records.extend_from_slice(&f.tail);
data.extend_from_slice(&f.data);
}
}
let mut h = vec![0u8; HEADER_LEN];
let put16 = |h: &mut [u8], at: usize, v: u16| h[at..at + 2].copy_from_slice(&v.to_le_bytes());
let put32 = |h: &mut [u8], at: usize, v: u32| h[at..at + 4].copy_from_slice(&v.to_le_bytes());
put16(&mut h, 0, (HEADER_LEN - 2) as u16);
put16(&mut h, 4, spec.codec_version);
put16(&mut h, 6, blocks.len() as u16);
put16(&mut h, 8, spec.top);
put16(&mut h, 10, spec.left);
put16(&mut h, 12, spec.width);
put16(&mut h, 14, spec.height);
put16(&mut h, 16, if spec.audio.is_some() { 0x1000 } else { 0 });
put16(&mut h, 18, per_block as u16);
put32(&mut h, 20, HEADER_LEN as u32);
h[28..796].copy_from_slice(&spec.palette);
put32(&mut h, 800, spec.unpack);
if let Some(a) = spec.audio {
put16(&mut h, 804, a.sample_rate);
put16(&mut h, 806, a.frame_length as u16);
put16(&mut h, 808, a.buffers);
put16(&mut h, 810, a.flags);
}
put32(&mut h, 812, (HEADER_LEN + data.len()) as u32);
h.extend_from_slice(&data);
for o in offsets {
h.extend_from_slice(&[0, 0]);
h.extend_from_slice(&o.to_le_bytes());
}
h.extend_from_slice(&records);
h
}
/// The 770 bytes that open a video frame carrying a new palette.
pub fn palette_chunk(palette: &[u8; 768]) -> Vec<u8> {
let mut v = vec![0, 255];
v.extend_from_slice(palette);
v
}
/// LZ-pack `data` (what follows the coding method byte): the length, the optional marker that
/// selects long chains, then tagged literals and chains. `rng` picks between a literal and a
/// chain where both are possible, so both paths get exercised.
pub fn lz_pack(data: &[u8], marker: bool, rng: &mut Rng) -> Vec<u8> {
let mut out = (data.len() as u32).to_le_bytes().to_vec();
let mut queue = [0x20u8; 4096];
let mut qpos = if marker {
out.extend_from_slice(&[0x34, 0x12, 0x78, 0x56]);
0x111usize
} else {
0xFEE
};
let max_len = if marker { 18 + 255 } else { 18 };
let mut pos = 0;
while pos < data.len() {
// a tag of 0xFF with more than 8 bytes left means 8 raw bytes
let tag_at = out.len();
out.push(0);
let mut tag = 0u8;
for bit in 0..8 {
if pos >= data.len() {
break;
}
let left = data.len() - pos;
// the longest chain in the queue; a chain may run into the bytes it is writing
let (mut best_len, mut best_off) = (0usize, 0usize);
for off in 0..4096usize {
let mut n = 0;
while n < max_len.min(left) {
let behind = (off + n).wrapping_sub(qpos) & 0xFFF;
let have = if behind < n { data[pos + behind] } else { queue[(off + n) & 0xFFF] };
if have != data[pos + n] {
break;
}
n += 1;
}
if n > best_len {
(best_len, best_off) = (n, off);
}
}
if best_len >= 3 && rng.below(4) != 0 {
// sometimes a shorter chain than the longest
let len = if rng.below(3) == 0 { 3 + rng.below(best_len - 2) } else { best_len };
let nibble = if marker && len >= 18 { 15 } else { len - 3 };
out.push(best_off as u8);
out.push(((best_off >> 4) & 0xF0) as u8 | nibble as u8);
if marker && len >= 18 {
out.push((len - 18) as u8);
}
for i in 0..len {
queue[(qpos + i) & 0xFFF] = data[pos + i];
}
qpos = (qpos + len) & 0xFFF;
pos += len;
} else {
tag |= 1 << bit;
out.push(data[pos]);
queue[qpos] = data[pos];
qpos = (qpos + 1) & 0xFFF;
pos += 1;
}
}
out[tag_at] = tag;
}
out
}
/// The body of a method 1 (`rle` false) or method 3 frame that turns the `rect` of `prev` into
/// that of `cur`; both are whole pictures of `stride` bytes a row. Unchanged runs are skipped.
/// With `rle`, changed runs are run-length packed when `rng` says so (always when they begin
/// with 0xFF, which a plain run cannot).
///
/// With `rle`, no changed run is a single pixel: the description and ffmpeg disagree on how a
/// run-length run of one pixel ends, and the game files seen do not have one. A lone changed
/// pixel takes its neighbour along, so the rectangle must be at least two pixels wide.
pub fn delta_lines(prev: &[u8], cur: &[u8], stride: usize, rect: [u16; 4], rle: bool, rng: &mut Rng) -> Vec<u8> {
let [left, top, right, bottom] = rect.map(usize::from);
let width = right - left + 1;
let mut out = Vec::new();
for y in top..=bottom {
let row = y * stride + left;
let mut changed: Vec<bool> = (0..width).map(|x| prev[row + x] != cur[row + x]).collect();
if rle {
for x in 0..width {
let alone = changed[x] && (x == 0 || !changed[x - 1]) && (x + 1 == width || !changed[x + 1]);
if alone && x + 1 < width {
changed[x + 1] = true;
} else if alone && x > 0 {
changed[x - 1] = true;
}
}
}
let mut x = 0;
while x < width {
let mut end = x;
while end < width && changed[end] == changed[x] {
end += 1;
}
let mut n = (end - x).min(128);
if rle && changed[x] && end - x - n == 1 {
n -= 1;
}
if !changed[x] {
out.push((n - 1) as u8);
} else {
let run = &cur[row + x..row + x + n];
out.push(0x80 | (n - 1) as u8);
if rle && (run[0] == 0xFF || rng.below(2) == 0) {
out.push(0xFF);
rle_pack(run, &mut out);
} else {
out.extend_from_slice(run);
}
}
x += n;
}
}
out
}
fn rle_pack(run: &[u8], out: &mut Vec<u8>) {
let mut run = run;
if run.len() % 2 == 1 {
out.push(run[0]);
run = &run[1..];
}
let pairs = run.as_chunks::<2>().0;
let mut i = 0;
while i < pairs.len() {
let mut n = 1;
while i + n < pairs.len() && pairs[i + n] == pairs[i] && n < 127 {
n += 1;
}
if n > 1 {
out.push(n as u8);
out.extend_from_slice(&pairs[i]);
i += n;
continue;
}
// pairs up to the next repeat go out as they are
let start = i;
while i < pairs.len() && i - start < 127 && !(i + 1 < pairs.len() && pairs[i + 1] == pairs[i]) {
i += 1;
}
out.push(0x80 | (i - start) as u8);
out.extend(pairs[start..i].iter().flatten());
}
}
/// The step table of the 16-bit sound coding.
pub const DPCM_STEPS: [u16; 128] = {
let mut t = [0u16; 128];
let mut i = 1;
while i < 128 {
t[i] = match i {
1 => 8,
2..=33 => 16 * (i as u16 - 1),
34..=97 => 512 + 8 * (i as u16 - 33),
98..=113 => 1024 + 64 * (i as u16 - 97),
114..=121 => 2048 + 256 * (i as u16 - 113),
122..=125 => 4096 + 1024 * (i as u16 - 121),
126 => 12288,
_ => 16384,
};
i += 1;
}
t
};
/// Pack one block of 16-bit sound: `samples` are interleaved across `channels`. Returns the
/// block (each channel's first sample as it is, then one code a sample) and the samples a
/// decoder gets back from it.
pub fn dpcm_pack(samples: &[i16], channels: usize) -> (Vec<u8>, Vec<i16>) {
let mut out = Vec::new();
let mut decoded = Vec::new();
let mut pred = [0i32; 2];
for (i, &s) in samples.iter().enumerate() {
let ch = i % channels;
if i < channels {
out.extend_from_slice(&s.to_le_bytes());
pred[ch] = i32::from(s);
} else {
let diff = i32::from(s) - pred[ch];
let mag = diff.unsigned_abs();
let mut code = 0;
for (c, &step) in DPCM_STEPS.iter().enumerate() {
if u32::from(step).abs_diff(mag) < u32::from(DPCM_STEPS[code]).abs_diff(mag) {
code = c;
}
}
let step = i32::from(DPCM_STEPS[code]);
// stay inside 16 bits, so that a decoder's handling of overflow does not matter
let (next, byte) = if diff < 0 { (pred[ch] - step, 0x80 | code as u8) } else { (pred[ch] + step, code as u8) };
let (next, byte) = if (-32768..=32767).contains(&next) { (next, byte) } else { (pred[ch], 0) };
pred[ch] = next;
out.push(byte);
}
decoded.push(pred[ch] as i16);
}
(out, decoded)
}
+6
View File
@@ -24,6 +24,8 @@ avi = []
mxf = ["dep:chrono"]
# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`).
mpegts = []
# Sierra VMD (Video and Music Data) demuxer (`craft_media::vmd`).
vmd = []
# Ogg demuxer (Ogg Opus and Vorbis mapping, `craft_media::ogg`).
ogg = []
# Serialize and Deserialize for `Container`, `CodecId`, `CodecParams` and `PcmFormat`.
@@ -79,6 +81,10 @@ required-features = ["mxf"]
name = "oracle_ogg"
required-features = ["ogg"]
[[test]]
name = "oracle_vmd"
required-features = ["vmd"]
[[test]]
name = "roundtrip"
required-features = ["isobmff"]
+57 -6
View File
@@ -2,7 +2,7 @@
Media containers and bit-level I/O for the Craft apps: an MSB-first bit reader and writer,
clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers, and
Ogg and MPEG-2 Systems (transport and program stream) demuxers, written from the public specifications. No `unsafe`, no panics on malformed
Ogg, MPEG-2 Systems (transport and program stream) and Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed
input, builds for `wasm32-unknown-unknown`. Dependencies: `thiserror` (for `isobmff`), `chrono`
(for `mxf`), `serde` (optional).
@@ -22,12 +22,13 @@ that codec crates use to describe a file and configure a decoder.
| `avi` | `craft_media::avi` | none |
| `mxf` | `craft_media::mxf` | `chrono` |
| `mpegts` | `craft_media::mpegts` | none |
| `vmd` | `craft_media::vmd` | none |
| (none) | `Container`, `CodecId`, `CodecParams`, `PcmFormat`, `xiph_lace`, `ByteSource`, `ReadSeekSource` | none |
| `serde` | `Serialize`/`Deserialize` on `Container`, `CodecId`, `CodecParams` and `PcmFormat` | `serde` |
`default = ["isobmff"]`, so `bitstream` and `isobmff` build. `matroska` is opt-in: it is about as
much code as `isobmff`, and most users of MP4/MOV (LightCraft, FigCraft, SoundCraft, EffectCraft)
do not read Matroska. `ogg`, `avi`, `mxf` and `mpegts` are opt-in as well. The features are independent.
do not read Matroska. `ogg`, `avi`, `mxf`, `mpegts` and `vmd` are opt-in as well. The features are independent.
```toml
craft-media = { git = "https://github.com/storytold/craft-libs", rev = "<commit>", features = ["matroska"] }
@@ -814,14 +815,64 @@ ffmpeg's decoded sound sample for sample; and files written by `MxfWriter` from
which ffprobe must describe like their source and ffmpeg must decode to the same pictures and
sound.
## `vmd`
A clean-room demuxer for Sierra VMD (Video and Music Data), the video format of Sierra's and
Coktel Vision's 1990s games (Phantasmagoria, Gabriel Knight 2, Shivers, …). There is no official
specification; it is written from the public description at
<https://wiki.multimedia.cx/index.php/VMD>.
```rust
use craft_media::vmd::{FrameKind, open};
let file = open(&bytes)?; // header and table of contents
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(i), craft_video::vmd */ }
FrameKind::Audio { flags } => { /* craft_audio::vmd */ }
FrameKind::Other(_) => {}
}
}
```
- A file is a sequence of blocks, one picture period each (`Frame::block`). A block holds the
same number of frames in every block; a block with no picture has a frame of no data or of
type 0 in its place, and the picture stays as it was.
- `frame_rate()`: a file with sound plays one block of sound a picture (sample rate over block
length); a file without plays 10 pictures a second.
- Timing: the video frame of block `n` is shown at picture period `n`. Sound is one continuous
stream from the first picture on: decode the sound frames in file order and play the samples
end to end. The first sound frame holds many blocks (28 in most Phantasmagoria files), loaded
ahead by the player, so a later sound frame is heard that much later than the block it is
stored in, and the sound outlasts the pictures.
- `video_params()` and `audio_params()` return `CodecParams` with `CodecId::VmdVideo` and
`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(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. A frame with no rectangle in
the picture can still carry a palette (`craft_video::vmd::Decoder::decode_palette`).
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
pictures, or with IMA ADPCM sound, open, and report `CodecId::Unknown` for that stream. `sniff`
has only the two-byte header length to go by, so check the file extension too.
Tests: unit tests on files from the test kit's VMD writer (`craft_media_testkit::vmd`; ffmpeg
reads VMD but cannot write it), hostile input, and `tests/oracle_vmd.rs`, which compares the
streams and picture rate with ffprobe's.
## Containers, codecs and codec parameters
Always built, with no dependencies, so codec crates share them:
- `Container`: the file format (`Wav`, `Aiff`, `Flac`, `Mp4`, `QuickTime`, `Matroska`, `WebM`,
`Ogg`, `Caf`, `Adts`, `MpegAudio`, `Ac3`, `Avi`, `Mxf`, `MpegTs`, `MpegPs`), with `name()`.
`Ogg`, `Caf`, `Adts`, `MpegAudio`, `Ac3`, `Avi`, `Mxf`, `MpegTs`, `MpegPs`, `Vmd`), with `name()`.
- `CodecId`: audio and video codecs (`Aac`, `HeAac`, `Opus`, `Eac3`, `Speex`, …, `H264`, `Hevc`,
`Av1`, `ProRes`, `Dnxhd`, `Apv`, `Theora`, …, `Unknown`), with `name()`, `is_audio()`,
`Av1`, `ProRes`, `Dnxhd`, `Apv`, `Theora`, `VmdVideo`, `VmdAudio`, …, `Unknown`), with `name()`, `is_audio()`,
`is_video()`.
- `PcmFormat`: the layout of uncompressed samples, built with `PcmFormat::int(bits, signed,
big_endian)` or `PcmFormat::float(bits, big_endian)`.
@@ -833,7 +884,7 @@ Always built, with no dependencies, so codec crates share them:
Matroska's `CodecPrivate`, as ffmpeg's extradata does: the `AudioSpecificConfig` for AAC, the
`OpusHead` for Opus (MP4's `dOps` is converted), Xiph-laced headers for Vorbis (`xiph_lace`,
`None` for more than 256 packets), `fLaC` + metadata blocks for FLAC, the
`avcC`/`hvcC`/`av1C`/`apvC` record for video.
`avcC`/`hvcC`/`av1C`/`apvC` record for video, the 816-byte file header for VMD video and sound.
All are `#[non_exhaustive]`: new formats and fields are minor changes.
@@ -841,7 +892,7 @@ All are `#[non_exhaustive]`: new formats and fields are minor changes.
`craft_media::ByteSource` (`len`, `read_at(offset, buf)`) is what every demuxer reads from. It is
always built, so a crate that uses only `bitstream` can name it too. `isobmff::ByteSource`,
`matroska::ByteSource`, `ogg::ByteSource`, `avi::ByteSource`, `mxf::ByteSource` and `mpegts::ByteSource` are the same trait. It is implemented for `[u8]`,
`matroska::ByteSource`, `ogg::ByteSource`, `avi::ByteSource`, `mxf::ByteSource`, `mpegts::ByteSource` and `vmd::ByteSource` are the same trait. It is implemented for `[u8]`,
`Vec<u8>`, `&T`, `Arc<T>`, `Box<T>` and `std::fs::File` (not on wasm). `ReadSeekSource` adapts any
`Read + Seek`; it is `Send + Sync` when the reader is `Send`. Implement the trait once for a
custom source (a web `Blob`, a network range reader) to use every container with it.
+15 -2
View File
@@ -44,6 +44,8 @@ pub enum Container {
MpegTs,
/// MPEG-1/2 program stream (MPG, VOB).
MpegPs,
/// Sierra VMD (Video and Music Data).
Vmd,
}
impl Container {
@@ -66,6 +68,7 @@ impl Container {
Container::Mxf => "MXF",
Container::MpegTs => "MPEG-TS",
Container::MpegPs => "MPEG-PS",
Container::Vmd => "VMD",
}
}
}
@@ -132,6 +135,10 @@ pub enum CodecId {
Dnxhd,
/// APV (Advanced Professional Video).
Apv,
/// Sierra VMD video (8-bit paletted).
VmdVideo,
/// Sierra VMD audio (8-bit PCM or 16-bit DPCM).
VmdAudio,
/// A codec this crate has no identifier for.
Unknown,
}
@@ -168,6 +175,8 @@ impl CodecId {
CodecId::Theora => "Theora",
CodecId::Dnxhd => "DNxHD",
CodecId::Apv => "APV",
CodecId::VmdVideo => "VMD video",
CodecId::VmdAudio => "VMD audio",
CodecId::Unknown => "unknown",
}
}
@@ -192,6 +201,7 @@ impl CodecId {
| CodecId::Opus
| CodecId::Vorbis
| CodecId::Speex
| CodecId::VmdAudio
)
}
@@ -211,6 +221,7 @@ impl CodecId {
| CodecId::Theora
| CodecId::Dnxhd
| CodecId::Apv
| CodecId::VmdVideo
)
}
}
@@ -260,6 +271,7 @@ impl PcmFormat {
/// | H.264 / HEVC / AV1 | the `avcC` / `hvcC` / `av1C` record |
/// | VP9 | the MP4 `vpcC` payload, or Matroska's codec feature metadata |
/// | APV | the `apvC` record |
/// | VMD video, VMD audio | the 816-byte VMD file header |
///
/// `sample_rate` and `channels` are what the container declares (for HE-AAC with implicit
/// signalling, usually the core rate), except that Opus is always 48 kHz, the rate it decodes at;
@@ -359,13 +371,14 @@ mod tests {
#[test]
fn audio_and_video_are_disjoint() {
for c in [CodecId::Aac, CodecId::Opus, CodecId::Pcm, CodecId::Eac3, CodecId::Speex] {
for c in [CodecId::Aac, CodecId::Opus, CodecId::Pcm, CodecId::Eac3, CodecId::Speex, CodecId::VmdAudio] {
assert!(c.is_audio() && !c.is_video(), "{c:?}");
}
for c in [CodecId::H264, CodecId::Av1, CodecId::ProRes, CodecId::Theora, CodecId::Dnxhd, CodecId::Apv] {
for c in [CodecId::H264, CodecId::Av1, CodecId::ProRes, CodecId::Theora, CodecId::Dnxhd, CodecId::Apv, CodecId::VmdVideo] {
assert!(c.is_video() && !c.is_audio(), "{c:?}");
}
assert!(!CodecId::Unknown.is_audio() && !CodecId::Unknown.is_video());
assert_eq!((CodecId::VmdVideo.name(), CodecId::VmdAudio.name(), Container::Vmd.name()), ("VMD video", "VMD audio", "VMD"));
}
#[test]
+5 -1
View File
@@ -12,12 +12,13 @@
//! - `mxf` (feature `mxf`, enables `chrono`): a clean-room MXF demuxer and writer (OP1a, OP-Atom).
//! - `mpegts` (feature `mpegts`): a clean-room MPEG-2 Systems demuxer (transport streams and
//! program streams).
//! - `vmd` (feature `vmd`): a clean-room Sierra VMD (Video and Music Data) demuxer.
//! - [`Container`] and [`CodecId`] (no feature): the identifiers the codec crates report a file's
//! container and codec with.
//! - `FileReader` (native): a pooled file `ByteSource` so many clips can be open without holding a
//! descriptor each.
//!
//! `bitstream` and `isobmff` are on by default; `matroska`, `ogg`, `avi`, `mxf` and `mpegts` are opt-in. A crate that needs
//! `bitstream` and `isobmff` are on by default; `matroska`, `ogg`, `avi`, `mxf`, `mpegts` and `vmd` are opt-in. A crate that needs
//! only bit I/O uses `default-features = false, features = ["bitstream"]`.
#[cfg(feature = "avi")]
@@ -38,6 +39,9 @@ pub mod mxf;
#[cfg(feature = "ogg")]
pub mod ogg;
pub mod source;
#[cfg(feature = "vmd")]
pub mod vmd;
#[cfg(not(target_arch = "wasm32"))]
pub use file::{FileReader, MAX_OPEN_FILES};
+437
View File
@@ -0,0 +1,437 @@
//! Clean-room Sierra VMD (Video and Music Data) demuxer, written from the public format
//! description at <https://wiki.multimedia.cx/index.php/VMD> ("Description of the Sierra Video
//! and Music Data (VMD) Format", Mike Melanson and Vladimir Gneushev) and checked against
//! ffmpeg's reading of files made by this crate's tests.
//!
//! A VMD file is an 816-byte header (picture size, a 256-colour palette, the sound format), the
//! frame data, and a table of contents at the end: one 6-byte offset record a block, then one
//! 16-byte record a frame. A block is one picture period and holds the same number of frames in
//! every block: usually a sound frame and a video frame.
//!
//! Pictures and sound are timed differently. The video frame of block `n` is shown at picture
//! period `n` ([`Frame::block`], [`VmdFile::frame_rate`]). Sound is one continuous stream that
//! starts with the first picture: decode the sound frames in file order and play the samples end
//! to end. The first sound frame holds many blocks of sound, which the player loads ahead, so
//! each later sound frame is heard that much later than the block it is stored in, and the sound
//! runs on after the last picture.
//!
//! [`open`] reads the header and the table of contents; [`VmdFile::read_frame`] reads one frame's
//! data on demand. The video decoder is `craft_video::vmd` and the sound decoder
//! `craft_audio::vmd`; both take the header ([`VmdFile::header_bytes`]) as their configuration.
//!
//! Only the 816-byte header is read: the later Coktel Vision revisions with a longer header or
//! one without a palette are refused as [`Error::NotVmd`]. Files whose pictures are 16-bit,
//! 24-bit or Indeo 3 open, and say so in [`Header::video_format`].
//!
//! Every size and count comes from the file and is treated as hostile: the table of contents
//! must lie inside the file, its length is capped, and a frame is read only if all of it is
//! there.
//!
//! No dependencies beyond `std`, no `unsafe`, builds for `wasm32-unknown-unknown`.
#![warn(missing_docs)]
#[cfg(test)]
mod tests;
pub use crate::source::{ByteSource, ReadSeekSource};
use std::io;
/// Errors from reading a VMD file.
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
/// Not a VMD file with the 816-byte header.
NotVmd,
/// A read failed.
Io(io::Error),
/// Structurally invalid data.
Invalid(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::NotVmd => f.write_str("not a VMD file"),
Error::Io(e) => write!(f, "I/O error: {e}"),
Error::Invalid(e) => write!(f, "invalid VMD: {e}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io(e) => Some(e),
_ => None,
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Error::Io(e)
}
}
/// Result alias for this module.
pub type Result<T> = std::result::Result<T, Error>;
/// Bytes of the file header, its two-byte length field included.
pub const HEADER_LEN: usize = 816;
/// Frames a table of contents may list. A file has at most 65 535 blocks of a few frames each;
/// this bounds the table a hostile header can ask for (16 bytes a frame).
const MAX_FRAMES: u64 = 1 << 22;
/// Whether `head` starts like a VMD file: the header length field, 0x32E. Two bytes are a weak
/// signature, so check the file extension as well, and expect [`open`] to refuse a false match.
pub fn sniff(head: &[u8]) -> bool {
head.get(..2) == Some(&[0x2E, 0x03])
}
/// How the pictures are stored.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoFormat {
/// 8-bit palette indices: what `craft_video::vmd` decodes.
Paletted,
/// 16-bit RGB (codec version 13).
Rgb16,
/// 24-bit RGB (codec version 5).
Rgb24,
/// Intel Indeo 3 (codec version 7, or the `iv32` mark).
Indeo3,
}
/// The sound format, from the header.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AudioHeader {
/// Samples per second.
pub sample_rate: u16,
/// The frame length field, sign removed: samples a block and channel, except in old-style
/// stereo, where it counts both channels.
pub frame_length: u16,
/// 8 (unsigned PCM) or 16 (DPCM).
pub bits: u8,
/// 1 or 2.
pub channels: u8,
/// Number of sound buffers. In the game files seen it is one more than the blocks of sound
/// (silent ones included) in the file's first sound frame.
pub buffers: u16,
/// The audio flags as stored (0x8000 old-style stereo, 0x200 new-style stereo, 0x10 IMA
/// ADPCM).
pub flags: u16,
}
impl AudioHeader {
/// Samples of one block, for one channel.
pub fn block_samples(&self) -> u32 {
let n = u32::from(self.frame_length);
if self.flags & 0x8000 != 0 { n / 2 } else { n }
}
/// Whether the sound is IMA ADPCM, which `craft_audio::vmd` does not decode.
pub fn is_ima_adpcm(&self) -> bool {
self.flags & 0x10 != 0
}
}
/// The file header.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Header {
/// Bytes 2-3: the VMD handle and version.
pub version: u16,
/// Bytes 4-5: the video codec version.
pub codec_version: u16,
/// Number of blocks.
pub blocks: u16,
/// Top coordinate of the picture on the screen.
pub top: u16,
/// Left coordinate of the picture on the screen.
pub left: u16,
/// Picture width in pixels.
pub width: u16,
/// Picture height in pixels.
pub height: u16,
/// Flags (0x1000: the file has sound, if its sample rate is not 0).
pub flags: u16,
/// Frames in every block.
pub frames_per_block: u16,
/// Offset of the frame data.
pub data_offset: u32,
/// Bytes 24-27: `iv32` (in either case) when the video is Indeo 3.
pub indeo: [u8; 4],
/// The first palette: 256 R-G-B triplets of 6-bit components (0 to 63).
pub palette: [u8; 768],
/// Recommended size of the buffer a frame is loaded into.
pub load_buffer_size: u32,
/// Size of the buffer LZ-packed video unpacks into.
pub unpack_buffer_size: u32,
/// The sound format, if the file has sound.
pub audio: Option<AudioHeader>,
/// Offset of the table of contents.
pub toc_offset: u32,
}
impl Header {
/// How the pictures are stored.
pub fn video_format(&self) -> VideoFormat {
if self.indeo.eq_ignore_ascii_case(b"iv32") {
return VideoFormat::Indeo3;
}
match self.codec_version {
5 => VideoFormat::Rgb24,
7 => VideoFormat::Indeo3,
13 => VideoFormat::Rgb16,
_ => VideoFormat::Paletted,
}
}
fn parse(h: &[u8; HEADER_LEN]) -> Result<Header> {
let u16_at = |at: usize| u16::from_le_bytes([h[at], h[at + 1]]);
let u32_at = |at: usize| u32::from_le_bytes([h[at], h[at + 1], h[at + 2], h[at + 3]]);
if usize::from(u16_at(0)) != HEADER_LEN - 2 {
return Err(Error::NotVmd);
}
let flags = u16_at(16);
// 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);
AudioHeader {
sample_rate: u16_at(804),
frame_length: length.unsigned_abs(),
bits: if length < 0 { 16 } else { 8 },
channels: if audio_flags & 0x8200 != 0 { 2 } else { 1 },
buffers: u16_at(808),
flags: audio_flags,
}
});
let mut palette = [0; 768];
palette.copy_from_slice(&h[28..796]);
Ok(Header {
version: u16_at(2),
codec_version: u16_at(4),
blocks: u16_at(6),
top: u16_at(8),
left: u16_at(10),
width: u16_at(12),
height: u16_at(14),
flags,
frames_per_block: u16_at(18),
data_offset: u32_at(20),
indeo: [h[24], h[25], h[26], h[27]],
palette,
load_buffer_size: u32_at(796),
unpack_buffer_size: u32_at(800),
audio,
toc_offset: u32_at(812),
})
}
}
/// What a frame holds, from its record in the table of contents.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FrameKind {
/// Sound.
Audio {
/// 1: one block of sound; 2: a silence mask, then blocks of sound; 3: one block of
/// silence.
flags: u8,
},
/// A picture update. The coordinates are as stored, and include the last column and row;
/// [`VmdFile::picture_rect`] places them in the picture.
Video {
/// Left column.
left: u16,
/// Top row.
top: u16,
/// Right column.
right: u16,
/// Bottom row.
bottom: u16,
/// The data begins with a new palette.
new_palette: bool,
},
/// A frame type this module does not know.
Other(u8),
}
/// One frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Frame {
/// What the frame holds.
pub kind: FrameKind,
/// The block the frame is stored in. A block is one picture period, so this is when a video
/// frame is shown. It is not when a sound frame is heard: see the module documentation.
pub block: u32,
/// Offset of the frame data.
pub offset: u64,
/// Bytes of frame data; 0 for a frame that changes nothing.
pub size: u32,
}
/// An opened VMD file: the header and the frames of every block, in file order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VmdFile {
/// The header.
pub header: Header,
/// The frames, block after block.
pub frames: Vec<Frame>,
raw_header: Vec<u8>,
/// 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.
pub fn open<S: ByteSource + ?Sized>(src: &S) -> Result<VmdFile> {
let mut raw = [0u8; HEADER_LEN];
if src.len() < HEADER_LEN as u64 {
return Err(Error::NotVmd);
}
src.read_at(0, &mut raw)?;
let header = Header::parse(&raw)?;
let blocks = u64::from(header.blocks);
let per_block = u64::from(header.frames_per_block);
let count = blocks * per_block;
if count > MAX_FRAMES {
return Err(Error::Invalid(format!("{count} frames in the table of contents")));
}
let toc_len = blocks * 6 + count * 16;
let toc_offset = u64::from(header.toc_offset);
if toc_offset < HEADER_LEN as u64 || toc_offset.checked_add(toc_len).is_none_or(|end| end > src.len()) {
return Err(Error::Invalid("the table of contents is outside the file".into()));
}
// bounded by MAX_FRAMES and by the file length
let mut toc = vec![0u8; toc_len as usize];
src.read_at(toc_offset, &mut toc)?;
let (offsets, records) = toc.split_at(blocks as usize * 6);
let mut frames = Vec::with_capacity(count as usize);
for (block, (entry, records)) in offsets.as_chunks::<6>().0.iter().zip(records.chunks_exact((per_block as usize * 16).max(1))).enumerate() {
let mut offset = u64::from(u32::from_le_bytes([entry[2], entry[3], entry[4], entry[5]]));
for r in records.as_chunks::<16>().0 {
let size = u32::from_le_bytes([r[2], r[3], r[4], r[5]]);
let u16_at = |at: usize| u16::from_le_bytes([r[at], r[at + 1]]);
let kind = match r[0] {
1 => FrameKind::Audio { flags: r[6] },
2 => FrameKind::Video { left: u16_at(6), top: u16_at(8), right: u16_at(10), bottom: u16_at(12), new_palette: r[15] & 2 != 0 },
other => FrameKind::Other(other),
};
frames.push(Frame { kind, block: block as u32, offset, size });
// at most 65 535 frames of under 4 GiB each: no overflow
offset += u64::from(size);
}
}
// the picture's place on the screen as each frame finds it: see `picture_rect`
let mut origin = (0, 0);
let origins = frames
.iter()
.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
})
.collect();
Ok(VmdFile { header, frames, raw_header: raw.to_vec(), origins })
}
/// `size` zero bytes, or `None` if they cannot be had. `vec![0; size]` panics with a capacity
/// overflow for a size the address space cannot hold, which a frame of over 2 GiB is on a 32-bit
/// target.
fn zeroed(size: usize) -> Option<Vec<u8>> {
let mut bytes = Vec::new();
bytes.try_reserve_exact(size).ok()?;
bytes.resize(size, 0);
Some(bytes)
}
impl VmdFile {
/// The 816 header bytes as stored: the configuration (`CodecParams::extradata`) of the VMD
/// video and sound decoders.
pub fn header_bytes(&self) -> &[u8] {
&self.raw_header
}
/// Read the data of frame `index`. A frame that reaches past the end of the file is an
/// error.
pub fn read_frame<S: ByteSource + ?Sized>(&self, src: &S, index: usize) -> Result<Vec<u8>> {
let f = self.frames.get(index).ok_or_else(|| Error::Invalid(format!("no frame {index}")))?;
// checked before allocating: the size is the file's word
if f.offset.checked_add(u64::from(f.size)).is_none_or(|end| end > src.len()) {
return Err(Error::Invalid(format!("frame {index} reaches past the end of the file")));
}
let mut data = zeroed(f.size as usize).ok_or_else(|| Error::Invalid(format!("frame {index} is too large to load")))?;
src.read_at(f.offset, &mut data)?;
Ok(data)
}
/// Pictures a second, as a fraction. A file with sound plays one block of sound a picture;
/// one without plays 10 pictures a second.
pub fn frame_rate(&self) -> (u32, u32) {
match &self.header.audio {
Some(a) if a.block_samples() > 0 => (u32::from(a.sample_rate), a.block_samples()),
_ => (10, 1),
}
}
/// 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 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 (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))
}
/// What a video decoder needs, in the container-neutral form the codec crates take:
/// [`CodecId::VmdVideo`] for paletted pictures, with the header as `extradata`. 16-bit,
/// 24-bit and Indeo 3 pictures are [`CodecId::Unknown`] (Indeo 3 with the tag `IV32`).
///
/// [`CodecId::VmdVideo`]: crate::CodecId::VmdVideo
/// [`CodecId::Unknown`]: crate::CodecId::Unknown
pub fn video_params(&self) -> crate::CodecParams {
use crate::{CodecId, CodecParams};
let h = &self.header;
let params = match h.video_format() {
VideoFormat::Paletted => CodecParams::new(CodecId::VmdVideo).with_extradata(self.raw_header.clone()),
VideoFormat::Indeo3 => CodecParams::new(CodecId::Unknown).with_tag(*b"IV32"),
VideoFormat::Rgb16 | VideoFormat::Rgb24 => CodecParams::new(CodecId::Unknown),
};
params.with_size(u32::from(h.width), u32::from(h.height))
}
/// What a sound decoder needs, or `None` for a file without sound: [`CodecId::VmdAudio`]
/// with the header as `extradata`, or [`CodecId::Unknown`] for IMA ADPCM sound.
///
/// [`CodecId::VmdAudio`]: crate::CodecId::VmdAudio
/// [`CodecId::Unknown`]: crate::CodecId::Unknown
pub fn audio_params(&self) -> Option<crate::CodecParams> {
use crate::{CodecId, CodecParams};
let a = self.header.audio.as_ref()?;
let params = if a.is_ima_adpcm() {
CodecParams::new(CodecId::Unknown)
} else {
CodecParams::new(CodecId::VmdAudio).with_extradata(self.raw_header.clone())
};
Some(params.with_sample_rate(u32::from(a.sample_rate)).with_channels(u16::from(a.channels)))
}
}
+205
View File
@@ -0,0 +1,205 @@
use super::*;
use crate::CodecId;
use craft_media_testkit::vmd::{Audio, Frame as F, Spec, build};
fn sample(audio: bool) -> Vec<u8> {
let mut spec = Spec::new(16, 8);
spec.audio = audio.then_some(Audio { sample_rate: 22050, frame_length: 20, buffers: 4, flags: 0 });
let video = |rect, data: &[u8]| F::video(rect, false, data.to_vec());
let mut blocks = vec![vec![video([0, 0, 15, 7], &[2; 129])], vec![video([4, 2, 7, 3], &[2; 9])], vec![video([0, 0, 15, 7], &[])]];
if audio {
for b in &mut blocks {
b.insert(0, F::audio(1, vec![0x80; 20]));
}
}
build(&spec, &blocks)
}
#[test]
fn reads_header_and_frames() {
let d = sample(true);
assert!(sniff(&d));
let f = open(&d).unwrap();
let h = &f.header;
assert_eq!((h.width, h.height, h.blocks, h.frames_per_block), (16, 8, 3, 2));
assert_eq!(h.video_format(), VideoFormat::Paletted);
assert_eq!(h.audio, Some(AudioHeader { sample_rate: 22050, frame_length: 20, bits: 8, channels: 1, buffers: 4, flags: 0 }));
assert_eq!(h.palette[765..], [63, 63, 63]);
assert_eq!(f.header_bytes(), &d[..HEADER_LEN]);
assert_eq!(f.frame_rate(), (22050, 20));
assert_eq!(f.frames.len(), 6);
let sizes: Vec<u32> = f.frames.iter().map(|f| f.size).collect();
assert_eq!(sizes, [20, 129, 20, 9, 20, 0]);
assert_eq!(f.frames.iter().map(|f| f.block).collect::<Vec<_>>(), [0, 0, 1, 1, 2, 2]);
// frames follow each other from the block's offset
assert_eq!(f.frames[0].offset, HEADER_LEN as u64);
assert_eq!(f.frames[1].offset, HEADER_LEN as u64 + 20);
assert_eq!(f.frames[3].offset, HEADER_LEN as u64 + 20 + 129 + 20);
assert_eq!(f.frames[0].kind, FrameKind::Audio { flags: 1 });
assert_eq!(f.frames[3].kind, FrameKind::Video { left: 4, top: 2, right: 7, bottom: 3, new_palette: false });
assert_eq!(f.read_frame(&d, 3).unwrap(), [2; 9]);
assert_eq!(f.read_frame(&d, 5).unwrap(), [0u8; 0]);
assert!(f.read_frame(&d, 6).is_err());
let v = f.video_params();
assert_eq!((v.codec, v.width, v.height, v.extradata.len()), (CodecId::VmdVideo, Some(16), Some(8), HEADER_LEN));
let a = f.audio_params().unwrap();
assert_eq!((a.codec, a.sample_rate, a.channels), (CodecId::VmdAudio, Some(22050), Some(1)));
}
#[test]
fn silent_file_plays_ten_pictures_a_second() {
let f = open(&sample(false)).unwrap();
assert_eq!(f.header.audio, None);
assert!(f.audio_params().is_none());
assert_eq!(f.frame_rate(), (10, 1));
assert_eq!(f.frames.len(), 3);
}
#[test]
fn sound_formats() {
let open_with = |frame_length, flags| {
let mut spec = Spec::new(4, 4);
spec.audio = Some(Audio { sample_rate: 11025, frame_length, buffers: 1, flags });
let f = open(&build(&spec, &[])).unwrap();
let a = f.header.audio.unwrap();
(a.bits, a.channels, a.block_samples(), f.audio_params().unwrap().codec)
};
assert_eq!(open_with(-500, 0), (16, 1, 500, CodecId::VmdAudio));
// new-style stereo counts one channel, old-style both
assert_eq!(open_with(-500, 0x200), (16, 2, 500, CodecId::VmdAudio));
assert_eq!(open_with(500, 0x8000), (8, 2, 250, CodecId::VmdAudio));
assert_eq!(open_with(i16::MIN, 0), (16, 1, 32768, CodecId::VmdAudio));
assert_eq!(open_with(-500, 0x10).3, CodecId::Unknown);
// sound needs the header flag and a sample rate
let mut d = sample(true);
d[804..806].fill(0);
assert_eq!(open(&d).unwrap().header.audio, None);
let mut d = sample(true);
d[17] &= !0x10;
assert_eq!(open(&d).unwrap().header.audio, None);
}
#[test]
fn other_picture_formats_are_not_vmd_video() {
let params = |patch: fn(&mut Vec<u8>)| {
let mut d = sample(false);
patch(&mut d);
let f = open(&d).unwrap();
(f.header.video_format(), f.video_params().codec, f.video_params().tag)
};
assert_eq!(params(|d| d[4] = 5), (VideoFormat::Rgb24, CodecId::Unknown, None));
assert_eq!(params(|d| d[4] = 13), (VideoFormat::Rgb16, CodecId::Unknown, None));
assert_eq!(params(|d| d[4] = 7), (VideoFormat::Indeo3, CodecId::Unknown, Some(*b"IV32")));
assert_eq!(params(|d| d[24..28].copy_from_slice(b"iv32")).0, VideoFormat::Indeo3);
}
/// The cases ffmpeg was checked on. The picture is 20x10 and every frame has data unless said.
#[test]
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, size)| vec![F::video(rect, false, vec![2; size])]).collect();
let f = open(&build(&spec, &blocks)).unwrap();
(0..f.frames.len()).map(|i| f.picture_rect(i)).collect::<Vec<_>>()
};
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], 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), &[([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)]);
// and so is one as high but not as wide
assert_eq!(rects((0, 0), &[([3, 2, 10, 11], 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]
);
}
#[test]
fn rejects_what_is_not_vmd() {
assert!(matches!(open(&[0u8; 4][..]), Err(Error::NotVmd)));
assert!(matches!(open(&vec![0u8; 2000]), Err(Error::NotVmd)));
assert!(!sniff(b"RIFF"));
// the shorter header of later revisions
let mut d = sample(false);
d[0] = 0x32;
d[1] = 0;
assert!(matches!(open(&d), Err(Error::NotVmd)));
}
#[test]
fn table_of_contents_must_be_in_the_file() {
let d = sample(true);
assert!(matches!(open(&d[..d.len() - 1]), Err(Error::Invalid(_))));
let mut far = d.clone();
far[812..816].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(matches!(open(&far), Err(Error::Invalid(_))));
let mut early = d.clone();
early[812..816].copy_from_slice(&0u32.to_le_bytes());
assert!(matches!(open(&early), Err(Error::Invalid(_))));
// 65 535 blocks of 65 535 frames is refused before anything is allocated
let mut many = d.clone();
many[6..8].copy_from_slice(&[0xFF; 2]);
many[18..20].copy_from_slice(&[0xFF; 2]);
assert!(matches!(open(&many), Err(Error::Invalid(e)) if e.contains("frames in the table")));
}
#[test]
fn frame_past_the_end_is_an_error() {
let mut d = sample(false);
let toc = u32::from_le_bytes([d[812], d[813], d[814], d[815]]) as usize;
// first frame record: its size field
let record = toc + 3 * 6;
d[record + 2..record + 6].copy_from_slice(&u32::MAX.to_le_bytes());
let f = open(&d).unwrap();
assert!(matches!(f.read_frame(&d, 0), Err(Error::Invalid(_))));
}
/// `vec![0; size]` panics for a size past `isize::MAX`, which a frame of over 2 GiB is on a
/// 32-bit target; the frame buffer must not.
#[test]
fn a_buffer_that_cannot_be_had_is_not_a_panic() {
assert_eq!(zeroed(usize::MAX), None);
assert_eq!(zeroed(isize::MAX as usize + 1), None);
assert_eq!(zeroed(3), Some(vec![0; 3]));
}
#[test]
fn hostile_input_never_panics() {
for (i, seed) in [sample(true), sample(false)].iter().enumerate() {
craft_media_testkit::hostile::hammer(&format!("vmd seed {i}"), seed, 30_000, |d| {
if let Ok(f) = open(d) {
let n = f.frames.len();
for k in [0, n / 2, n.saturating_sub(1), n, usize::MAX] {
let _ = f.read_frame(d, k);
}
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());
}
});
}
}
+68
View File
@@ -0,0 +1,68 @@
//! VMD files written by the test kit (ffmpeg cannot write VMD), read by ffprobe (skipped without
//! it): the picture size, the sound format and the picture rate agree with what the demuxer
//! reports.
use std::process::Command;
use craft_media::vmd::open;
use craft_media_testkit::vmd::{Audio, Frame, Spec, build};
/// `key=value` lines of ffprobe's stream description.
fn probe(bytes: &[u8], name: &str) -> Option<String> {
let ffprobe = craft_media_testkit::ffprobe()?;
let dir = craft_media_testkit::private_dir("vmd-probe");
let path = dir.join(name);
std::fs::write(&path, bytes).unwrap();
let out = Command::new(ffprobe)
.args(["-v", "error", "-show_entries", "stream=codec_name,width,height,sample_rate,channels,r_frame_rate", "-of", "default=nw=1"])
.arg(&path)
.output()
.unwrap();
std::fs::remove_dir_all(&dir).unwrap();
Some(String::from_utf8_lossy(&out.stdout).into_owned())
}
#[test]
fn ffprobe_agrees_on_the_streams() {
// (frame length field, audio flags): 8-bit mono, 16-bit mono, new and old stereo
let sounds = [None, Some((20i16, 0u16)), Some((-20, 0)), Some((-20, 0x200)), Some((-20, 0x8000)), Some((20, 0x8000))];
for (i, sound) in sounds.into_iter().enumerate() {
let mut spec = Spec::new(32, 24);
spec.audio = sound.map(|(frame_length, flags)| Audio { sample_rate: 22050, frame_length, buffers: 4, flags });
let mut picture = vec![2u8];
picture.extend(std::iter::repeat_n(7, 32 * 24));
let blocks: Vec<Vec<Frame>> = (0..3)
.map(|_| {
let mut block = vec![Frame::video([0, 0, 31, 23], false, picture.clone())];
if sound.is_some() {
// one block of silence
block.insert(0, Frame::audio(3, vec![]));
}
block
})
.collect();
let bytes = build(&spec, &blocks);
let f = open(&bytes).unwrap();
let Some(report) = probe(&bytes, &format!("streams{i}.vmd")) else { return };
let has = |line: &str| assert!(report.lines().any(|l| l == line), "case {i}: no `{line}` in\n{report}");
has("codec_name=vmdvideo");
has(&format!("width={}", f.header.width));
has(&format!("height={}", f.header.height));
let (num, den) = f.frame_rate();
let g = gcd(num, den);
has(&format!("r_frame_rate={}/{}", num / g, den / g));
match f.header.audio {
Some(a) => {
has("codec_name=vmdaudio");
has(&format!("sample_rate={}", a.sample_rate));
has(&format!("channels={}", a.channels));
}
None => assert!(!report.contains("vmdaudio"), "case {i}"),
}
}
}
fn gcd(a: u32, b: u32) -> u32 {
if b == 0 { a } else { gcd(b, a % b) }
}
+17
View File
@@ -78,3 +78,20 @@ is MIT OR Apache-2.0 like the rest of the repository. Vendor binaries were not d
decompiled or debugged. The line-segment overcut is this crate's own geometric rule, not a
captured vendor stream. When extending the crate, keep to this: public documentation and
observed device behaviour, never GPL driver source.
## HP-GL byte lexer
`hpgl::lex` also exposes a borrowing HP-GL/2 lexer with PCL/PJL framing,
label/comment skipping and encoded polyline values. It does not interpret drawing
commands or replace the existing cutter encoder. The caller supplies numeric
storage and controls document/geometry budgets; scanning time is proportional to
input consumed, not capped by this API. PJL language detection copies at most 256
bytes of a line. Malformed-input recovery retains the original VectorCraft behavior,
except that only `@PJL ENTER LANGUAGE` selects a language: COMMENT/ECHO/SET text
mentioning LANGUAGE no longer hides subsequent HP-GL commands. This is not a full
PJL validator; the remaining permissive language-value handling is unchanged.
This module comes from dotCooCoo's VectorCraft `crates/cad/src/hpgl/lex.rs`,
commit `74ea25cd6c4dffa4cd41f6ee9a76f7afd4225622` (MIT OR Apache-2.0),
with public visibility for reuse. The drawing interpreter and export policies remain
in VectorCraft. Existing plotter encoders and their device limits are unchanged.
+3
View File
@@ -7,6 +7,9 @@
//! bottom-left and y points up, so the design is flipped about its bottom edge. Force and speed
//! are set on the machine's panel.
/// Byte-oriented HP-GL/2 lexer, including PCL/PJL framing and encoded polylines.
pub mod lex;
use crate::{Command, Error, Framing, Job, Program, y_up};
/// Plotter units per mm (1 plu = 0.025 mm).
+563
View File
@@ -0,0 +1,563 @@
//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow
//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the
//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped,
//! with the data their escapes carry.
/// The end-of-text character, the default label terminator.
pub const ETX: u8 = 3;
const ESC: u8 = 0x1b;
/// The most digits of a number that count: longer ones are read as their first digits.
const MAX_DIGITS: usize = 18;
/// What the bytes being read hold.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
/// HP-GL instructions.
Hpgl,
/// PCL or HP RTL: escape sequences and their data, nothing to draw.
Pcl,
/// After a Universal Exit Language: PJL lines until a language starts.
Pjl,
}
/// One item of a PE (Polyline Encoded) instruction.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PeItem {
/// Select pen.
Pen(i64),
/// Rectangle mode: the following coordinates come in fours.
Rect,
/// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`).
Point { x: f64, y: f64, up: bool, absolute: bool },
}
/// The state of one PE instruction being read.
#[derive(Clone, Copy, Debug, Default)]
pub struct Pe {
seven_bit: bool,
fraction_bits: u32,
up: bool,
absolute: bool,
}
pub struct Lexer<'a> {
b: &'a [u8],
at: usize,
mode: Mode,
/// The file holds HP RTL or PCL raster image data.
pub raster: bool,
}
/// Is `c` a byte that separates numeric parameters (or white space between instructions)?
fn separator(c: u8) -> bool {
matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0)
}
impl<'a> Lexer<'a> {
pub fn new(b: &'a [u8]) -> Self {
Self { b, at: 0, mode: Mode::Hpgl, raster: false }
}
fn peek(&self) -> Option<u8> {
self.b.get(self.at).copied()
}
/// Whether everything has been read.
pub fn done(&self) -> bool {
self.at >= self.b.len()
}
/// How many bytes have been read.
pub fn pos(&self) -> usize {
self.at
}
/// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and
/// escape sequences may come before it (anything else gives `None`, as the end does).
pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> {
loop {
let c = self.peek()?;
if c == ESC {
self.escape();
continue;
}
match self.mode {
Mode::Pcl => {
self.at += 1;
continue;
}
Mode::Pjl => {
if separator(c) {
self.at += 1;
} else if c == b'@' {
self.pjl_line();
} else {
self.mode = Mode::Hpgl;
}
continue;
}
Mode::Hpgl => {}
}
let next = self.b.get(self.at + 1).copied();
if c.is_ascii_alphabetic()
&& let Some(n) = next.filter(u8::is_ascii_alphabetic)
{
self.at += 2;
return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]);
}
if strict && !(separator(c) || c == b';' || c < 0x20) {
return None;
}
self.at += 1;
}
}
/// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows.
fn pjl_line(&mut self) {
let rest = &self.b[self.at..];
let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1);
// A command names its language within its first 256 bytes; longer lines aren't copied.
let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase();
// COMMENT/ECHO text may mention LANGUAGE without changing the printer language.
if let Some((command, language)) = line.split_once("LANGUAGE")
&& command.split_ascii_whitespace().eq(["@PJL", "ENTER"])
{
let lang = language.trim_start_matches([' ', '\t', '=']).trim();
self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl };
}
self.at += end;
}
/// An escape sequence at the current byte, with the data it carries.
fn escape(&mut self) {
self.at += 1;
let Some(c) = self.peek() else { return };
self.at += 1;
match c {
// Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL,
// `ESC%#A` to PCL or HP RTL).
b'%' => {
let (_, end) = self.value();
match end {
Some(b'X') => self.mode = Mode::Pjl,
Some(b'B') => self.mode = Mode::Hpgl,
Some(b'A') => self.mode = Mode::Pcl,
_ => {}
}
}
// Reset: PCL follows, until a language switch.
b'E' => self.mode = Mode::Pcl,
// HP-GL device control: `ESC.` and a letter, with parameters up to a colon.
b'.' => {
let Some(kind) = self.peek() else { return };
self.at += 1;
if !b"()YZBEJKLORUX".contains(&kind) {
let rest = &self.b[self.at..self.b.len().min(self.at + 80)];
if let Some(n) = rest.iter().position(|&c| c == b':')
&& rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b','))
{
self.at += n + 1;
}
}
}
// Parameterized PCL: a group character, then values each ending in a letter (upper case
// ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print
// data) are followed by that many bytes of data. Without a group character (`ESC(8U`,
// `ESC)0N`), one value and the letter ending it.
0x21..=0x2f => {
let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else {
self.value();
return;
};
self.at += 1;
loop {
let (v, end) = self.value();
let Some(end) = end else { return };
let upper = end.to_ascii_uppercase();
if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') {
let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize;
if (c, group) == (b'*', b'b') && n > 0 {
self.raster = true;
}
self.at += n;
}
if (c, group, end) == (b'*', b'r', b'A') {
self.raster = true;
}
if !end.is_ascii_lowercase() {
return;
}
}
}
// A two-character escape.
_ => {}
}
}
/// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None`
/// when that is not a letter or `@` (which is then left unread).
fn value(&mut self) -> (f64, Option<u8>) {
let v = self.number_here().unwrap_or(0.0);
match self.peek() {
Some(c) if c.is_ascii_alphabetic() || c == b'@' => {
self.at += 1;
(v, Some(c))
}
_ => (v, None),
}
}
/// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit
/// (its sign and point are read all the same).
fn number_here(&mut self) -> Option<f64> {
let mut neg = false;
if let Some(c @ (b'+' | b'-')) = self.peek() {
neg = c == b'-';
self.at += 1;
}
let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64);
let mut point = false;
while let Some(c) = self.peek() {
if c.is_ascii_digit() {
if digits < MAX_DIGITS {
if point {
scale /= 10.0;
v += f64::from(c - b'0') * scale;
} else {
v = v * 10.0 + f64::from(c - b'0');
}
} else if !point {
// Past the digits that count, an integer part keeps its size.
v *= 10.0;
}
digits += 1;
} else if c == b'.' && !point {
point = true;
} else {
break;
}
self.at += 1;
}
let v = v.min(f64::MAX);
(digits > 0).then_some(if neg { -v } else { v })
}
/// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon
/// ending it is read).
pub fn number(&mut self) -> Option<f64> {
loop {
let c = self.peek()?;
if separator(c) {
self.at += 1;
} else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') {
if let Some(v) = self.number_here() {
return Some(v);
}
} else {
if c == b';' {
self.at += 1;
}
return None;
}
}
}
/// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many.
pub fn numbers(&mut self, out: &mut [f64]) -> usize {
let mut n = 0;
while let Some(v) = self.number() {
if let Some(slot) = out.get_mut(n) {
*slot = v;
}
n += 1;
}
n.min(out.len())
}
/// Read and drop the parameters of the instruction being read: numbers and quoted strings.
pub fn params(&mut self) {
loop {
while self.number().is_some() {}
if self.peek() != Some(b'"') {
return;
}
self.quoted();
}
}
/// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader
/// doesn't know, written out in full).
pub fn closed_params(&mut self) -> bool {
while self.number().is_some() {}
self.at > 0 && self.b.get(self.at - 1) == Some(&b';')
}
/// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it
/// is one.
pub fn comment(&mut self) -> bool {
while self.peek().is_some_and(separator) {
self.at += 1;
}
match self.peek() {
Some(b'"') => self.quoted(),
Some(b';') => {
self.at += 1;
true
}
None => true,
Some(_) => false,
}
}
/// The text of a label, up to and including `terminator` (or the end).
pub fn label(&mut self, terminator: u8) {
let rest = &self.b[self.at..];
self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1);
}
/// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether
/// there was one.
pub fn quoted(&mut self) -> bool {
while self.peek().is_some_and(separator) {
self.at += 1;
}
let found = self.peek() == Some(b'"');
if found {
self.at += 1;
let rest = &self.b[self.at..];
self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1);
}
if self.peek() == Some(b';') {
self.at += 1;
}
found
}
/// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end
/// (the semicolon is read).
pub fn char(&mut self) -> Option<u8> {
let c = self.peek()?;
self.at += 1;
(c != b';').then_some(c)
}
/// The next item of a PE instruction, `None` at its end (its semicolon is read).
pub fn pe(&mut self, st: &mut Pe) -> Option<PeItem> {
loop {
let raw = self.peek()?;
let c = raw & 0x7f;
// Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored.
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
self.at += 1;
continue;
}
match c {
b';' => {
self.at += 1;
return None;
}
// Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up).
b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => {
self.at += 1;
match c {
b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()),
b'<' => st.up = true,
b'>' => match self.pe_value(st) {
Some(n) => st.fraction_bits = n.clamp(0, 52) as u32,
None => return self.end_pe(),
},
b'=' => st.absolute = true,
b'7' => st.seven_bit = true,
_ => return Some(PeItem::Rect),
}
}
_ => {
let scale = 0.5f64.powi(st.fraction_bits as i32);
let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() };
let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute };
(st.up, st.absolute) = (false, false);
return Some(item);
}
}
}
}
/// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`].
fn end_pe(&mut self) -> Option<PeItem> {
self.skip_pe();
None
}
/// The data of a PE instruction, up to and including its semicolon, unread: its data is never
/// read as instructions.
pub fn skip_pe(&mut self) {
let rest = &self.b[self.at..];
self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1);
}
/// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no
/// digit comes first, which is read).
fn pe_value(&mut self, st: &Pe) -> Option<i64> {
let (base, low, high): (u64, std::ops::RangeInclusive<u8>, std::ops::RangeInclusive<u8>) =
if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) };
let (mut v, mut place) = (0u64, 1u64);
loop {
let raw = self.peek()?;
let c = if st.seven_bit { raw & 0x7f } else { raw };
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
self.at += 1;
continue;
}
if c == b';' {
return None;
}
self.at += 1;
let (digit, last) = if low.contains(&c) {
(u64::from(c - 63), false)
} else if high.contains(&c) {
(u64::from(c - high.start()), true)
} else {
return None;
};
v = v.saturating_add(digit.saturating_mul(place));
place = place.saturating_mul(base);
if last {
// The low bit is the sign.
let n = i64::try_from(v >> 1).unwrap_or(i64::MAX);
return Some(if v & 1 == 1 { -n } else { n });
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pjl_comments_do_not_select_a_language() {
for command in ["COMMENT LANGUAGE=PCL", "ECHO ENTER LANGUAGE=PCL", "SET LANGUAGE=PCL"] {
let bytes = format!("\x1b%-12345X@PJL {command}\n@PJL ENTER LANGUAGE=HPGL2\nIN;");
assert_eq!(Lexer::new(bytes.as_bytes()).op(true), Some(*b"IN"));
}
assert_eq!(Lexer::new(b"\x1b%-12345X@pjl\tenter\tlanguage=HPGL2\r\nIN;").op(true), Some(*b"IN"));
}
#[test]
fn pjl_language_separator_accepts_horizontal_tabs() {
assert_eq!(Lexer::new(b"\x1b%-12345X@PJL ENTER LANGUAGE\t=\tHPGL2\nIN;").op(true), Some(*b"IN"));
}
#[test]
fn framing_labels_and_bounded_numbers() {
let mut lex = Lexer::new(b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\nIN;LBPU999;\x03PA1,2,3,4;SP2;");
assert_eq!(lex.op(true), Some(*b"IN"));
lex.params();
assert_eq!(lex.op(true), Some(*b"LB"));
lex.label(ETX);
assert_eq!(lex.op(true), Some(*b"PA"));
let mut values = [0.0; 2];
assert_eq!(lex.numbers(&mut values), 2);
assert_eq!(values, [1.0, 2.0]);
assert_eq!(lex.op(true), Some(*b"SP"));
assert_eq!(lex.number(), Some(2.0));
}
#[test]
fn encoded_flags_and_truncated_pair_recover_at_semicolon() {
let mut lex = Lexer::new(b"PE<=\xc1\xc3\xc5;PU;");
assert_eq!(lex.op(true), Some(*b"PE"));
let mut state = Pe::default();
assert_eq!(lex.pe(&mut state), Some(PeItem::Point { x: 1.0, y: 2.0, up: true, absolute: true }));
assert_eq!(lex.pe(&mut state), None);
assert_eq!(lex.op(true), Some(*b"PU"));
}
}
#[cfg(test)]
mod recovery_tests {
use super::*;
#[test]
fn short_encoded_payloads_terminate_with_finite_coordinates() {
for value in 0..=u16::MAX {
let [a, b] = value.to_be_bytes();
let bytes = [a, b, b';'];
let mut lex = Lexer::new(&bytes);
let mut state = Pe::default();
let mut ended = false;
for _ in 0..=bytes.len() {
let before = lex.pos();
let Some(item) = lex.pe(&mut state) else {
ended = true;
break;
};
assert!(lex.pos() > before);
assert!(lex.pos() <= bytes.len());
if let PeItem::Point { x, y, .. } = item {
assert!(x.is_finite() && y.is_finite());
}
}
assert!(ended);
}
}
#[test]
fn pcl_payloads_are_never_interpreted_as_plot_commands() {
for escape in [b"\x1b*b6W".as_slice(), b"\x1b*b6V", b"\x1b&p6X"] {
let mut bytes = escape.to_vec();
bytes.extend(b"PD9,9;\x1b%0BIN;");
let mut lex = Lexer::new(&bytes);
assert_eq!(lex.op(true), Some(*b"IN"));
assert_eq!(lex.raster, escape.starts_with(b"\x1b*b"));
}
for prefix in [
b"\x1bEgarbage\x1b%0B".as_slice(),
b"\x1b(8U",
b"\x1b.r12,3:",
b"\x1b.Y",
b"\x1b*z1a2B",
b"\x1b0",
b"\x1b%-12345X@PJL ENTER LANGUAGE=PCL\nignored\x1b%0B",
] {
let mut bytes = prefix.to_vec();
bytes.extend(b"IN;");
assert_eq!(Lexer::new(&bytes).op(true), Some(*b"IN"));
}
let mut raster = Lexer::new(b"\x1b*r1AIN;");
assert_eq!(raster.op(true), Some(*b"IN"));
assert!(raster.raster);
for bytes in [b"\x1b".as_slice(), b"\x1b.", b"\x1b*b", b"\x1b*b999999999999Wshort"] {
let mut lex = Lexer::new(bytes);
assert_eq!(lex.op(false), None);
assert!(lex.done());
}
}
#[test]
fn malformed_parameters_comments_and_label_delimiters_preserve_boundaries() {
let mut lex = Lexer::new(b" +-.12,999999999999999999999999999999;PU;");
assert_eq!(lex.number(), Some(-(0.1 + 0.02)));
assert!(lex.number().is_some_and(f64::is_finite));
assert_eq!(lex.number(), None);
assert_eq!(lex.op(true), Some(*b"PU"));
for (bytes, closed) in [(b"1,2;".as_slice(), true), (b"1,2PU", false)] {
assert_eq!(Lexer::new(bytes).closed_params(), closed);
}
for (bytes, valid) in [(b" \"PD9,9;\";".as_slice(), true), (b";", true), (b"", true), (b"unquoted", false)] {
assert_eq!(Lexer::new(bytes).comment(), valid);
}
let mut lex = Lexer::new(b"1,2\"label\";SP3;");
lex.params();
assert_eq!(lex.op(true), Some(*b"SP"));
assert!(!Lexer::new(b"bad").quoted());
assert_eq!(Lexer::new(b";").char(), None);
assert_eq!(Lexer::new(b"@").char(), Some(b'@'));
assert_eq!(Lexer::new(b"1IN;").op(true), None);
assert_eq!(Lexer::new(b"1IN;").op(false), Some(*b"IN"));
let mut lex = Lexer::new(b"unterminated");
lex.label(ETX);
assert!(lex.done());
}
}
+10 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-video"
description = "Clean-room pure-Rust video codecs, one feature per codec: DNxHD/DNxHR, VP8, ProRes, H.264, HEVC, VP9, AV1, MPEG-4 Part 2."
description = "Clean-room pure-Rust video codecs, one feature per codec: DNxHD/DNxHR, VP8, ProRes, H.264, HEVC, VP9, AV1, MPEG-4 Part 2, Sierra VMD."
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -62,6 +62,9 @@ av1-decode = []
av1-encode = ["craft-media/isobmff"]
# Tiled AV1 fallback for frames that exceed the clean-room encoder's single-tile limits.
av1-large-encode = ["av1-encode", "dep:rav1e"]
# Sierra VMD video (8-bit paletted): decoder; `vmd` turns it on too.
vmd = ["vmd-decode"]
vmd-decode = []
# Decode and encode across worker threads (rayon) in the codecs that support it.
threads = ["dep:rayon", "rav1e?/threading"]
@@ -77,8 +80,12 @@ rav1e = { version = "0.8", default-features = false, optional = true }
[dev-dependencies]
craft-media-testkit = { workspace = true }
# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test.
craft-media = { workspace = true, features = ["avi"] }
# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test, and the VMD demuxer for the VMD decoder's.
craft-media = { workspace = true, features = ["avi", "vmd"] }
[[test]]
name = "vmd"
required-features = ["vmd-decode"]
[[test]]
name = "hap"
+4 -1
View File
@@ -30,6 +30,7 @@ No codec feature is on by default.
| `hevc` | [`hevc`](src/hevc/decode/README.md) | ITU-T H.265 / HEVC: decoder (`hevc-decode` alone) and encoder (`hevc-encode` alone) |
| `vp9` | [`vp9`](src/vp9/decode/README.md) | VP9: decoder (`vp9-decode` alone) and encoder (`vp9-encode` alone) |
| `av1` | [`av1`](src/av1/decode/README.md) | AV1 (AOMedia Video 1): decoder (`av1-decode` alone) and clean-room encoder (`av1-encode`); tiled rav1e fallback for large frames (`av1-large-encode`) |
| `vmd` | `vmd` | Sierra VMD video (the 8-bit paletted pictures of Sierra and Coktel Vision game videos): decoder (`vmd-decode`) |
| `threads` | — | Multi-threaded slice/row parallelism via `rayon` |
## Decoded frames
@@ -41,7 +42,9 @@ comes with its codec's feature):
- Planes are `[Y, Cb, Cr]`, `[R, G, B]` or `[Y]` (`ColorFamily`), plus an optional alpha plane.
DNx, VP9 and AV1 (identity matrix) store RGB as G, B, R; the conversion reorders them.
- Samples keep the decoder's storage, `u8` or `u16`, with a bit depth per plane (HEVC chroma may
differ from luma). Converting moves the buffers and copies no samples.
differ from luma). Converting moves the buffers and copies no samples, except for paletted
video: VMD holds its picture as palette indices in the decoder, so `VideoFrame::try_from(&decoder)`
looks them up and writes new 8-bit R, G, B planes.
- Chroma subsampling is a log2 shift per axis, 0 to 3 (FFV1 codes up to 3).
- Colour is given as ITU-T H.273 code points (`ColorTags`), mapped from each codec's own
signalling. Codecs that do not signal a value leave it unspecified (2).
+34
View File
@@ -369,3 +369,37 @@ impl TryFrom<crate::ffv1::Frame> for VideoFrame {
Ok(f)
}
}
#[cfg(feature = "vmd-decode")]
impl TryFrom<&crate::vmd::Decoder> for VideoFrame {
type Error = FrameError;
/// The decoder's current picture, its palette indices looked up in its palette: 8-bit R, G, B
/// planes at full size (the samples are copied, as VMD stores none of them as planes). VMD
/// signals no colour description beyond RGB, nor timing.
fn try_from(d: &crate::vmd::Decoder) -> Result<Self, FrameError> {
paletted(d.width(), d.height(), d.indices(), d.palette())
}
}
/// A picture of palette indices, `width` a row, as 8-bit R, G, B planes. Matrix 0 (identity), the
/// other colour tags unspecified.
#[cfg(feature = "vmd-decode")]
fn paletted(width: usize, height: usize, indices: &[u8], palette: &[[u8; 3]; 256]) -> Result<VideoFrame, FrameError> {
let too_large = FrameError::Shape("picture size does not fit in u32");
let (w, h) = (u32::try_from(width).map_err(|_| too_large.clone())?, u32::try_from(height).map_err(|_| too_large)?);
let n = width.checked_mul(height).ok_or(FrameError::Shape("picture size overflows"))?;
let indices = indices.get(..n).ok_or(FrameError::Plane("fewer palette indices than pixels"))?;
let mut planes = [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)];
for &i in indices {
let [r, g, b] = palette[usize::from(i)];
planes[0].push(r);
planes[1].push(g);
planes[2].push(b);
}
let [r, g, b] = planes;
let planes = vec![Plane::packed(w, h, 8, Samples::U8(r))?, Plane::packed(w, h, 8, Samples::U8(g))?, Plane::packed(w, h, 8, Samples::U8(b))?];
let mut f = VideoFrame::new(w, h, ColorFamily::Rgb, Subsampling::S444, planes, None)?;
f.color.matrix = 0;
Ok(f)
}
+3 -1
View File
@@ -4,7 +4,9 @@
//! common: planar samples at their stored width (`u8` or `u16`), per-plane bit depth, chroma
//! subsampling, an optional alpha plane, colour tags as ITU-T H.273 code points, and timing.
//! Every decoder output converts into it with `VideoFrame::try_from`, behind the codec's feature.
//! A conversion moves the sample buffers; it does not copy or rescale samples.
//! A conversion moves the sample buffers; it does not copy or rescale samples. Paletted video is
//! the exception: VMD's decoder holds palette indices, and converting it (`&vmd::Decoder`) writes
//! new 8-bit R, G, B planes from its palette.
//!
//! Plane order is fixed by [`ColorFamily`]: `[Y, Cb, Cr]`, `[R, G, B]` or `[Y]`. Decoders that
//! store RGB in another order (DNx, VP9 and identity-matrix AV1 store G, B, R) are reordered by
+4
View File
@@ -18,6 +18,7 @@
//! | `hevc` | [`hevc`] | ITU-T H.265 / HEVC: decoder (`hevc-decode`) and encoder (`hevc-encode`) |
//! | `vp9` | [`vp9`] | VP9: decoder (`vp9-decode`) and encoder (`vp9-encode`) |
//! | `av1` | [`av1`] | AV1 (AOMedia Video 1): decoder (`av1-decode`) and encoder (`av1-encode`) |
//! | `vmd` | [`vmd`] | Sierra VMD video (8-bit paletted): decoder (`vmd-decode`) |
//!
//! No codec is on by default. Feature `threads` spreads the work of the codecs that support it
//! over rayon worker threads.
@@ -78,3 +79,6 @@ pub mod raw_video;
/// Bounded Screen Video key-frame decoding (FLV codec 3).
#[cfg(feature = "screen-video")]
pub mod screen_video;
#[cfg(feature = "vmd-decode")]
pub mod vmd;
+402
View File
@@ -0,0 +1,402 @@
//! Sierra VMD video decoder: the 8-bit paletted pictures of VMD (Video and Music Data) files, as
//! in Sierra's and Coktel Vision's 1990s games.
//!
//! Clean-room, from the public format description at <https://wiki.multimedia.cx/index.php/VMD>
//! ("Description of the Sierra Video and Music Data (VMD) Format", Mike Melanson and Vladimir
//! Gneushev). Where the description leaves a choice open, the decoder does what ffmpeg does with
//! the same bytes, observed from outside on files made by this crate's tests:
//!
//! - a frame's new palette replaces all 256 entries, whatever the two bytes before it say;
//! - a line of a method 1 or 3 frame must fill its width exactly.
//!
//! A [`Decoder`] is made from the 816-byte file header and holds one picture of palette indices.
//! Each video frame updates a rectangle of it: [`Decoder::decode`] takes the rectangle and the
//! palette flag from the frame's record in the file's table of contents (`craft_media::vmd`
//! reads both) and the frame data. The first frame of a file paints the whole picture; every
//! later frame depends on the ones before it, so decoding starts at the first frame.
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let bytes: Vec<u8> = Vec::new();
//! use craft_media::vmd::{FrameKind, open};
//! use craft_video::vmd::{Decoder, Rect};
//!
//! let file = open(&bytes)?;
//! 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 data = file.read_frame(&bytes, i)?;
//! match file.picture_rect(i) {
//! Some(rect) => decoder.decode(Rect::from(rect), new_palette, &data)?,
//! // a frame that paints nothing in the picture can still bring a palette
//! None if new_palette => decoder.decode_palette(&data)?,
//! None => {}
//! }
//! let rgb = decoder.rgb24(); // the picture after this block
//! }
//! # Ok(())
//! # }
//! ```
//!
//! Not decoded: the 16-bit and 24-bit pictures and the Indeo 3 video of later Coktel Vision
//! files ([`Error::Unsupported`]).
//!
//! Input is treated as hostile: the picture is checked against the decode memory budget
//! ([`crate::budget`]), LZ output is bounded by the header's unpack buffer size and by a few
//! bytes a pixel of the picture, and every copy is bounds-checked. No `unsafe`, no panics.
#![warn(missing_docs)]
use crate::budget::{DECODE_MEMORY_BUDGET, PictureShape};
/// Bytes of the VMD file header a [`Decoder`] is made from.
pub const HEADER_LEN: usize = 816;
/// Errors from decoding VMD video.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
/// The header or a frame is not valid.
#[error("invalid VMD video: {0}")]
Invalid(&'static str),
/// Valid, but not something this decoder handles.
#[error("unsupported VMD video: {0}")]
Unsupported(&'static str),
/// The picture does not fit the decode memory budget.
#[error("a VMD picture of {0}x{1} exceeds the decode memory budget")]
TooLarge(u16, u16),
}
/// Result alias for this module.
pub type Result<T> = std::result::Result<T, Error>;
/// The part of the picture a frame updates. `right` and `bottom` are the last column and row
/// updated, not one past them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rect {
/// First column.
pub left: u16,
/// First row.
pub top: u16,
/// Last column.
pub right: u16,
/// Last row.
pub bottom: u16,
}
impl From<(u16, u16, u16, u16)> for Rect {
/// From `(left, top, right, bottom)`, as `craft_media::vmd::VmdFile::picture_rect` returns
/// it.
fn from((left, top, right, bottom): (u16, u16, u16, u16)) -> Rect {
Rect { left, top, right, bottom }
}
}
/// A VMD video decoder: one picture of palette indices and the current palette.
#[derive(Clone, Debug)]
pub struct Decoder {
width: usize,
height: usize,
indices: Vec<u8>,
palette: [[u8; 3]; 256],
/// The header's unpack buffer size: the most an LZ-packed frame may unpack to.
unpack_limit: usize,
/// LZ output of the current frame, kept between frames to save the allocation.
unpacked: Vec<u8>,
}
impl Decoder {
/// A decoder for the file whose header is `header` (its first 816 bytes; more are ignored).
/// The picture starts as index 0 everywhere, with the header's palette.
pub fn new(header: &[u8]) -> Result<Decoder> {
let h = header.get(..HEADER_LEN).ok_or(Error::Invalid("the header is shorter than 816 bytes"))?;
let u16_at = |at: usize| u16::from_le_bytes([h[at], h[at + 1]]);
if usize::from(u16_at(0)) != HEADER_LEN - 2 {
return Err(Error::Invalid("not a VMD header"));
}
if h[24..28].eq_ignore_ascii_case(b"iv32") {
return Err(Error::Unsupported("Indeo 3 video"));
}
match u16_at(4) {
5 => return Err(Error::Unsupported("24-bit pictures")),
7 => return Err(Error::Unsupported("Indeo 3 video")),
13 => return Err(Error::Unsupported("16-bit pictures")),
_ => {}
}
let (width, height) = (u16_at(12), u16_at(14));
if width == 0 || height == 0 {
return Err(Error::Invalid("the picture has no pixels"));
}
// 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));
}
let (width, height) = (usize::from(width), usize::from(height));
let mut d = Decoder {
width,
height,
indices: vec![0; width * height],
palette: [[0; 3]; 256],
unpack_limit: u32::from_le_bytes([h[800], h[801], h[802], h[803]]) as usize,
unpacked: Vec::new(),
};
d.load_palette(&h[28..796]);
Ok(d)
}
/// Picture width in pixels.
pub fn width(&self) -> usize {
self.width
}
/// Picture height in pixels.
pub fn height(&self) -> usize {
self.height
}
/// The picture as palette indices: `width * height` bytes, rows from the top.
pub fn indices(&self) -> &[u8] {
&self.indices
}
/// The current palette as 8-bit R, G, B. The file stores 6-bit components; they are widened
/// by repeating their top bits, so 63 becomes 255.
pub fn palette(&self) -> &[[u8; 3]; 256] {
&self.palette
}
/// The picture as packed 8-bit R, G, B: `width * height * 3` bytes, rows from the top.
pub fn rgb24(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(self.indices.len() * 3);
for &i in &self.indices {
out.extend_from_slice(&self.palette[usize::from(i)]);
}
out
}
/// The picture as packed 8-bit R, G, B, A with opaque alpha: `width * height * 4` bytes.
pub fn rgba8(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(self.indices.len() * 4);
for &i in &self.indices {
let [r, g, b] = self.palette[usize::from(i)];
out.extend_from_slice(&[r, g, b, 255]);
}
out
}
/// Decode one video frame into the picture. `rect` is the part of the picture the frame
/// updates and `new_palette` whether its data begins with a palette, both from the frame's
/// record; `data` is the frame data. An empty frame changes nothing.
///
/// On an error the picture holds whatever the frame had painted up to that point; later
/// frames still decode against it.
pub fn decode(&mut self, rect: Rect, new_palette: bool, data: &[u8]) -> Result<()> {
let mut data = data;
if new_palette && !data.is_empty() {
self.decode_palette(data)?;
data = &data[770..];
}
let Some((&method, body)) = data.split_first() else { return Ok(()) };
if rect.right < rect.left || rect.bottom < rect.top || usize::from(rect.right) >= self.width || usize::from(rect.bottom) >= self.height {
return Err(Error::Invalid("the frame lies outside the picture"));
}
if method & 0x80 == 0 {
return self.render(rect, method, body);
}
let mut unpacked = std::mem::take(&mut self.unpacked);
// 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;
result
}
/// Take the palette that the data of a frame with a new palette begins with, and paint
/// nothing: for a video frame that has no rectangle in the picture (an empty one, as ffmpeg
/// was seen to accept, or one outside the picture). [`Decoder::decode`] does this itself for
/// the frames it is given. An empty frame changes nothing.
pub fn decode_palette(&mut self, data: &[u8]) -> Result<()> {
if data.is_empty() {
return Ok(());
}
// first index and count (ignored, see the module documentation), then 256 entries
let chunk = data.get(..770).ok_or(Error::Invalid("the palette is cut short"))?;
self.load_palette(&chunk[2..]);
Ok(())
}
fn load_palette(&mut self, vga: &[u8]) {
for (entry, rgb) in self.palette.iter_mut().zip(vga.as_chunks::<3>().0) {
for (c, &v) in entry.iter_mut().zip(rgb) {
let v = v & 0x3F;
*c = v << 2 | v >> 4;
}
}
}
/// Paint `data` (the frame body, unpacked if it was LZ-packed) onto `rect`.
fn render(&mut self, rect: Rect, method: u8, data: &[u8]) -> Result<()> {
const SHORT: Error = Error::Invalid("the frame data ends early");
let left = usize::from(rect.left);
let width = usize::from(rect.right) - left + 1;
let rows = usize::from(rect.top)..=usize::from(rect.bottom);
let mut src = Reader(data);
match method {
// lines of runs: skip (keep the pixels of the previous picture) or copy
1 | 3 => {
for y in rows {
let line = &mut self.indices[y * self.width + left..][..width];
let mut x = 0;
while x < width {
let code = src.byte().ok_or(SHORT)?;
let n = usize::from(code & 0x7F) + 1;
let run = line.get_mut(x..x + n).ok_or(Error::Invalid("a run crosses the end of its line"))?;
if code & 0x80 != 0 {
if method == 3 && src.peek() == Some(0xFF) {
src.byte();
unpack_rle(&mut src, run)?;
} else {
run.copy_from_slice(src.take(n).ok_or(SHORT)?);
}
}
x += n;
}
}
Ok(())
}
// the pixels as they are
2 => {
for y in rows {
let line = &mut self.indices[y * self.width + left..][..width];
line.copy_from_slice(src.take(width).ok_or(SHORT)?);
}
Ok(())
}
_ => Err(Error::Unsupported("unknown rendering method")),
}
}
}
/// A cursor over frame data.
struct Reader<'a>(&'a [u8]);
impl<'a> Reader<'a> {
fn peek(&self) -> Option<u8> {
self.0.first().copied()
}
fn byte(&mut self) -> Option<u8> {
let (&b, rest) = self.0.split_first()?;
self.0 = rest;
Some(b)
}
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let (head, rest) = self.0.split_at_checked(n)?;
self.0 = rest;
Some(head)
}
}
/// Fill `run` from the run-length coding of method 3: a single byte if the run is odd, then
/// pairs of bytes, either copied or one pair repeated.
fn unpack_rle(src: &mut Reader, run: &mut [u8]) -> Result<()> {
const SHORT: Error = Error::Invalid("the frame data ends early");
const LONG: Error = Error::Invalid("run-length data overruns its run");
let mut run = run;
if run.len() % 2 == 1 {
run[0] = src.byte().ok_or(SHORT)?;
run = &mut run[1..];
}
while !run.is_empty() {
let code = src.byte().ok_or(SHORT)?;
let n = usize::from(code & 0x7F) * 2;
let (head, rest) = run.split_at_mut_checked(n).ok_or(LONG)?;
if code & 0x80 != 0 {
head.copy_from_slice(src.take(n).ok_or(SHORT)?);
} else {
let pair = src.take(2).ok_or(SHORT)?;
for p in head.as_chunks_mut::<2>().0 {
p.copy_from_slice(pair);
}
}
run = rest;
}
Ok(())
}
/// Unpack an LZ-packed frame body into `out`: the unpacked length, an optional marker that
/// selects long chains, then tag bytes whose bits (lowest first) each announce a literal byte
/// or a chain copied from a 4096-byte window of earlier output. Packed data that ends before
/// the length is reached leaves `out` short; the rendering then fails if it needs more. A length
/// above `limit` is an error; unpacking stops after `useful` bytes.
fn lz_unpack(src: &[u8], limit: usize, useful: usize, out: &mut Vec<u8>) -> Result<()> {
out.clear();
let mut src = Reader(src);
let len = src.take(4).ok_or(Error::Invalid("the frame data ends early"))?;
let mut left = u32::from_le_bytes([len[0], len[1], len[2], len[3]]) as usize;
if left > limit {
return Err(Error::Invalid("an LZ-packed frame is larger than the unpack buffer"));
}
left = left.min(useful);
let mut window = Window { bytes: [0x20; 4096], at: 0xFEE };
let mut long_chains = false;
if src.0.starts_with(&[0x34, 0x12, 0x78, 0x56]) {
src.take(4);
window.at = 0x111;
long_chains = true;
}
while left > 0 {
let Some(tag) = src.byte() else { return Ok(()) };
if tag == 0xFF && left > 8 {
let Some(raw) = src.take(8) else { return Ok(()) };
for &b in raw {
window.emit(b, out);
}
left -= 8;
continue;
}
for bit in 0..8 {
if left == 0 {
break;
}
if tag >> bit & 1 == 1 {
let Some(b) = src.byte() else { return Ok(()) };
window.emit(b, out);
left -= 1;
continue;
}
let Some(&[lo, hi]) = src.take(2).and_then(|p| p.first_chunk::<2>()) else { return Ok(()) };
let from = usize::from(lo) | usize::from(hi & 0xF0) << 4;
let mut n = usize::from(hi & 0x0F) + 3;
if long_chains && n == 18 {
let Some(more) = src.byte() else { return Ok(()) };
n += usize::from(more);
}
let n = n.min(left);
// byte by byte: a chain may read what it has just written
for i in 0..n {
window.emit(window.bytes[(from + i) & 0xFFF], out);
}
left -= n;
}
}
Ok(())
}
/// The 4096 bytes of earlier output that LZ chains copy from, and where the next byte goes.
struct Window {
bytes: [u8; 4096],
at: usize,
}
impl Window {
fn emit(&mut self, b: u8, out: &mut Vec<u8>) {
out.push(b);
self.bytes[self.at] = b;
self.at = (self.at + 1) & 0xFFF;
}
}
+538
View File
@@ -0,0 +1,538 @@
//! VMD video decoder tests. ffmpeg reads VMD but cannot write it, so the files come from the
//! test kit's VMD writer, which packs random pictures with every coding mode: the three
//! rendering methods, LZ packing with short and long chains, partial updates and palette
//! changes. The decoder must return the pictures that were packed, and the same pictures as
//! ffmpeg (skipped without ffmpeg).
use std::io::Read;
use std::process::{Command, Stdio};
use craft_media::vmd::{FrameKind, open};
use craft_media_testkit::hostile::Rng;
use craft_media_testkit::vmd::{Frame, Spec, build, delta_lines, lz_pack, palette_chunk};
use craft_video::vmd::{Decoder, Error, Rect};
/// A file and the picture (indices and 6-bit palette) expected after each block.
struct Movie {
bytes: Vec<u8>,
width: usize,
pictures: Vec<(Vec<u8>, [u8; 768])>,
/// How each frame was packed, for failure messages.
notes: Vec<String>,
}
/// Change a random rectangle of `pic` with stretches of noise, flat colour, repeated pairs,
/// 0xFF and untouched pixels; returns the rectangle.
fn mutate(rng: &mut Rng, pic: &mut [u8], w: usize, h: usize) -> [u16; 4] {
let x0 = rng.below(w);
let x1 = x0 + rng.below(w - x0);
let y0 = rng.below(h);
let y1 = y0 + rng.below(h - y0);
for y in y0..=y1 {
let mut style = rng.below(5);
let (a, b) = (rng.next_u64() as u8, rng.next_u64() as u8);
for x in x0..=x1 {
if rng.below(12) == 0 {
style = rng.below(5);
}
let p = &mut pic[y * w + x];
match style {
0 => *p = rng.next_u64() as u8,
1 => *p = a,
2 => *p = if x % 2 == 0 { a } else { b },
3 => *p = 0xFF,
_ => {}
}
}
}
[x0 as u16, y0 as u16, x1 as u16, y1 as u16]
}
fn movie(seed: u64, w: usize, h: usize, frames: usize) -> Movie {
let mut rng = Rng(seed | 1);
let mut spec = Spec::new(w as u16, h as u16);
for p in spec.palette.iter_mut() {
*p = rng.below(64) as u8;
}
let mut palette = spec.palette;
let mut prev = vec![0u8; w * h];
let mut blocks = Vec::new();
let mut pictures = Vec::new();
let mut notes = Vec::new();
for n in 0..frames {
let mut cur = prev.clone();
let rect = if n == 0 {
for p in cur.iter_mut() {
*p = rng.next_u64() as u8;
}
mutate(&mut rng, &mut cur, w, h);
[0, 0, w as u16 - 1, h as u16 - 1]
} else {
mutate(&mut rng, &mut cur, w, h)
};
let method = 1 + rng.below(3) as u8;
// the writer's method 3 needs two pixels a line; the first frame has no picture before
// it to keep pixels from, and ffmpeg refuses methods 1 and 3 there
let method = match method {
_ if n == 0 => 2,
3 if rect[0] == rect[2] => 1,
m => m,
};
let mut body = match method {
2 => (rect[1]..=rect[3]).flat_map(|y| cur[usize::from(y) * w..][usize::from(rect[0])..=usize::from(rect[2])].to_vec()).collect(),
_ => delta_lines(&prev, &cur, w, rect, method == 3, &mut rng),
};
// ffmpeg refuses LZ packing of a body of a byte or two, which no encoder would pack
let packing = if body.len() < 16 { 0 } else { rng.below(3) };
if packing > 0 {
body = lz_pack(&body, packing == 2, &mut rng);
}
let new_palette = rng.below(4) == 0;
let mut data = Vec::new();
if new_palette {
for p in palette.iter_mut() {
*p = rng.below(64) as u8;
}
data = palette_chunk(&palette);
}
data.push(method | if packing > 0 { 0x80 } else { 0 });
data.extend_from_slice(&body);
notes.push(format!("method {method}, packing {packing}, new palette {new_palette}, rect {rect:?}, body {body:02x?}"));
blocks.push(vec![Frame::video(rect, new_palette, data)]);
pictures.push((cur.clone(), palette));
prev = cur;
}
Movie { bytes: build(&spec, &blocks), width: w, pictures, notes }
}
/// The pictures of a file as the decoder gives them: indices and RGB, one for each block.
fn decode_all(bytes: &[u8]) -> Vec<(Vec<u8>, Vec<u8>)> {
let file = open(bytes).unwrap();
let mut decoder = Decoder::new(file.header_bytes()).unwrap();
let mut out = Vec::new();
for (i, frame) in file.frames.iter().enumerate() {
let FrameKind::Video { new_palette, .. } = frame.kind else { continue };
let data = file.read_frame(bytes, i).unwrap();
match file.picture_rect(i) {
Some(rect) => decoder.decode(rect.into(), new_palette, &data).unwrap(),
None if new_palette => decoder.decode_palette(&data).unwrap(),
None => {}
}
out.push((decoder.indices().to_vec(), decoder.rgb24()));
}
out
}
fn rgb(indices: &[u8], palette: &[u8; 768]) -> Vec<u8> {
indices.iter().flat_map(|&i| palette[usize::from(i) * 3..][..3].iter().map(|&v| v << 2 | v >> 4)).collect()
}
/// (seed, width, height, frames): small pictures, one wider than the longest run (128) and one
/// larger than the LZ window (4096).
const MOVIES: [(u64, usize, usize, usize); 5] = [(1, 40, 30, 40), (2, 300, 5, 30), (3, 1, 1, 6), (4, 7, 64, 30), (5, 96, 80, 12)];
/// Each picture converts into a `VideoFrame` of R, G, B planes holding the colours the decoder
/// gives as RGB.
#[test]
fn pictures_convert_to_rgb_video_frames() {
use craft_video::frame::{ColorFamily, Samples, VideoFrame};
for (seed, w, h, frames) in MOVIES {
let m = movie(seed, w, h, frames);
let file = open(&m.bytes).unwrap();
let mut decoder = Decoder::new(file.header_bytes()).unwrap();
for (i, frame) in file.frames.iter().enumerate() {
let FrameKind::Video { new_palette, .. } = frame.kind else { continue };
let data = file.read_frame(&m.bytes, i).unwrap();
match file.picture_rect(i) {
Some(rect) => decoder.decode(rect.into(), new_palette, &data).unwrap(),
None if new_palette => decoder.decode_palette(&data).unwrap(),
None => {}
}
let f = VideoFrame::try_from(&decoder).unwrap();
assert_eq!((f.width(), f.height(), f.family(), f.bit_depth()), (w as u32, h as u32, ColorFamily::Rgb, 8));
assert_eq!(f.color.matrix, 0);
let plane = |p: usize| match f.plane(p).map(|p| p.samples()) {
Some(Samples::U8(s)) => s.clone(),
other => panic!("plane {p}: {other:?}"),
};
let (r, g, b) = (plane(0), plane(1), plane(2));
let interleaved: Vec<u8> = (0..w * h).flat_map(|i| [r[i], g[i], b[i]]).collect();
assert!(interleaved == decoder.rgb24(), "movie {seed}: frame {i}");
}
}
}
#[test]
fn decodes_the_pictures_that_were_packed() {
for (seed, w, h, frames) in MOVIES {
let m = movie(seed, w, h, frames);
let got = decode_all(&m.bytes);
assert_eq!(got.len(), frames);
for (n, ((indices, rgb24), (want, palette))) in got.iter().zip(&m.pictures).enumerate() {
assert!(indices == want, "movie {seed}: indices of frame {n}");
assert!(*rgb24 == rgb(want, palette), "movie {seed}: colours of frame {n}");
}
}
}
#[test]
fn matches_ffmpeg() {
let Some(ffmpeg) = craft_media_testkit::ffmpeg_or_skip("vmd video oracle") else { return };
let dir = craft_media_testkit::private_dir("vmd-video");
for (seed, w, h, frames) in MOVIES {
let m = movie(seed, w, h, frames);
let path = dir.join(format!("movie{seed}.vmd"));
let run = |bytes: &[u8]| {
std::fs::write(&path, bytes).unwrap();
Command::new(&ffmpeg)
.args(["-v", "error", "-i"])
.arg(&path)
.args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
.output()
.unwrap()
};
let out = run(&m.bytes);
if !out.status.success() || !out.stderr.is_empty() {
// the same movie cut after each frame in turn shows which frame ffmpeg refuses
let bad = (1..=frames).find(|&k| !run(&movie(seed, w, h, k).bytes).stderr.is_empty()).map_or(0, |k| k - 1);
panic!("movie {seed}: ffmpeg refuses frame {bad} ({}): {}", m.notes[bad], String::from_utf8_lossy(&out.stderr));
}
let theirs: Vec<&[u8]> = out.stdout.chunks(m.width * h * 3).collect();
let ours = decode_all(&m.bytes);
assert_eq!(theirs.len(), ours.len(), "movie {seed}: frame count");
for (n, (theirs, (_, ours))) in theirs.iter().zip(&ours).enumerate() {
assert!(*theirs == ours.as_slice(), "movie {seed}: frame {n} differs from ffmpeg");
}
}
std::fs::remove_dir_all(&dir).unwrap();
}
/// A 16x2 decoder whose picture is all 0x40.
fn flat() -> Decoder {
let header = build(&Spec::new(16, 2), &[]);
let mut d = Decoder::new(&header).unwrap();
let mut key = vec![2u8];
key.extend([0x40; 32]);
d.decode(FULL, false, &key).unwrap();
d
}
const FULL: Rect = Rect { left: 0, top: 0, right: 15, bottom: 1 };
/// Method 3 lines as ffmpeg was seen to decode them: the second line is skipped whole.
#[test]
fn run_length_lines() {
let cases: [(&[u8], [u8; 16]); 5] = [
// 16 bytes that do not begin with 0xFF are copied
(&[0x8F, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]),
// 0xFF: a pair three times, two pairs as they are, a pair three times
(
&[0x8F, 0xFF, 3, 0xA0, 0xB0, 0x82, 1, 2, 3, 4, 3, 0xC0, 0xD0],
[0xA0, 0xB0, 0xA0, 0xB0, 0xA0, 0xB0, 1, 2, 3, 4, 0xC0, 0xD0, 0xC0, 0xD0, 0xC0, 0xD0],
),
// an odd run starts with a single byte; the last pixel is a plain run of one
(
&[0x8E, 0xFF, 0xE0, 7, 0xA0, 0xB0, 0x80, 0xE4],
[0xE0, 0xA0, 0xB0, 0xA0, 0xB0, 0xA0, 0xB0, 0xA0, 0xB0, 0xA0, 0xB0, 0xA0, 0xB0, 0xA0, 0xB0, 0xE4],
),
// skip 8, then run-length
(&[7, 0x87, 0xFF, 4, 0x50, 0x60], [0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x50, 0x60, 0x50, 0x60, 0x50, 0x60, 0x50, 0x60]),
// skip 8, then plain
(&[7, 0x87, 1, 2, 3, 4, 5, 6, 7, 8], [0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 1, 2, 3, 4, 5, 6, 7, 8]),
];
for (line, want) in cases {
let mut d = flat();
let mut data = vec![3u8];
data.extend_from_slice(line);
data.push(15);
d.decode(FULL, false, &data).unwrap();
assert_eq!(d.indices()[..16], want, "{line:x?}");
assert_eq!(d.indices()[16..], [0x40; 16], "{line:x?}");
}
// method 1 has no run-length coding: 0xFF is a pixel
let mut d = flat();
d.decode(FULL, false, &[1, 0x81, 0xFF, 9, 13, 15]).unwrap();
assert_eq!(d.indices()[..3], [0xFF, 9, 0x40]);
}
#[test]
fn lz_chains() {
let unpack = |packed: &[u8]| {
let mut d = flat();
let mut data = vec![0x82u8];
data.extend_from_slice(packed);
d.decode(FULL, false, &data).map(|()| d.indices().to_vec())
};
// three literals, a chain that repeats them, then chains into the window's fill of 0x20:
// 5 bytes, 18 bytes (the longest short chain), 3 bytes
let short = [32, 0, 0, 0, 0b0000_0111, 0x90, 0xA0, 0xB0, 0xEE, 0xF0, 0x00, 0x02, 0x00, 0x0F, 0x00, 0x00];
let mut want = vec![0x90, 0xA0, 0xB0, 0x90, 0xA0, 0xB0];
want.resize(32, 0x20);
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];
// 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);
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]);
// a tag of 0xFF with more than 8 bytes left is 8 raw bytes
let mut raw = vec![32, 0, 0, 0];
for chunk in (0u8..32).collect::<Vec<_>>().chunks(8) {
raw.push(0xFF);
raw.extend_from_slice(chunk);
}
assert_eq!(unpack(&raw).unwrap(), (0u8..32).collect::<Vec<_>>());
// with 8 bytes or fewer left, a tag of 0xFF is eight literal bits, of which only the bytes
// left are read: 13 bytes are 8 raw and 5 literals
let mut d = flat();
let tail = [0x82, 13, 0, 0, 0, 0xFF, 1, 2, 3, 4, 5, 6, 7, 8, 0xFF, 9, 10, 11, 12, 13];
d.decode(Rect { right: 12, bottom: 0, ..FULL }, false, &tail).unwrap();
assert_eq!(d.indices()[..14], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0x40]);
}
/// A frame that says it unpacks to the whole unpack buffer costs no more than its picture: the
/// same 8 packed bytes repeated would otherwise be unpacked to megabytes for every frame.
#[test]
fn lz_unpacking_stops_at_what_a_picture_can_use() {
let mut spec = Spec::new(16, 2);
spec.unpack = u32::MAX;
let mut d = Decoder::new(&build(&spec, &[])).unwrap();
// 4 GiB declared; long chains of 273 bytes from the window's fill, far more than 32 pixels
let mut data = vec![0x82, 0xFF, 0xFF, 0xFF, 0xFF, 0x34, 0x12, 0x78, 0x56];
for _ in 0..40_000 {
data.push(0);
data.extend([0x00, 0x0F, 0xFF].repeat(8));
}
let start = std::time::Instant::now();
for _ in 0..200 {
d.decode(FULL, false, &data).unwrap();
}
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<u8> = (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<u8> = (0..w * h / 2).flat_map(|i| [i as u8, (i >> 8) as u8]).collect();
assert!(d.indices() == want);
}
#[test]
fn palette_changes() {
let mut d = flat();
assert_eq!(d.palette()[0x40], [0x41; 3]);
assert_eq!(d.palette()[255], [255; 3]);
let mut palette = [0u8; 768];
palette[0x40 * 3..][..3].copy_from_slice(&[63, 1, 32]);
// a palette and nothing else
d.decode(FULL, true, &palette_chunk(&palette)).unwrap();
assert_eq!(d.palette()[0x40], [255, 4, 130]);
assert_eq!(d.rgb24()[..3], [255, 4, 130]);
assert_eq!(d.rgba8()[..4], [255, 4, 130, 255]);
assert_eq!(d.indices(), [0x40; 32]);
// every entry is replaced, whatever the first-index and count bytes say
let mut chunk = palette_chunk(&[63; 768]);
chunk[..2].copy_from_slice(&[4, 2]);
d.decode(FULL, true, &chunk).unwrap();
assert_eq!((d.palette()[0], d.palette()[255]), ([255; 3], [255; 3]));
// components are 6 bits: higher bits are dropped
d.decode(FULL, true, &palette_chunk(&[0x41; 768])).unwrap();
assert_eq!(d.palette()[7], [4; 3]);
assert_eq!(d.decode(FULL, true, &[0; 769]), Err(Error::Invalid("the palette is cut short")));
}
/// A frame whose rectangle is empty paints nothing, but its palette counts: the pictures after
/// it use it. ffmpeg was seen to do the same with such a frame.
#[test]
fn palette_of_a_frame_without_a_rectangle() {
let spec = Spec::new(4, 2);
let picture = |fill: u8| [vec![2], vec![fill; 8]].concat();
let mut palette = [0u8; 768];
palette[5 * 3..][..3].copy_from_slice(&[63, 0, 63]);
palette[6 * 3..][..3].copy_from_slice(&[0, 63, 0]);
let bytes = build(
&spec,
&[
vec![Frame::video([0, 0, 3, 1], false, picture(5))],
// right is one less than left: no pixels, a palette and a picture that is not painted
vec![Frame::video([1, 1, 0, 1], true, [palette_chunk(&palette), picture(6)].concat())],
vec![Frame::video([0, 0, 1, 0], false, picture(6)[..3].to_vec())],
],
);
assert_eq!(open(&bytes).unwrap().picture_rect(1), None);
let pictures = decode_all(&bytes);
// index 5 is dark grey in the header's palette
assert_eq!(pictures[0], (vec![5; 8], [4u8; 24].to_vec()));
assert_eq!(pictures[1], (vec![5; 8], [255, 0, 255].repeat(8)));
assert_eq!(pictures[2].0, [6, 6, 5, 5, 5, 5, 5, 5]);
assert_eq!(pictures[2].1[..9], [0, 255, 0, 0, 255, 0, 255, 0, 255]);
let mut d = flat();
d.decode_palette(&[]).unwrap();
assert_eq!(d.palette()[0x40], [0x41; 3]);
assert_eq!(d.decode_palette(&[0; 769]), Err(Error::Invalid("the palette is cut short")));
}
#[test]
fn partial_updates_and_empty_frames() {
let mut d = flat();
d.decode(Rect { left: 4, top: 1, right: 7, bottom: 1 }, false, &[2, 1, 2, 3, 4]).unwrap();
assert_eq!(d.indices()[..20], [[0x40; 4]; 5].concat());
assert_eq!(d.indices()[20..24], [1, 2, 3, 4]);
let before = d.indices().to_vec();
d.decode(FULL, false, &[]).unwrap();
assert_eq!(d.indices(), before);
assert_eq!((d.width(), d.height()), (16, 2));
}
#[test]
fn bad_frames_are_errors() {
let mut d = flat();
for rect in [Rect { right: 16, ..FULL }, Rect { bottom: 2, ..FULL }, Rect { left: 9, right: 8, ..FULL }, Rect { top: 1, bottom: 0, ..FULL }] {
assert_eq!(d.decode(rect, false, &[2; 40]), Err(Error::Invalid("the frame lies outside the picture")), "{rect:?}");
}
assert_eq!(d.decode(FULL, false, &[2; 32]), Err(Error::Invalid("the frame data ends early")));
assert_eq!(d.decode(FULL, false, &[1, 0x8F]), Err(Error::Invalid("the frame data ends early")));
// 9 + 8 pixels in a line of 16
assert_eq!(d.decode(FULL, false, &[1, 8, 7]), Err(Error::Invalid("a run crosses the end of its line")));
assert_eq!(d.decode(FULL, false, &[3, 0x8F, 0xFF, 9, 1, 2]), Err(Error::Invalid("run-length data overruns its run")));
assert_eq!(d.decode(FULL, false, &[4, 0, 0]), Err(Error::Unsupported("unknown rendering method")));
// the header allows 1 MiB of LZ output
assert_eq!(d.decode(FULL, false, &[0x82, 0, 0, 0x10, 0x01]), Err(Error::Invalid("an LZ-packed frame is larger than the unpack buffer")));
}
#[test]
fn bad_headers_are_errors() {
let good = build(&Spec::new(16, 2), &[]);
let with = |patch: &dyn Fn(&mut Vec<u8>)| {
let mut h = good.clone();
patch(&mut h);
Decoder::new(&h).err()
};
assert_eq!(with(&|_| {}), None);
assert_eq!(with(&|h| h.truncate(815)), Some(Error::Invalid("the header is shorter than 816 bytes")));
assert_eq!(with(&|h| h[0] = 0), Some(Error::Invalid("not a VMD header")));
assert_eq!(with(&|h| h[12..14].fill(0)), Some(Error::Invalid("the picture has no pixels")));
assert_eq!(with(&|h| h[4] = 5), Some(Error::Unsupported("24-bit pictures")));
assert_eq!(with(&|h| h[4] = 13), Some(Error::Unsupported("16-bit pictures")));
assert_eq!(with(&|h| h[4] = 7), Some(Error::Unsupported("Indeo 3 video")));
assert_eq!(with(&|h| h[24..28].copy_from_slice(b"IV32")), Some(Error::Unsupported("Indeo 3 video")));
// 65 535 x 65 535 is refused before anything is allocated
assert_eq!(with(&|h| h[12..16].fill(0xFF)), Some(Error::TooLarge(65535, 65535)));
}
#[test]
fn hostile_input_never_panics() {
for (seed, w, h, frames) in [(11, 24, 10, 12), (12, 140, 3, 8)] {
let m = movie(seed, w, h, frames);
craft_media_testkit::hostile::hammer(&format!("vmd video seed {seed}"), &m.bytes, 20_000, |d| {
let Ok(file) = open(d) else { return };
let Ok(mut decoder) = Decoder::new(file.header_bytes()) else { return };
for (i, frame) in file.frames.iter().enumerate() {
let FrameKind::Video { new_palette, left, top, right, bottom } = frame.kind else { continue };
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(i) {
let _ = decoder.decode(rect.into(), new_palette, &data);
}
let _ = decoder.decode_palette(&data);
}
let _ = decoder.rgb24();
});
}
}
/// Real files, for whoever has some: every `.vmd` in the directory `CRAFT_MEDIA_VMD_SAMPLES`
/// names must decode to the pictures ffmpeg gets. Game files are not redistributable, so none
/// are in the repository and the test is skipped without the variable.
#[test]
fn real_files_match_ffmpeg() {
let Some(dir) = std::env::var_os("CRAFT_MEDIA_VMD_SAMPLES").filter(|d| !d.is_empty()) else {
craft_media_testkit::skip_test("vmd samples", "CRAFT_MEDIA_VMD_SAMPLES is not set");
return;
};
let Some(ffmpeg) = craft_media_testkit::ffmpeg_or_skip("vmd video samples") else { return };
let mut paths: Vec<_> = std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| Some(e.ok()?.path()))
.filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("vmd")))
.collect();
paths.sort();
assert!(!paths.is_empty(), "no .vmd files in CRAFT_MEDIA_VMD_SAMPLES");
let mut pictures = 0u64;
for path in &paths {
let name = path.display();
let source = std::fs::File::open(path).unwrap();
let file = open(&source).unwrap();
let mut decoder = Decoder::new(file.header_bytes()).unwrap();
let mut child = Command::new(&ffmpeg)
.args(["-v", "quiet", "-i"])
.arg(path)
// passthrough: one picture a video frame, none repeated to fill blocks that have no video
.args(["-an", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut theirs_out = child.stdout.take().unwrap();
let mut theirs = vec![0u8; decoder.width() * decoder.height() * 3];
for (i, frame) in file.frames.iter().enumerate() {
let FrameKind::Video { new_palette, .. } = frame.kind else { continue };
// ffmpeg gives no picture for a frame without data
if frame.size == 0 {
continue;
}
let data = file.read_frame(&source, i).unwrap();
// as the documented loop does: a frame without a rectangle may still bring a palette
match file.picture_rect(i) {
Some(rect) => decoder.decode(rect.into(), new_palette, &data),
None if new_palette => decoder.decode_palette(&data),
None => panic!("{name}: frame {i} lies outside the picture"),
}
.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}"));
let ours = decoder.rgb24();
if theirs != ours {
let wrong: Vec<usize> = (0..ours.len() / 3).filter(|&p| ours[p * 3..][..3] != theirs[p * 3..][..3]).collect();
let (w, first) = (decoder.width(), wrong[0]);
panic!(
"{name}: frame {i} (block {}) differs from ffmpeg in {} pixels, first at ({}, {}); {:?}, data starts {:02x?}",
frame.block,
wrong.len(),
first % w,
first / w,
frame.kind,
&data[..data.len().min(8)]
);
}
pictures += 1;
}
assert_eq!(theirs_out.read(&mut theirs).unwrap(), 0, "{name}: ffmpeg has more pictures");
// pictures that match but an ffmpeg that failed are no comparison
let status = child.wait().unwrap();
assert!(status.success(), "{name}: ffmpeg exited with {status}");
}
println!("{} files, {pictures} pictures match ffmpeg", paths.len());
}
+22 -1
View File
@@ -44,6 +44,26 @@ impl Writer {
/// Adds an entry from a byte slice. A name the archive already has is an error.
pub fn add(&mut self, name: &str, data: &[u8], compression: Compression) -> Result<(), Error> {
self.add_entry(name, data, compression, 1, data.len() as u64 >= u64::from(u32::MAX) / 2)
}
/// Adds a stored entry whose payload starts on an `alignment`-byte boundary.
///
/// Entries use ordinary ZIP headers, matching the USDZ writer this replaces;
/// oversized entries fail rather than opting into ZIP64 headers.
/// USDZ uses 64. Only powers of two from 1 through 4096 are accepted, bounding
/// per-entry padding. This does not impose a total archive-size budget; callers
/// retain their format-specific size and name policies. Discard the writer after
/// a write error, just as for [`Self::add`]. Invalid alignment is rejected before
/// starting an entry.
pub fn add_stored_aligned(&mut self, name: &str, data: &[u8], alignment: u16) -> Result<(), Error> {
if !alignment.is_power_of_two() || alignment > 4096 {
return Err(Error::Write("alignment must be a power of two between 1 and 4096".into()));
}
self.add_entry(name, data, Compression::Stored, alignment, false)
}
fn add_entry(&mut self, name: &str, data: &[u8], compression: Compression, alignment: u16, large_file: bool) -> Result<(), Error> {
let (method, level) = match compression {
Compression::Stored => (zip::CompressionMethod::Stored, None),
Compression::Deflated => (zip::CompressionMethod::Deflated, Some(6)),
@@ -53,7 +73,8 @@ impl Writer {
.compression_method(method)
.compression_level(level)
.last_modified_time(zip::DateTime::default())
.large_file(data.len() as u64 >= u64::from(u32::MAX) / 2);
.large_file(large_file)
.with_alignment(alignment);
let fail = |e: &dyn std::fmt::Display| Error::Write(format!("{name}: {e}"));
self.zip.start_file(name, options).map_err(|e| fail(&e))?;
self.zip.write_all(data).map_err(|e| fail(&e))
+49
View File
@@ -0,0 +1,49 @@
use craft_zip::{Compression, Writer};
use std::io::{Cursor, Read, Write};
#[test]
fn aligned_stored_matches_previous_usdz_writer() {
for tail in 0..128 {
let payload = vec![37u8; tail];
let entries: [(&str, &[u8]); 3] = [("scene.usdc", b"PXR-USDC"), ("textures/synthetic.png", &payload), ("empty", b"")];
let mut shared = Writer::new();
let mut previous = zip::ZipWriter::new(Cursor::new(Vec::new()));
let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).with_alignment(64);
for (name, data) in entries {
shared.add_stored_aligned(name, data, 64).unwrap();
previous.start_file(name, options).unwrap();
previous.write_all(data).unwrap();
}
let bytes = shared.finish().unwrap();
assert_eq!(bytes, previous.finish().unwrap().into_inner());
let mut archive = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap();
for (i, (name, expected)) in entries.iter().enumerate() {
let mut file = archive.by_index(i).unwrap();
assert_eq!(file.name().unwrap(), *name);
assert_eq!(file.compression(), zip::CompressionMethod::Stored);
assert_eq!(file.data_start().unwrap() % 64, 0);
let mut actual = Vec::new();
file.read_to_end(&mut actual).unwrap();
assert_eq!(actual, *expected);
}
}
}
#[test]
fn invalid_alignment_does_not_start_entry_and_duplicates_fail() {
let mut writer = Writer::new();
for alignment in [0, 3, 65, 8192, u16::MAX] {
assert!(writer.add_stored_aligned("layer", b"data", alignment).is_err());
}
writer.add_stored_aligned("layer", b"data", 64).unwrap();
assert!(writer.add_stored_aligned("layer", b"again", 64).is_err());
}
#[test]
fn alignment_one_retains_ordinary_stored_bytes() {
let mut ordinary = Writer::new();
ordinary.add("entry", b"data", Compression::Stored).unwrap();
let mut aligned = Writer::new();
aligned.add_stored_aligned("entry", b"data", 1).unwrap();
assert_eq!(ordinary.finish().unwrap(), aligned.finish().unwrap());
}