mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 02:36:54 +01:00
Merge feat/craft-xtask-pins into feat/craft-xtask-pins-one-commit
This commit is contained in:
commit
4ec8a1cc62
219 files changed
+21644
-946
No files matched your search
Generated
+4
@@ -2286,6 +2286,7 @@ dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
@@ -2653,6 +2654,7 @@ dependencies = [
|
||||
"exr",
|
||||
"flate2",
|
||||
"half",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -3466,6 +3468,8 @@ dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
"craft-flow",
|
||||
"craft-html",
|
||||
"craft-markdown",
|
||||
"craft-math",
|
||||
"craft-metafile",
|
||||
"craft-wordmodel",
|
||||
|
||||
@@ -302,7 +302,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
- [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model.
|
||||
- [`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
|
||||
(`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`), Bink (`bink`) 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
|
||||
|
||||
@@ -24,7 +24,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa-
|
||||
# The symphonia fallback for the formats with no native decoder yet.
|
||||
symphonia = ["decode-native", "dep:symphonia"]
|
||||
# Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders.
|
||||
# All but Opus are also file formats of `encode` and `FileEncoder`.
|
||||
# All but Opus are also file formats of `encode` and `FileEncoder`; all are codecs of `PacketEncoder`.
|
||||
encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode", "vorbis-encode"]
|
||||
# Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files.
|
||||
lossless-encode = ["pcm-encode", "flac-encode"]
|
||||
@@ -44,6 +44,8 @@ aac-decode = ["craft-media/bitstream"]
|
||||
# The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`.
|
||||
aac-encode = ["craft-media/bitstream", "craft-media/isobmff"]
|
||||
opus-decode = []
|
||||
# SMPTE ST 302M (AES3 audio in MPEG-2 transport streams): packet decoder and encoder.
|
||||
s302m = []
|
||||
# ADPCM (`adpcm`): IMA WAV, Microsoft, Yamaha and Flash (SWF) decoders and encoders.
|
||||
adpcm = ["craft-media/bitstream"]
|
||||
# QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own.
|
||||
@@ -54,6 +56,7 @@ qoa-encode = []
|
||||
g722 = []
|
||||
# ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s).
|
||||
g726 = []
|
||||
# The Opus encoder (`opus::encoder`), and Opus through `PacketEncoder`.
|
||||
opus-encode = []
|
||||
# GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own.
|
||||
gsm = ["gsm-decode", "gsm-encode"]
|
||||
|
||||
+102
-9
@@ -34,19 +34,20 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou
|
||||
| `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none |
|
||||
| `flac-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | none |
|
||||
| `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` |
|
||||
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` |
|
||||
| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` |
|
||||
| `alac-decode` | `alac::Decoder` | none |
|
||||
| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` |
|
||||
| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none |
|
||||
| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A; `PacketEncoder` for ALAC | craft-media `isobmff` |
|
||||
| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder`; with `opus-encode`, `PacketEncoder` for Opus | none |
|
||||
| `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` |
|
||||
| `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | craft-media `ogg` |
|
||||
| `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` |
|
||||
| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` |
|
||||
| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams; `PacketEncoder` for them | craft-media `bitstream` |
|
||||
| `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` |
|
||||
| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3; `PacketEncoder` for MP3 | craft-media `bitstream` |
|
||||
| `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` |
|
||||
| `adpcm` | `adpcm::{ima, ms, yamaha, swf}`: decoders and encoders for IMA WAV, Microsoft, Yamaha and Flash ADPCM | craft-media `bitstream` |
|
||||
| `s302m` | `s302m::{decode, Encoder}`: SMPTE ST 302M packets (AES3 audio in MPEG-2 transport streams), 2 to 8 channels of 16, 20 or 24 bits | none |
|
||||
| `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 |
|
||||
@@ -313,12 +314,76 @@ file needs that step before it is written again.
|
||||
|
||||
An M4A's edit list skips the AAC encoder's priming (1024 frames) and ends at the last frame
|
||||
written, so the file decodes to the length that went in. An MP3, AC-3 or E-AC-3 stream has no
|
||||
place for that (see [Limits](#limits)). For a container of your own, use the codec modules below.
|
||||
place for that (see [Limits](#limits)). For a container of your own, use `PacketEncoder` below.
|
||||
|
||||
### Encode packets for your own container
|
||||
|
||||
`PacketEncoder` is the encode-side counterpart of `TrackDecoder`: one interface over the AAC-LC,
|
||||
ALAC, MP3, AC-3, E-AC-3 and Opus encoders for an app that muxes the audio itself (a video export
|
||||
to MP4, Matroska or MXF). It returns packets and writes no file; `FileEncoder` writes its coded
|
||||
formats through it.
|
||||
|
||||
```rust
|
||||
use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder};
|
||||
|
||||
let opts = EncodeOptions::new(EncodeFormat::Aac).with_layout(info.layout).with_bitrate(384_000);
|
||||
let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 6)?;
|
||||
for block in blocks { // planar f32 in WAV order, any length
|
||||
for p in enc.encode(&block.channels, block.frames())? {
|
||||
mux.write(p.pts, p.duration, &p.data)?; // pts and duration in samples at the rate
|
||||
}
|
||||
}
|
||||
for p in enc.finish()? {
|
||||
mux.write(p.pts, p.duration, &p.data)?;
|
||||
}
|
||||
let params = enc.codec_params(); // codec, rate, channels, extradata: what TrackDecoder::new takes
|
||||
let priming = enc.priming(); // decoded samples before the first input frame
|
||||
let padding = enc.padding(); // decoded samples after the last one
|
||||
```
|
||||
|
||||
It takes the `EncodeOptions` of `FileEncoder` and reads `rate_control`, `layout`, and for ALAC
|
||||
`bit_depth` and `dither`; `format` is ignored, so `EncodeOptions::default()` with a bit rate will
|
||||
do for any codec. Input is planar `f32` in WAV channel order. `layout` names the speakers, the
|
||||
channels are reordered into the codec's order, and ALAC's samples are quantized to the bit depth.
|
||||
`layout()` reports the speakers the stream carries, in WAV order: the codec's layout for the count
|
||||
(AAC's 5.1 has side surrounds, ALAC's back surrounds), or the AC-3 coding mode the layout chose.
|
||||
|
||||
| `CodecId` | Feature | Frames per packet | `extradata()` | `priming()` |
|
||||
|---|---|---|---|---|
|
||||
| `Aac` (LC) | `aac-encode` | 1024 | `AudioSpecificConfig` | 1024 |
|
||||
| `Alac` | `alac-encode` | 4096, the last one shorter | `alac` box payload / CodecPrivate | 0 |
|
||||
| `Mp3` | `mp3-encode` | 1152 (576 below 32 kHz), one frame per packet | empty | 1057 |
|
||||
| `Ac3`, `Eac3` | `ac3-encode`, `eac3-encode` | 1536 | empty | 256 |
|
||||
| `Opus` | `opus-encode` | 960 (20 ms) | `OpusHead` | the pre-skip |
|
||||
|
||||
The sample rates, channel counts and layouts are those of the `EncodeFormat` of the same name;
|
||||
Opus takes 48 kHz mono or stereo at a constant bit rate, 64 kbit/s per channel by default. A codec
|
||||
with no encoder here, and one whose feature is off, are `Unsupported`; settings a codec cannot take
|
||||
get the error `EncodeOptions::check` gives for the format.
|
||||
|
||||
Timing: a packet's `pts` is where its decoded audio starts, counted from the first decoded sample,
|
||||
so input frame `n` is at `n + priming()`. `finish` pads the end with silence until a decoder
|
||||
returns every input frame, and the durations add up to `priming() + frames() + padding()`. With no
|
||||
input there are no packets: the durations add up to 0 and `padding()` is 0, while `priming()` still
|
||||
reports the codec's delay. A muxer
|
||||
skips the priming (MP4: `TrackConfig::media_start` or an edit list; Matroska: `CodecDelay`; Opus:
|
||||
the pre-skip, which `OpusHead` already holds) and trims the padding (the end of an MP4 edit,
|
||||
Matroska's `DiscardPadding`). ALAC's `extradata` records the largest packet and the average bit
|
||||
rate, so read it after `finish`. `bitrate()` is the constant rate used (`None` for ALAC and AAC by
|
||||
quality); `bit_depth()` is ALAC's.
|
||||
|
||||
`encode` refuses a block without one slice per channel, or with a slice shorter than `frames`,
|
||||
and encodes nothing; the encoder stays usable, so the caller can correct the block and call again.
|
||||
After `finish`, or after encoding itself failed (the block's packets are lost), every call returns
|
||||
an error.
|
||||
E-AC-3 7.1 is encoded as 7.1, and this crate's `TrackDecoder` plays its 5.1 substream (see
|
||||
[Limits](#limits)).
|
||||
|
||||
### Encode AAC packets
|
||||
|
||||
For an `.m4a` file, use `EncodeFormat::Aac` above. `aac::Encoder` is the packet encoder behind it,
|
||||
for muxing into a container of your own:
|
||||
For an `.m4a` file, use `EncodeFormat::Aac` above, and for packets in WAV channel order,
|
||||
`PacketEncoder`. `aac::Encoder` is the codec's own encoder behind both, with the settings
|
||||
`EncodeOptions` does not have (bandwidth, TNS, M/S stereo, window shape, ADTS):
|
||||
|
||||
```rust
|
||||
use craft_audio::AudioError;
|
||||
@@ -575,7 +640,35 @@ Each codec module's rustdoc lists the coding tools it implements.
|
||||
| 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 |
|
||||
| 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 (except 24- and 32-bit packets quiet enough to shift off fewer low bytes, such as silence), same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways |
|
||||
|
||||
### ALAC encoding
|
||||
|
||||
Apple's reference encoder stores the low byte (24-bit) or low two bytes (32-bit) of every sample
|
||||
uncompressed. This encoder shifts off fewer bytes, per element and per packet, when the samples
|
||||
allow it: at 24 bits a packet that peaks below −54 dBFS keeps no uncompressed byte; at 32 bits one
|
||||
below −54 dBFS keeps one, and a mono or LFE element below −102 dBFS none (a 32-bit pair always keeps
|
||||
one). Other packets are the same as the reference's, and decoders need no change.
|
||||
|
||||
Stream sizes in MB (10⁶ bytes) for 4 minutes at 48 kHz in 4096-frame packets. "Reference" is this
|
||||
encoder with the reference's fixed shift; Apple's `afconvert` gives the same sizes for the 24-bit stereo rows. The
|
||||
music is synthetic (decaying harmonic notes over a noise floor, peaking at −3 dBFS); a stem plays
|
||||
5 or 10 seconds in every 20.
|
||||
|
||||
| Material | Depth / ch | PCM | Reference | This encoder | Saved |
|
||||
|---|---|---|---|---|---|
|
||||
| Music throughout | 24 / 2 | 69.1 | 45.5 | 45.5 | 0% |
|
||||
| Music, 2 s of digital silence at each end | 24 / 2 | 69.1 | 45.1 | 44.7 | 0.8% |
|
||||
| Stem playing half the time, digital silence between | 24 / 2 | 69.1 | 34.3 | 22.8 | 33% |
|
||||
| Stem playing a quarter of the time, digital silence between | 24 / 2 | 69.1 | 28.7 | 11.5 | 60% |
|
||||
| The same, noise at −110 dBFS in place of silence | 24 / 2 | 69.1 | 32.6 | 25.1 | 23% |
|
||||
| Quiet music, peaking at −60 dBFS | 24 / 2 | 69.1 | 27.7 | 20.1 | 27% |
|
||||
| Digital silence | 24 / 2 | 69.1 | 23.1 | 0.09 | 99.6% |
|
||||
| 5.1: music in front, surrounds a quarter of the time, silent LFE | 24 / 6 | 207.4 | 108.7 | 79.9 | 26% |
|
||||
| Stem playing a quarter of the time, digital silence between | 32 / 1 | 46.1 | 25.9 | 8.7 | 66% |
|
||||
| Stem playing a quarter of the time, digital silence between | 32 / 2 | 92.2 | 51.7 | 34.5 | 33% |
|
||||
| Quiet music, peaking at −60 dBFS | 32 / 2 | 92.2 | 50.7 | 43.2 | 15% |
|
||||
| Digital silence | 32 / 2 | 92.2 | 46.2 | 23.1 | 50% |
|
||||
|
||||
### MP3 encoding
|
||||
|
||||
|
||||
@@ -8,7 +8,11 @@
|
||||
//!
|
||||
//! The search (stereo matrixing, 4 or 8 predictor coefficients) and the state kept across
|
||||
//! packets (coefficients, the last matrixing, and the buffers the trial runs read stale parts of)
|
||||
//! follow the reference, so for the same input this writes the same packets as it.
|
||||
//! follow the reference, so for the same input this writes the same packets as it, with one
|
||||
//! exception: the shifted-off low bytes. The reference passes 1 (24-bit) or 2 (32-bit) low bytes
|
||||
//! of every sample through uncompressed, even for silence. Here an element shifts off fewer bytes
|
||||
//! in a packet whose samples fit well within the width the reference predicts (see
|
||||
//! [`packet_shift`]), so silence and quiet passages are not padded with a byte or two per sample.
|
||||
|
||||
use super::ag::{self, AgParams};
|
||||
use super::bits::{BitCounter, BitSink, BitWriter};
|
||||
@@ -100,6 +104,25 @@ fn bytes_shifted(bit_depth: u32) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes an element shifts off in one packet: the fewest, down from the reference's
|
||||
/// [`bytes_shifted`], that leave every sample at least one bit narrower than the width the
|
||||
/// reference predicts (`bit_depth − 8 · bytes_shifted`). The predictor then works on values no
|
||||
/// wider than in the reference, so its arithmetic stays in the same range; only fewer low bytes go
|
||||
/// out uncompressed. The spare bit is there because at the full width, coding the low byte through
|
||||
/// the predictor costs about as much as storing it, and for 24-bit mono measured 2% more.
|
||||
/// A 32-bit pair keeps at least 1: with none, its prediction width (33 bits) exceeds the 32 the
|
||||
/// format allows.
|
||||
fn packet_shift(bit_depth: u32, channels: &[&[i32]]) -> u32 {
|
||||
let reference = bytes_shifted(bit_depth);
|
||||
let width = bit_depth - reference * 8 - 1;
|
||||
let floor = u32::from(bit_depth == 32 && channels.len() == 2);
|
||||
let fits = |bytes: u32| {
|
||||
let (lo, hi) = (-(1i64 << (width - 1)), (1i64 << (width - 1)) - 1);
|
||||
channels.iter().flat_map(|c| c.iter()).all(|&x| (lo..=hi).contains(&i64::from(x >> (bytes * 8))))
|
||||
};
|
||||
(floor..reference).find(|&b| fits(b)).unwrap_or(reference)
|
||||
}
|
||||
|
||||
impl Encoder {
|
||||
/// An encoder for `cfg`.
|
||||
pub fn new(cfg: EncoderConfig) -> Result<Self> {
|
||||
@@ -191,11 +214,12 @@ impl Encoder {
|
||||
w.put(cpe_tag, 4);
|
||||
cpe_tag += 1;
|
||||
let (l, r) = (channels[index], channels[index + 1]);
|
||||
let bs = packet_shift(self.bit_depth, &[l, r]);
|
||||
// as in the reference, fast mode applies to stereo streams only
|
||||
if self.cfg.fast && channels.len() == 2 {
|
||||
self.encode_stereo_fast(&mut w, index, l, r)?;
|
||||
self.encode_stereo_fast(&mut w, index, l, r, bs)?;
|
||||
} else {
|
||||
self.encode_stereo(&mut w, index, l, r)?;
|
||||
self.encode_stereo(&mut w, index, l, r, bs)?;
|
||||
}
|
||||
index += 2;
|
||||
}
|
||||
@@ -203,7 +227,8 @@ impl Encoder {
|
||||
let tag = if element == ID_LFE { &mut lfe_tag } else { &mut sce_tag };
|
||||
w.put(*tag, 4);
|
||||
*tag += 1;
|
||||
self.encode_mono(&mut w, index, channels[index])?;
|
||||
let bs = packet_shift(self.bit_depth, &[channels[index]]);
|
||||
self.encode_mono(&mut w, index, channels[index], bs)?;
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
@@ -231,10 +256,10 @@ impl Encoder {
|
||||
}
|
||||
|
||||
/// `EncodeStereo`: a channel pair with the matrixing and coefficient search.
|
||||
fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> {
|
||||
/// `bs`: the bytes shifted off, from [`packet_shift`].
|
||||
fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> {
|
||||
let start = w.bit_len();
|
||||
let n = l.len();
|
||||
let bs = bytes_shifted(self.bit_depth);
|
||||
let chan_bits = self.bit_depth - bs * 8 + 1;
|
||||
let partial = self.partial(n);
|
||||
let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0);
|
||||
@@ -329,10 +354,9 @@ impl Encoder {
|
||||
}
|
||||
|
||||
/// `EncodeStereoFast`: a channel pair without matrixing or search.
|
||||
fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> {
|
||||
fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> {
|
||||
let start = w.bit_len();
|
||||
let n = l.len();
|
||||
let bs = bytes_shifted(self.bit_depth);
|
||||
let chan_bits = self.bit_depth - bs * 8 + 1;
|
||||
let partial = self.partial(n);
|
||||
let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0);
|
||||
@@ -396,10 +420,9 @@ impl Encoder {
|
||||
}
|
||||
|
||||
/// `EncodeMono`: one channel (SCE or LFE).
|
||||
fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32]) -> Result<()> {
|
||||
fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32], bs: u32) -> Result<()> {
|
||||
let start = w.bit_len();
|
||||
let n = input.len();
|
||||
let bs = bytes_shifted(self.bit_depth);
|
||||
let shift = bs * 8;
|
||||
let chan_bits = self.bit_depth - shift;
|
||||
let partial = self.partial(n);
|
||||
@@ -563,4 +586,84 @@ mod tests {
|
||||
let mut dec = Decoder::new(&enc.cookie()).unwrap();
|
||||
assert_eq!(dec.decode(&p).unwrap(), vec![noise[..4096].to_vec()]);
|
||||
}
|
||||
|
||||
/// One packet of `frames` frames per element, encoded and decoded back; its size in bytes.
|
||||
fn packet_bytes(cfg: EncoderConfig, input: &[Vec<i32>]) -> usize {
|
||||
let mut enc = Encoder::new(cfg).unwrap();
|
||||
let chunk: Vec<&[i32]> = input.iter().map(Vec::as_slice).collect();
|
||||
let p = enc.encode(&chunk).unwrap();
|
||||
let mut dec = Decoder::new(&enc.cookie()).unwrap();
|
||||
assert_eq!(dec.decode(&p).unwrap(), input, "{cfg:?}");
|
||||
p.len()
|
||||
}
|
||||
|
||||
/// The reference shifts 1 (24-bit) or 2 (32-bit) low bytes of every sample off and stores them
|
||||
/// uncompressed, so a 4096-frame stereo packet of 24-bit silence was 8224 bytes (#1368).
|
||||
#[test]
|
||||
fn silence_is_a_few_bytes_at_every_depth() {
|
||||
for bits in [16, 20, 24, 32] {
|
||||
for ch in [1, 2, 6] {
|
||||
for fast in [false, true] {
|
||||
let cfg = EncoderConfig::new(48_000, ch, bits).with_fast(fast);
|
||||
let bytes = packet_bytes(cfg, &vec![vec![0; 4096]; usize::from(ch)]);
|
||||
// a 32-bit pair keeps one shifted byte per sample: the format allows no less
|
||||
let floor = if bits == 32 { 4096 * 2 * (usize::from(ch) / 2) } else { 0 };
|
||||
assert!(bytes <= floor + 40 * usize::from(ch), "{bits} bits, {ch} ch, fast {fast}: {bytes} bytes");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quiet audio (within 12 bits) at 24 and 32 bits shifts nothing off and comes within 10% of
|
||||
/// the same audio at 16 bits (the wider prediction width makes the coder's escapes longer);
|
||||
/// the reference stored a byte or two more per sample. Samples at the edges of each width and
|
||||
/// loud audio decode exactly.
|
||||
#[test]
|
||||
fn quiet_packets_compress_like_16_bit_audio_and_loud_ones_round_trip() {
|
||||
let quiet = signal(4096, 2, 12);
|
||||
let at16 = packet_bytes(EncoderConfig::new(48_000, 2, 16), &quiet);
|
||||
let at24 = packet_bytes(EncoderConfig::new(48_000, 2, 24), &quiet);
|
||||
assert!(at24 * 10 <= at16 * 11, "24-bit {at24} bytes, 16-bit {at16}");
|
||||
let mono = vec![quiet[0].clone()];
|
||||
let at16 = packet_bytes(EncoderConfig::new(48_000, 1, 16), &mono);
|
||||
let at32 = packet_bytes(EncoderConfig::new(48_000, 1, 32), &mono);
|
||||
assert!(at32 * 10 <= at16 * 11, "32-bit mono {at32} bytes, 16-bit {at16}");
|
||||
// the samples just past each narrower width, and loud audio, decode exactly
|
||||
for bits in [24u32, 32] {
|
||||
for ch in [1u8, 2] {
|
||||
let edge: Vec<Vec<i32>> = (0..ch)
|
||||
.map(|c| {
|
||||
(0..4096)
|
||||
.map(|i| match (i + usize::from(c)) % 4 {
|
||||
0 => (16_384 << (bits - 24)) - 1,
|
||||
1 => -(16_384 << (bits - 24)),
|
||||
2 => 16_384 << (bits - 24),
|
||||
_ => -(16_384 << (bits - 24)) - 1,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &edge);
|
||||
packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &signal(4096, usize::from(ch), bits));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shift_is_the_fewest_bytes_that_keep_the_reference_width() {
|
||||
let z = [0i32; 4];
|
||||
assert_eq!(packet_shift(16, &[&z]), 0);
|
||||
assert_eq!(packet_shift(24, &[&z, &z]), 0);
|
||||
assert_eq!(packet_shift(24, &[&[16_383, -16_384], &z]), 0);
|
||||
assert_eq!(packet_shift(24, &[&[16_384], &z]), 1);
|
||||
assert_eq!(packet_shift(24, &[&[-16_385]]), 1);
|
||||
assert_eq!(packet_shift(24, &[&[32_767]]), 1);
|
||||
assert_eq!(packet_shift(32, &[&z]), 0);
|
||||
assert_eq!(packet_shift(32, &[&[16_383]]), 0);
|
||||
assert_eq!(packet_shift(32, &[&z, &z]), 1);
|
||||
assert_eq!(packet_shift(32, &[&[1 << 21]]), 1);
|
||||
assert_eq!(packet_shift(32, &[&[1 << 22]]), 2);
|
||||
assert_eq!(packet_shift(32, &[&[i32::MIN]]), 2);
|
||||
assert_eq!(packet_shift(32, &[&[i32::MAX], &z]), 2);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,9 @@
|
||||
//! reference: hostile input returns errors instead of reading or writing out of bounds, integer
|
||||
//! arithmetic wraps where C would overflow, the 4- and 8-tap predictor loops are folded into the
|
||||
//! general one (same values), the sample-width variants of the matrix routines into one routine
|
||||
//! over `i32`, and the encoder fills in the cookie's average bit rate.
|
||||
//! over `i32`, the encoder fills in the cookie's average bit rate, and it shifts off fewer low
|
||||
//! bytes in packets whose samples fit a narrower width (silence and quiet passages at 24 and 32
|
||||
//! bits), where the reference always passes them through uncompressed.
|
||||
|
||||
// The bit I/O, coder, predictor and matrix modules serve both halves; with only one of
|
||||
// `alac-decode` and `alac-encode` built, the other half's routines are unused.
|
||||
|
||||
+25
-1
@@ -23,6 +23,9 @@
|
||||
//! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`,
|
||||
//! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature
|
||||
//! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder.
|
||||
//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`,
|
||||
//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC,
|
||||
//! MP3, AC-3, E-AC-3 or Opus, with their timing and codec configuration, for an app's own muxer.
|
||||
//! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`],
|
||||
//! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF
|
||||
//! file bit for bit, and minimal files around such PCM, for essence embedded in other containers.
|
||||
@@ -32,7 +35,8 @@
|
||||
//! [`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), [`adpcm`]
|
||||
//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM),
|
||||
//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`s302m`] (`s302m`: SMPTE 302M packets),
|
||||
//! [`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).
|
||||
//!
|
||||
@@ -64,6 +68,15 @@ pub mod mp3;
|
||||
pub mod mpa;
|
||||
#[cfg(any(feature = "opus-decode", feature = "opus-encode"))]
|
||||
pub mod opus;
|
||||
#[cfg(any(
|
||||
feature = "aac-encode",
|
||||
feature = "alac-encode",
|
||||
feature = "mp3-encode",
|
||||
feature = "ac3-encode",
|
||||
feature = "eac3-encode",
|
||||
feature = "opus-encode"
|
||||
))]
|
||||
mod packet;
|
||||
#[cfg(any(
|
||||
feature = "aac-decode",
|
||||
feature = "alac-decode",
|
||||
@@ -79,6 +92,8 @@ pub mod peaks;
|
||||
pub mod qoa;
|
||||
#[cfg(feature = "decode-native")]
|
||||
mod read;
|
||||
#[cfg(feature = "s302m")]
|
||||
pub mod s302m;
|
||||
#[cfg(feature = "sbc")]
|
||||
pub mod sbc;
|
||||
#[cfg(any(
|
||||
@@ -157,6 +172,15 @@ pub use buffer::AudioBuffer;
|
||||
pub use craft_media;
|
||||
pub use craft_media::{ByteSource, CodecId, CodecParams, Container, PcmFormat, ReadSeekSource};
|
||||
pub use layout::{ChannelLayout, Speaker};
|
||||
#[cfg(any(
|
||||
feature = "aac-encode",
|
||||
feature = "alac-encode",
|
||||
feature = "mp3-encode",
|
||||
feature = "ac3-encode",
|
||||
feature = "eac3-encode",
|
||||
feature = "opus-encode"
|
||||
))]
|
||||
pub use packet::{EncodedPacket, PacketEncoder};
|
||||
#[cfg(feature = "decode-native")]
|
||||
pub use read::SharedSource;
|
||||
#[cfg(feature = "decode-native")]
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
//! [`PacketEncoder`]: one interface over the AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus encoders, for
|
||||
//! a caller that puts the packets in its own container. It takes planar `f32` in WAV channel order,
|
||||
//! maps the channels onto the codec's order, and returns packets with their timing; the coded
|
||||
//! formats of [`FileEncoder`](crate::FileEncoder) are written through it.
|
||||
|
||||
// Each codec is its own feature: with only some of them built, the other halves of the shared
|
||||
// code are unused.
|
||||
#![cfg_attr(
|
||||
not(all(
|
||||
feature = "aac-encode",
|
||||
feature = "alac-encode",
|
||||
feature = "mp3-encode",
|
||||
feature = "ac3-encode",
|
||||
feature = "eac3-encode",
|
||||
feature = "opus-encode"
|
||||
)),
|
||||
allow(dead_code, unused_imports, unused_variables, unused_mut)
|
||||
)]
|
||||
|
||||
use crate::layout::channel_map;
|
||||
use crate::{AudioError, ChannelLayout, CodecId, CodecParams, EncodeFormat, EncodeOptions, RateControl, Result};
|
||||
|
||||
/// Maximum frames handed to a codec per internal call, bounding that call's input and output.
|
||||
/// `PacketEncoder::encode` collects packets across all chunks, so its returned vector grows with
|
||||
/// the caller's input block. Also the frames of an ALAC packet.
|
||||
pub(crate) const CHUNK: usize = 4096;
|
||||
|
||||
/// Bits per second per channel when no rate is asked for: AAC and Opus.
|
||||
const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
|
||||
const OPUS_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
|
||||
/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per
|
||||
/// full-bandwidth channel).
|
||||
const DEFAULT_KBPS_PER_CHANNEL: u32 = 96;
|
||||
|
||||
/// Opus's layouts by channel count: RFC 7845 mapping family 0 (mono, and stereo as L R).
|
||||
const OPUS_LAYOUT_MASKS: [&[u32]; 2] = [&[0x4], &[0x3]];
|
||||
|
||||
/// One packet from a [`PacketEncoder`].
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct EncodedPacket {
|
||||
/// The coded bytes: an AAC raw data block (no ADTS header), an ALAC packet, one MP3 frame,
|
||||
/// one AC-3 syncframe or an E-AC-3 access unit, one Opus packet.
|
||||
pub data: Vec<u8>,
|
||||
/// Where the packet's decoded audio starts, in samples at the sample rate from the first
|
||||
/// decoded sample of the stream. The encoder's [priming](PacketEncoder::priming) comes first,
|
||||
/// so input frame `n` is at `n + priming`.
|
||||
pub pts: u64,
|
||||
/// The samples per channel the packet decodes to, the last packet's padding included.
|
||||
pub duration: u32,
|
||||
}
|
||||
|
||||
/// Encodes audio to packets of one codec, for a muxer of the caller's own: the encode-side
|
||||
/// counterpart of [`TrackDecoder`](crate::TrackDecoder). Built from a [`CodecId`] and the
|
||||
/// [`EncodeOptions`] of [`FileEncoder`](crate::FileEncoder), of which it reads the rate control,
|
||||
/// the layout, and for ALAC the bit depth and dither.
|
||||
///
|
||||
/// Input is planar `f32` in WAV channel order, one slice per channel, at any block size; packets
|
||||
/// come out as they are completed, and [`finish`](Self::finish) returns the rest. What a container
|
||||
/// needs to describe the track is on the encoder: [`codec_params`](Self::codec_params) (codec,
|
||||
/// rate, channels and [`extradata`](Self::extradata)), [`layout`](Self::layout),
|
||||
/// [`priming`](Self::priming), and after `finish` [`padding`](Self::padding).
|
||||
///
|
||||
/// | Codec | Feature | Packet | `extradata` | Priming |
|
||||
/// |---|---|---|---|---|
|
||||
/// | [`CodecId::Aac`] (LC) | `aac-encode` | 1024 frames | `AudioSpecificConfig` | 1024 |
|
||||
/// | [`CodecId::Alac`] | `alac-encode` | 4096 frames | the `alac` box / CodecPrivate | 0 |
|
||||
/// | [`CodecId::Mp3`] | `mp3-encode` | 1152 frames (576 below 32 kHz) | none | 1057 |
|
||||
/// | [`CodecId::Ac3`], [`CodecId::Eac3`] | `ac3-encode`, `eac3-encode` | 1536 frames | none | 256 |
|
||||
/// | [`CodecId::Opus`] | `opus-encode` | 960 frames (20 ms) | `OpusHead` | the pre-skip |
|
||||
///
|
||||
/// ```
|
||||
/// # #[cfg(all(feature = "aac-encode", feature = "aac-decode"))] {
|
||||
/// use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder, TrackDecoder};
|
||||
///
|
||||
/// let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128_000);
|
||||
/// let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 2)?;
|
||||
/// let block = [vec![0.25f32; 4800], vec![-0.25f32; 4800]]; // 0.1 s, one Vec per channel
|
||||
/// let mut packets = enc.encode(&block, 4800)?;
|
||||
/// packets.extend(enc.finish()?);
|
||||
/// assert_eq!(enc.priming(), 1024);
|
||||
/// assert_eq!(packets.iter().map(|p| u64::from(p.duration)).sum::<u64>(), 1024 + 4800 + enc.padding());
|
||||
///
|
||||
/// // The description a muxer writes is what a decoder reads.
|
||||
/// let mut dec = TrackDecoder::new(&enc.codec_params(), &[])?;
|
||||
/// assert_eq!(dec.decode(&packets[0].data)?.frames(), 1024);
|
||||
/// # }
|
||||
/// # Ok::<(), craft_audio::AudioError>(())
|
||||
/// ```
|
||||
pub struct PacketEncoder {
|
||||
codec: CodecId,
|
||||
inner: Inner,
|
||||
sample_rate: u32,
|
||||
/// The speakers of the channels encoded, in WAV order.
|
||||
layout: ChannelLayout,
|
||||
/// For each codec channel, the caller's channel that feeds it.
|
||||
map: Vec<usize>,
|
||||
bitrate: Option<u32>,
|
||||
/// The integer depth of a lossless codec.
|
||||
bit_depth: Option<u8>,
|
||||
/// Where the next packet starts.
|
||||
pts: u64,
|
||||
/// Frames of input taken.
|
||||
frames: u64,
|
||||
finished: bool,
|
||||
/// Set when a call failed: the packets of that block are lost, so the stream has a gap and
|
||||
/// every later call is refused.
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PacketEncoder {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PacketEncoder")
|
||||
.field("codec", &self.codec)
|
||||
.field("sample_rate", &self.sample_rate)
|
||||
.field("layout", &self.layout)
|
||||
.field("frames", &self.frames)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// A packet encoder of one of the codecs, taking planar `f32` in its own channel order.
|
||||
enum Inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Aac(Box<crate::aac::Encoder>),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Alac {
|
||||
enc: Box<crate::alac::Encoder>,
|
||||
quantizers: Vec<crate::write::pcm::Quantizer>,
|
||||
/// Quantized samples of the packet being filled, per channel.
|
||||
pending: Vec<Vec<i32>>,
|
||||
},
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Mp3 {
|
||||
enc: Box<crate::mp3::Encoder>,
|
||||
/// Bytes the encoder returned that do not yet make a whole frame.
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Ac3 {
|
||||
enc: Box<crate::ac3::encoder::Encoder>,
|
||||
/// The block with every sample finite and within ±1, as the encoder requires.
|
||||
planes: Vec<Vec<f32>>,
|
||||
},
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Opus {
|
||||
enc: Box<crate::opus::encoder::Encoder>,
|
||||
/// Interleaved samples of the frame being filled.
|
||||
pending: Vec<f32>,
|
||||
/// Frames of the decoded stream the packets so far cover.
|
||||
coded: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`.
|
||||
fn labels(mask: u32) -> String {
|
||||
ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// The speakers of the caller's layout, for an error message.
|
||||
fn given(layout: &ChannelLayout) -> String {
|
||||
layout.mask().map_or_else(|| "without speaker assignment".into(), labels)
|
||||
}
|
||||
|
||||
/// [`channel_map`] for a codec with one layout per channel count (the first of `masks`), and
|
||||
/// that layout; or why the audio does not fit.
|
||||
fn fixed_map(masks: &[u32], name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<(Vec<usize>, ChannelLayout)> {
|
||||
let Some(&mask) = masks.first() else {
|
||||
return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels())));
|
||||
};
|
||||
let map = channel_map(mask, order, layout).ok_or_else(|| {
|
||||
AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout)))
|
||||
})?;
|
||||
Ok((map, ChannelLayout::from_mask(mask)))
|
||||
}
|
||||
|
||||
/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for
|
||||
/// 8 channels configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc.
|
||||
#[cfg(feature = "aac-encode")]
|
||||
pub(super) fn aac_order(channels: usize) -> Option<&'static [usize]> {
|
||||
if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) }
|
||||
}
|
||||
|
||||
/// The lowest AAC bit rate used, per channel: 6 kbit/s, and a quarter of the sample rate (256
|
||||
/// bits a frame). The encoder accepts less, and from about half of this down codes silence; a
|
||||
/// stream of silence is no answer to a low bit rate (or to kbit/s given as bit/s).
|
||||
#[cfg(feature = "aac-encode")]
|
||||
fn aac_floor_per_channel(sample_rate: u32) -> u32 {
|
||||
(sample_rate / 4).max(6000)
|
||||
}
|
||||
|
||||
/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a
|
||||
/// quality of 0–1 spans the encoder's VBR range.
|
||||
#[cfg(feature = "aac-encode")]
|
||||
pub(super) fn aac_mode(rate: Option<RateControl>, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode {
|
||||
use crate::aac::BitrateMode;
|
||||
let (lo, hi) = crate::aac::cbr_range(sample_rate, channels);
|
||||
let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo));
|
||||
// An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone.
|
||||
let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps };
|
||||
match rate {
|
||||
None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))),
|
||||
Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)),
|
||||
// NaN stays NaN, which the encoder refuses.
|
||||
Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit rate in bits per second for a codec with constant bit rates only.
|
||||
fn constant_bps(name: &str, rate: Option<RateControl>, default: u32) -> Result<u32> {
|
||||
match rate {
|
||||
None => Ok(default),
|
||||
Some(RateControl::Bitrate(bps)) => Ok(bps),
|
||||
Some(RateControl::Quality(_)) => {
|
||||
Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding
|
||||
/// mode whose speakers the layout names, at the nearest bit rate the stream can carry.
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
pub(super) fn ac3_config(
|
||||
codec: crate::ac3::encoder::Codec,
|
||||
sample_rate: u32,
|
||||
layout: &ChannelLayout,
|
||||
rate: Option<RateControl>,
|
||||
) -> Result<(crate::ac3::encoder::Config, Vec<usize>)> {
|
||||
use crate::ac3::encoder::{Codec, CodingMode, Config};
|
||||
use CodingMode::*;
|
||||
let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" };
|
||||
let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71];
|
||||
let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| {
|
||||
// 7.1 is an E-AC-3 programme with an LFE; the encoder has no other.
|
||||
if mode == Surround71 && (codec != Codec::Eac3 || !lfe) {
|
||||
return None;
|
||||
}
|
||||
let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe };
|
||||
let map = channel_map(config.channel_layout().mask()?, None, layout)?;
|
||||
Some((config, map))
|
||||
});
|
||||
let Some((mut config, map)) = found else {
|
||||
return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout))));
|
||||
};
|
||||
let full = config.mode.channels() as u32;
|
||||
let want = constant_bps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full * 1000)? / 1000;
|
||||
// What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of
|
||||
// the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold.
|
||||
let least = if config.mode == Surround71 { 384 } else { 32 * full };
|
||||
config.bitrate_kbps = match codec {
|
||||
Codec::Ac3 => {
|
||||
let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least);
|
||||
crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor)
|
||||
}
|
||||
Codec::Eac3 => {
|
||||
let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 };
|
||||
want.clamp(least, most.max(least))
|
||||
}
|
||||
};
|
||||
Ok((config, map))
|
||||
}
|
||||
|
||||
/// The feature a codec's encoder is built with, or `None` for a codec with no encoder here.
|
||||
fn feature(codec: CodecId) -> Option<&'static str> {
|
||||
Some(match codec {
|
||||
CodecId::Aac => "aac-encode",
|
||||
CodecId::Alac => "alac-encode",
|
||||
CodecId::Mp3 => "mp3-encode",
|
||||
CodecId::Ac3 => "ac3-encode",
|
||||
CodecId::Eac3 => "eac3-encode",
|
||||
CodecId::Opus => "opus-encode",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl PacketEncoder {
|
||||
/// An encoder of `codec` for `channels` channels at `sample_rate`. Of `opts` it reads
|
||||
/// `rate_control` and `layout` (as [`FileEncoder`](crate::FileEncoder) does: the speakers of
|
||||
/// the caller's channels, mapped onto the codec's layout), and for ALAC `bit_depth` and
|
||||
/// `dither`; `format`, `bwf` and `force_rf64` are for files and ignored.
|
||||
///
|
||||
/// Opus takes 48 kHz mono or stereo at a constant bit rate (64 kbit/s per channel when none
|
||||
/// is asked for); the others take what their [`EncodeFormat`] lists. A codec this crate has
|
||||
/// no encoder for, and one whose feature is not built, are [`AudioError::Unsupported`]. A
|
||||
/// rate, channel count, layout or rate control the codec cannot take is refused with the error
|
||||
/// [`EncodeOptions::check`] gives for the format (`Unsupported` for a layout or rate control).
|
||||
pub fn new(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result<PacketEncoder> {
|
||||
let Some(feature) = feature(codec) else {
|
||||
return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name())));
|
||||
};
|
||||
let built = [
|
||||
(CodecId::Aac, cfg!(feature = "aac-encode")),
|
||||
(CodecId::Alac, cfg!(feature = "alac-encode")),
|
||||
(CodecId::Mp3, cfg!(feature = "mp3-encode")),
|
||||
(CodecId::Ac3, cfg!(feature = "ac3-encode")),
|
||||
(CodecId::Eac3, cfg!(feature = "eac3-encode")),
|
||||
(CodecId::Opus, cfg!(feature = "opus-encode")),
|
||||
];
|
||||
if !built.contains(&(codec, true)) {
|
||||
return Err(AudioError::Unsupported(format!("encoding {} needs the `{feature}` feature", codec.name())));
|
||||
}
|
||||
let n = usize::from(channels);
|
||||
// As the file writers word it.
|
||||
if channels == 0 {
|
||||
return Err(AudioError::Encode("buffer has no channels".into()));
|
||||
}
|
||||
if sample_rate == 0 {
|
||||
return Err(AudioError::Encode("sample rate is 0".into()));
|
||||
}
|
||||
if let Some(layout) = &opts.layout
|
||||
&& layout.channels() != channels
|
||||
{
|
||||
return Err(AudioError::Encode(format!("a {}-channel layout for {channels} channels", layout.channels())));
|
||||
}
|
||||
let given = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels));
|
||||
let (inner, map, layout, bitrate, bit_depth) = match codec {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
CodecId::Aac => {
|
||||
let (map, layout) = fixed_map(EncodeFormat::Aac.layout_masks(channels), "AAC", aac_order(n), &given)?;
|
||||
let mode = aac_mode(opts.rate_control, sample_rate, n);
|
||||
let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, n, 0) };
|
||||
let bitrate = match mode {
|
||||
crate::aac::BitrateMode::Cbr(bps) => Some(bps),
|
||||
crate::aac::BitrateMode::Vbr(_) => None,
|
||||
};
|
||||
(Inner::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, layout, bitrate, None)
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
CodecId::Alac => {
|
||||
let count = u8::try_from(channels).unwrap_or(u8::MAX);
|
||||
let (map, layout) = fixed_map(EncodeFormat::Alac.layout_masks(channels), "ALAC", crate::alac::alac_order(count), &given)?;
|
||||
let bits = match opts.bit_depth {
|
||||
crate::BitDepth::Int16 => 16,
|
||||
crate::BitDepth::Int24 => 24,
|
||||
crate::BitDepth::Int32 => 32,
|
||||
crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())),
|
||||
};
|
||||
let config = crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32);
|
||||
let enc = crate::alac::Encoder::new(config)?;
|
||||
let quantizers = crate::write::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, n);
|
||||
(Inner::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); n] }, map, layout, None, Some(bits))
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
CodecId::Mp3 => {
|
||||
let (map, layout) = fixed_map(EncodeFormat::Mp3.layout_masks(channels), "MP3", None, &given)?;
|
||||
let want = constant_bps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * u32::from(channels) * 1000)? / 1000;
|
||||
// A sample rate MP3 has not is the encoder's to refuse.
|
||||
let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want);
|
||||
let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, n, kbps))?;
|
||||
(Inner::Mp3 { enc: Box::new(enc), bytes: Vec::new() }, map, layout, Some(kbps.saturating_mul(1000)), None)
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
CodecId::Ac3 | CodecId::Eac3 => {
|
||||
let which = if codec == CodecId::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 };
|
||||
let (config, map) = ac3_config(which, sample_rate, &given, opts.rate_control)?;
|
||||
let enc = crate::ac3::encoder::Encoder::new(config)?;
|
||||
let layout = enc.channel_layout();
|
||||
let bitrate = Some(config.bitrate_kbps.saturating_mul(1000));
|
||||
(Inner::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); n] }, map, layout, bitrate, None)
|
||||
}
|
||||
#[cfg(feature = "opus-encode")]
|
||||
CodecId::Opus => {
|
||||
let masks = n.checked_sub(1).and_then(|i| OPUS_LAYOUT_MASKS.get(i)).copied().unwrap_or_default();
|
||||
let (map, layout) = fixed_map(masks, "Opus", None, &given)?;
|
||||
if sample_rate != 48_000 {
|
||||
return Err(AudioError::Unsupported(format!("Opus is encoded at 48000 Hz, not {sample_rate} Hz")));
|
||||
}
|
||||
let bps = constant_bps("Opus", opts.rate_control, OPUS_DEFAULT_BPS_PER_CHANNEL * u32::from(channels))?;
|
||||
let enc = crate::opus::encoder::Encoder::new(channels as u8, bps)?;
|
||||
let bitrate = Some(enc.bitrate());
|
||||
(Inner::Opus { enc: Box::new(enc), pending: Vec::new(), coded: 0 }, map, layout, bitrate, None)
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))),
|
||||
};
|
||||
Ok(PacketEncoder { codec, inner, sample_rate, layout, map, bitrate, bit_depth, pts: 0, frames: 0, finished: false, failed: false })
|
||||
}
|
||||
|
||||
/// The codec of the packets.
|
||||
pub fn codec(&self) -> CodecId {
|
||||
self.codec
|
||||
}
|
||||
|
||||
/// The sample rate of the audio and of the packets' timing.
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
/// The number of channels.
|
||||
pub fn channels(&self) -> u16 {
|
||||
self.layout.channels()
|
||||
}
|
||||
|
||||
/// The speakers of the channels encoded, in WAV order: the codec's layout for the channel
|
||||
/// count (for AC-3 and E-AC-3, the coding mode's), which is what a decoder reports. Where the
|
||||
/// codec has one surround pair, it is the codec's (AAC's 5.1 has side surrounds, ALAC's back
|
||||
/// ones), whichever pair the caller's layout named.
|
||||
pub fn layout(&self) -> ChannelLayout {
|
||||
self.layout
|
||||
}
|
||||
|
||||
/// The constant bit rate in bits per second for all channels together, as
|
||||
/// [`RateControl::Bitrate`] describes the rate the stream settles on; `None` for ALAC and
|
||||
/// for AAC at a constant quality.
|
||||
pub fn bitrate(&self) -> Option<u32> {
|
||||
self.bitrate
|
||||
}
|
||||
|
||||
/// The bits per sample of a lossless codec (ALAC), `None` for the lossy ones.
|
||||
pub fn bit_depth(&self) -> Option<u8> {
|
||||
self.bit_depth
|
||||
}
|
||||
|
||||
/// The codec configuration a container stores: AAC's `AudioSpecificConfig` (MP4 `esds`
|
||||
/// decoder-specific info, Matroska CodecPrivate), ALAC's configuration as MP4's `alac` box
|
||||
/// and Matroska's CodecPrivate hold it, Opus's `OpusHead`; empty for MP3, AC-3 and E-AC-3.
|
||||
/// ALAC's records the largest packet and the average bit rate so far, so read it after
|
||||
/// [`finish`](Self::finish).
|
||||
pub fn extradata(&self) -> Vec<u8> {
|
||||
match &self.inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Inner::Aac(enc) => enc.audio_specific_config(),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Inner::Alac { enc, .. } => enc.cookie(),
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Inner::Opus { enc, .. } => enc.opus_head(),
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The codec, sample rate, channels and [`extradata`](Self::extradata): the description
|
||||
/// [`TrackDecoder::new`](crate::TrackDecoder::new) takes, and what a muxer's track needs.
|
||||
pub fn codec_params(&self) -> CodecParams {
|
||||
CodecParams::new(self.codec).with_sample_rate(self.sample_rate).with_channels(self.channels()).with_extradata(self.extradata())
|
||||
}
|
||||
|
||||
/// Decoded samples before the first input frame: the encoder's delay, which a container
|
||||
/// skips (an MP4 edit list's media time, Matroska's CodecDelay, Opus's pre-skip, which
|
||||
/// `OpusHead` already holds). 0 for ALAC.
|
||||
///
|
||||
/// This is the codec's delay and does not depend on the input. An encoder that is given no
|
||||
/// input returns no packets, and this still reports the delay.
|
||||
pub fn priming(&self) -> u32 {
|
||||
match &self.inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Inner::Aac(enc) => enc.priming_samples(),
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Inner::Mp3 { enc, .. } => enc.delay(),
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Inner::Ac3 { enc, .. } => enc.priming_samples(),
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Inner::Opus { enc, .. } => u32::from(enc.pre_skip()),
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Frames of input taken so far.
|
||||
pub fn frames(&self) -> u64 {
|
||||
self.frames
|
||||
}
|
||||
|
||||
/// Decoded samples after the last input frame, which a container trims (the end of an MP4
|
||||
/// edit, Matroska's DiscardPadding): the packets' durations add up to
|
||||
/// [`priming`](Self::priming) + [`frames`](Self::frames) + this. Complete after
|
||||
/// [`finish`](Self::finish).
|
||||
///
|
||||
/// The sum holds once there is input. With none, [`finish`](Self::finish) returns no packets,
|
||||
/// so the durations add up to 0 and this is 0, while `priming` is still the codec's delay: a
|
||||
/// muxer writes an empty track and has no priming to skip.
|
||||
pub fn padding(&self) -> u64 {
|
||||
self.pts.saturating_sub(u64::from(self.priming()).saturating_add(self.frames))
|
||||
}
|
||||
|
||||
/// Encodes the first `frames` frames of `block`, one slice per channel in WAV order
|
||||
/// (`&[Vec<f32>]`, `&[&[f32]]`, …), and returns the packets completed. Samples are full scale
|
||||
/// at ±1; NaN is taken as 0, and what a codec cannot carry above full scale is clipped.
|
||||
///
|
||||
/// Internal codec calls process at most 4096 frames at a time, but this method collects their
|
||||
/// packets in one returned vector whose memory use grows with `frames`. For streaming with
|
||||
/// bounded memory, pass bounded input blocks and consume each returned batch before encoding
|
||||
/// the next block, as [`FileEncoder`](crate::FileEncoder) does for coded formats.
|
||||
///
|
||||
/// `block` must have one slice per channel, each at least `frames` long; otherwise nothing is
|
||||
/// encoded and the error is [`AudioError::Encode`]. A call after [`finish`](Self::finish) is
|
||||
/// an error too. When encoding itself fails, the packets of the block are lost, and every
|
||||
/// later call fails rather than return a stream with a gap.
|
||||
pub fn encode<C: AsRef<[f32]>>(&mut self, block: &[C], frames: usize) -> Result<Vec<EncodedPacket>> {
|
||||
self.usable()?;
|
||||
let channels = usize::from(self.channels());
|
||||
if block.len() != channels {
|
||||
return Err(AudioError::Encode(format!("a block of {} channels for a {channels}-channel stream", block.len())));
|
||||
}
|
||||
if let Some(short) = block.iter().map(|c| c.as_ref().len()).filter(|&n| n < frames).min() {
|
||||
return Err(AudioError::Encode(format!("{frames} frames asked for, but a channel holds {short}")));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for at in (0..frames).step_by(CHUNK) {
|
||||
let end = frames.min(at + CHUNK);
|
||||
let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect();
|
||||
if let Err(e) = self.push(&planes, &mut out) {
|
||||
self.failed = true;
|
||||
return Err(e);
|
||||
}
|
||||
self.frames = self.frames.saturating_add((end - at) as u64);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Encodes what the encoder still holds, padded with silence to whole packets and as far as
|
||||
/// a decoder needs to return every input frame after the priming, and returns the last
|
||||
/// packets. Later calls of [`encode`](Self::encode) and `finish` are errors; the description
|
||||
/// ([`extradata`](Self::extradata), [`padding`](Self::padding)) stays readable.
|
||||
pub fn finish(&mut self) -> Result<Vec<EncodedPacket>> {
|
||||
self.usable()?;
|
||||
self.finished = true;
|
||||
let mut out = Vec::new();
|
||||
let done = self.drain(&mut out);
|
||||
if done.is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
done.map(|()| out)
|
||||
}
|
||||
|
||||
fn usable(&self) -> Result<()> {
|
||||
if self.failed {
|
||||
Err(AudioError::Encode("the packet encoder already failed; its stream is incomplete".into()))
|
||||
} else if self.finished {
|
||||
Err(AudioError::Encode("the packet encoder is finished".into()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a packet of `duration` decoded samples at the current position.
|
||||
fn emit(pts: &mut u64, out: &mut Vec<EncodedPacket>, data: Vec<u8>, duration: u32) {
|
||||
out.push(EncodedPacket { data, pts: *pts, duration });
|
||||
*pts = pts.saturating_add(u64::from(duration));
|
||||
}
|
||||
|
||||
/// Encodes `planes` (one slice per codec channel, equally long, at most [`CHUNK`] frames)
|
||||
/// and appends the packets completed.
|
||||
fn push(&mut self, planes: &[&[f32]], out: &mut Vec<EncodedPacket>) -> Result<()> {
|
||||
let pts = &mut self.pts;
|
||||
match &mut self.inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Inner::Aac(enc) => {
|
||||
for data in enc.encode(planes) {
|
||||
Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Inner::Alac { enc, quantizers, pending } => {
|
||||
let frames = planes.first().map_or(0, |p| p.len());
|
||||
let mut at = 0;
|
||||
while at < frames {
|
||||
let filled = pending.first().map_or(0, Vec::len);
|
||||
let end = frames.min(at + CHUNK.saturating_sub(filled).max(1));
|
||||
for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) {
|
||||
dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s)));
|
||||
}
|
||||
at = end;
|
||||
if pending.first().is_some_and(|p| p.len() >= CHUNK) {
|
||||
alac_packet(enc, pending, pts, out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Inner::Mp3 { enc, bytes } => {
|
||||
bytes.extend(enc.encode(planes));
|
||||
mp3_frames(enc, bytes, pts, out)?;
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Inner::Ac3 { enc, planes: clean } => {
|
||||
for (dst, src) in clean.iter_mut().zip(planes) {
|
||||
dst.clear();
|
||||
dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }));
|
||||
}
|
||||
let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect();
|
||||
for p in enc.push(&refs)? {
|
||||
Self::emit(pts, out, p.data, p.samples);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Inner::Opus { enc, pending, coded } => {
|
||||
let frames = planes.first().map_or(0, |p| p.len());
|
||||
for i in 0..frames {
|
||||
pending.extend(planes.iter().map(|p| p.get(i).copied().map_or(0.0, |s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })));
|
||||
if pending.len() == crate::opus::encoder::Encoder::FRAME_SIZE * planes.len() {
|
||||
opus_packet(enc, pending, coded, pts, out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes what the codec still holds and appends the last packets.
|
||||
fn drain(&mut self, out: &mut Vec<EncodedPacket>) -> Result<()> {
|
||||
let pts = &mut self.pts;
|
||||
match &mut self.inner {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Inner::Aac(enc) => {
|
||||
for data in enc.flush() {
|
||||
Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Inner::Alac { enc, pending, .. } => {
|
||||
if pending.first().is_some_and(|p| !p.is_empty()) {
|
||||
alac_packet(enc, pending, pts, out)?;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Inner::Mp3 { enc, bytes } => {
|
||||
bytes.extend(enc.flush());
|
||||
mp3_frames(enc, bytes, pts, out)?;
|
||||
if !bytes.is_empty() {
|
||||
return Err(AudioError::Encode(format!("the MP3 encoder ended with {} bytes that are not a whole frame", bytes.len())));
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Inner::Ac3 { enc, .. } => {
|
||||
for p in enc.finish()?.packets {
|
||||
Self::emit(pts, out, p.data, p.samples);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "opus-encode")]
|
||||
Inner::Opus { enc, pending, coded } => {
|
||||
// Every input frame decodes after the pre-skip: as many packets as that takes.
|
||||
let size = crate::opus::encoder::Encoder::FRAME_SIZE as u64;
|
||||
let needed = if self.frames == 0 { 0 } else { (self.frames + u64::from(enc.pre_skip())).div_ceil(size) * size };
|
||||
let width = usize::from(enc.channels());
|
||||
while *coded < needed {
|
||||
pending.resize(crate::opus::encoder::Encoder::FRAME_SIZE * width, 0.0);
|
||||
opus_packet(enc, pending, coded, pts, out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes the pending samples as one ALAC packet and empties them.
|
||||
#[cfg(feature = "alac-encode")]
|
||||
fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec<i32>], pts: &mut u64, out: &mut Vec<EncodedPacket>) -> Result<()> {
|
||||
let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect();
|
||||
let frames = refs.first().map_or(0, |p| p.len()) as u32;
|
||||
let data = enc.encode(&refs)?;
|
||||
pending.iter_mut().for_each(Vec::clear);
|
||||
PacketEncoder::emit(pts, out, data, frames);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes one full frame of pending interleaved samples as an Opus packet and empties them.
|
||||
#[cfg(feature = "opus-encode")]
|
||||
fn opus_packet(
|
||||
enc: &mut crate::opus::encoder::Encoder,
|
||||
pending: &mut Vec<f32>,
|
||||
coded: &mut u64,
|
||||
pts: &mut u64,
|
||||
out: &mut Vec<EncodedPacket>,
|
||||
) -> Result<()> {
|
||||
let data = enc.encode_float(pending)?;
|
||||
pending.clear();
|
||||
let size = crate::opus::encoder::Encoder::FRAME_SIZE as u32;
|
||||
*coded += u64::from(size);
|
||||
PacketEncoder::emit(pts, out, data, size);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Splits the whole MP3 frames off the front of `bytes`. The encoder writes constant-rate frames
|
||||
/// back to back, so each one's length follows from its header's padding bit.
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
fn mp3_frames(enc: &crate::mp3::Encoder, bytes: &mut Vec<u8>, pts: &mut u64, out: &mut Vec<EncodedPacket>) -> Result<()> {
|
||||
let samples = enc.frame_samples();
|
||||
let config = enc.config();
|
||||
// Bytes per frame: samples / 8 × bit rate / sample rate, plus the padding slot.
|
||||
let base = (samples as u64 / 8 * u64::from(config.bitrate_kbps) * 1000 / u64::from(config.sample_rate.max(1))) as usize;
|
||||
let mut at = 0;
|
||||
while let Some(header) = bytes.get(at..at + 4) {
|
||||
if header[0] != 0xFF || header[1] & 0xE0 != 0xE0 {
|
||||
return Err(AudioError::Encode("the MP3 encoder returned bytes that are not a frame".into()));
|
||||
}
|
||||
let len = base + usize::from((header[2] >> 1) & 1);
|
||||
let Some(frame) = bytes.get(at..at + len).filter(|_| len > 4) else { break };
|
||||
PacketEncoder::emit(pts, out, frame.to_vec(), samples as u32);
|
||||
at += len;
|
||||
}
|
||||
bytes.drain(..at);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
|
||||
use crate::Speaker;
|
||||
use crate::{CodecId, Speaker};
|
||||
|
||||
fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option<Vec<usize>> {
|
||||
channel_map(mask, order, &ChannelLayout::from_mask(layout))
|
||||
@@ -165,3 +165,25 @@ fn the_listed_sample_rates_are_the_encoders() {
|
||||
assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES));
|
||||
assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES));
|
||||
}
|
||||
|
||||
/// A codec whose feature is not built is refused, as `EncodeOptions::check` refuses its format.
|
||||
#[test]
|
||||
fn unbuilt_codecs_are_unsupported() {
|
||||
let built = [
|
||||
(CodecId::Aac, cfg!(feature = "aac-encode")),
|
||||
(CodecId::Alac, cfg!(feature = "alac-encode")),
|
||||
(CodecId::Mp3, cfg!(feature = "mp3-encode")),
|
||||
(CodecId::Ac3, cfg!(feature = "ac3-encode")),
|
||||
(CodecId::Eac3, cfg!(feature = "eac3-encode")),
|
||||
(CodecId::Opus, cfg!(feature = "opus-encode")),
|
||||
];
|
||||
let opts = EncodeOptions::default().with_bit_depth(crate::BitDepth::Int16);
|
||||
for (codec, built) in built {
|
||||
let made = PacketEncoder::new(codec, &opts, 48_000, 2);
|
||||
if built {
|
||||
assert!(made.is_ok(), "{codec:?}: {made:?}");
|
||||
} else {
|
||||
assert!(matches!(&made, Err(AudioError::Unsupported(m)) if m.contains("feature")), "{codec:?}: {made:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! SMPTE ST 302M: AES3 audio carried in MPEG-2 transport stream packets (feature `s302m`): a
|
||||
//! packet decoder ([`decode`]) and encoder ([`Encoder`]) for the payload of one PES packet.
|
||||
//!
|
||||
//! A packet is a 4-byte header and the audio. The header is the size in bytes of the audio (16 bits,
|
||||
//! big-endian), then 16 bits: the channel count code (2 bits; 0 to 3 for 2, 4, 6 or 8 channels), the
|
||||
//! identification of the first channel (8 bits), the sample size code (2 bits; 0, 1 and 2 for 16, 20
|
||||
//! and 24 bits) and 4 alignment bits. The audio is, for every frame, one 40-, 48- or 56-bit group
|
||||
//! per channel pair, the pairs in order: each pair is two AES3 subframes, the left channel then the
|
||||
//! right one, each of the sample (least significant bit first) and four flag bits (V, U, C and a
|
||||
//! frame-start flag set on the left subframe of each channel pair in the first frame of every block of 192 frames). The
|
||||
//! bits go out in transmission order, so a byte holds them most significant bit first.
|
||||
//!
|
||||
//! Samples are signed `i32` in the stream's own range (16, 20 or 24 bits, not scaled). The
|
||||
//! decoder reads the flags and ignores them; the encoder writes the validity, user and channel
|
||||
//! status bits as zero and sets the frame-start flag.
|
||||
//!
|
||||
//! Written from the standard's description of the packet and the AES3 subframe. ffmpeg is only run
|
||||
//! as a black-box oracle in the tests.
|
||||
|
||||
/// The most audio bytes one packet can hold (the size field is 16 bits).
|
||||
pub const MAX_AUDIO_BYTES: usize = 0xFFFF;
|
||||
|
||||
/// What went wrong decoding or encoding.
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The packet is damaged, truncated, or uses a reserved code.
|
||||
#[error("malformed SMPTE 302M packet: {0}")]
|
||||
Malformed(&'static str),
|
||||
/// The settings or samples given to the encoder cannot be written.
|
||||
#[error("SMPTE 302M cannot encode: {0}")]
|
||||
InvalidInput(&'static str),
|
||||
}
|
||||
|
||||
/// `Result` of this module.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// The header of a packet.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
/// 2, 4, 6 or 8.
|
||||
pub channels: usize,
|
||||
/// The identification of the first channel (as the stream gives it).
|
||||
pub channel_id: u8,
|
||||
/// 16, 20 or 24.
|
||||
pub bits: u32,
|
||||
/// The alignment bits as written.
|
||||
pub alignment: u8,
|
||||
/// Bytes of audio after the header.
|
||||
pub audio_bytes: usize,
|
||||
}
|
||||
|
||||
impl Header {
|
||||
/// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow.
|
||||
pub fn frame_bytes(&self) -> usize {
|
||||
let pair_bytes = match self.bits {
|
||||
16 => 5,
|
||||
20 => 6,
|
||||
24 => 7,
|
||||
_ => return 0,
|
||||
};
|
||||
(self.channels / 2).checked_mul(pair_bytes).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the 4-byte header at the start of `packet`.
|
||||
pub fn parse_header(packet: &[u8]) -> Result<Header> {
|
||||
let [a, b, c, d, ..] = *packet else { return Err(Error::Malformed("shorter than the header")) };
|
||||
let size = usize::from(u16::from_be_bytes([a, b]));
|
||||
let word = u16::from_be_bytes([c, d]);
|
||||
let channels = 2 * (usize::from(word >> 14) + 1);
|
||||
let bits = match (word >> 4) & 3 {
|
||||
0 => 16,
|
||||
1 => 20,
|
||||
2 => 24,
|
||||
_ => return Err(Error::Malformed("reserved sample size code")),
|
||||
};
|
||||
Ok(Header { channels, channel_id: ((word >> 6) & 0xFF) as u8, bits, alignment: (word & 0xF) as u8, audio_bytes: size })
|
||||
}
|
||||
|
||||
/// One decoded packet.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Decoded {
|
||||
/// The packet header.
|
||||
pub header: Header,
|
||||
/// Interleaved samples, `header.channels` per frame.
|
||||
pub samples: Vec<i32>,
|
||||
}
|
||||
|
||||
/// Bit `i` of a byte string in transmission order (the first bit sent is the least significant bit of the sample, held in the most significant bit of the byte).
|
||||
fn bit(bytes: &[u8], i: usize) -> u32 {
|
||||
bytes.get(i / 8).map_or(0, |b| u32::from((b >> (7 - i % 8)) & 1))
|
||||
}
|
||||
|
||||
/// Decode the payload of one PES packet.
|
||||
pub fn decode(packet: &[u8]) -> Result<Decoded> {
|
||||
let header = parse_header(packet)?;
|
||||
let audio = packet.get(4..).unwrap_or(&[]);
|
||||
if audio.len() < header.audio_bytes {
|
||||
return Err(Error::Malformed("the audio is shorter than the header says"));
|
||||
}
|
||||
let audio = audio.get(..header.audio_bytes).unwrap_or(&[]);
|
||||
let frame_bytes = header.frame_bytes();
|
||||
if frame_bytes == 0 || audio.len() % frame_bytes != 0 {
|
||||
return Err(Error::Malformed("the audio is not a whole number of frames"));
|
||||
}
|
||||
let n = header.bits as usize;
|
||||
let mut samples = Vec::with_capacity(audio.len() / (n + 4) * 8 / 2);
|
||||
for frame in audio.chunks_exact(frame_bytes) {
|
||||
for pos in (0..header.channels).map(|c| c * (n + 4)) {
|
||||
let mut v = 0u32;
|
||||
for k in 0..n {
|
||||
v |= bit(frame, pos + k) << k;
|
||||
}
|
||||
// sign-extend the n-bit sample
|
||||
let shift = 32 - n as u32;
|
||||
samples.push(((v << shift) as i32) >> shift);
|
||||
}
|
||||
}
|
||||
Ok(Decoded { header, samples })
|
||||
}
|
||||
|
||||
/// A packet encoder. It counts frames so that the frame-start flag falls on the first frame of
|
||||
/// every block of 192.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Encoder {
|
||||
channels: usize,
|
||||
bits: u32,
|
||||
channel_id: u8,
|
||||
frames: u64,
|
||||
}
|
||||
|
||||
impl Encoder {
|
||||
/// An encoder for `channels` (2, 4, 6 or 8) channels of `bits` (16, 20 or 24) bits.
|
||||
pub fn new(channels: usize, bits: u32) -> Result<Encoder> {
|
||||
if !matches!(channels, 2 | 4 | 6 | 8) {
|
||||
return Err(Error::InvalidInput("SMPTE 302M carries 2, 4, 6 or 8 channels"));
|
||||
}
|
||||
if !matches!(bits, 16 | 20 | 24) {
|
||||
return Err(Error::InvalidInput("SMPTE 302M samples have 16, 20 or 24 bits"));
|
||||
}
|
||||
Ok(Encoder { channels, bits, channel_id: 0, frames: 0 })
|
||||
}
|
||||
|
||||
/// Set the identification of the first channel written in the header (0 by default).
|
||||
pub fn channel_id(mut self, id: u8) -> Encoder {
|
||||
self.channel_id = id;
|
||||
self
|
||||
}
|
||||
|
||||
/// The most frames one packet can hold.
|
||||
pub fn max_frames(&self) -> usize {
|
||||
MAX_AUDIO_BYTES / (self.channels / 2 * ((self.bits as usize + 4) * 2 / 8))
|
||||
}
|
||||
|
||||
/// Encode interleaved samples (a whole number of frames, at most [`Encoder::max_frames`], each
|
||||
/// within the sample size) as one packet payload.
|
||||
pub fn encode(&mut self, samples: &[i32]) -> Result<Vec<u8>> {
|
||||
if samples.is_empty() || !samples.len().is_multiple_of(self.channels) {
|
||||
return Err(Error::InvalidInput("the samples are not a whole number of frames"));
|
||||
}
|
||||
let frames = samples.len() / self.channels;
|
||||
if frames > self.max_frames() {
|
||||
return Err(Error::InvalidInput("too many frames for one packet"));
|
||||
}
|
||||
let n = self.bits as usize;
|
||||
let limit = 1i64 << (n - 1);
|
||||
if samples.iter().any(|&s| i64::from(s) < -limit || i64::from(s) >= limit) {
|
||||
return Err(Error::InvalidInput("a sample is outside the sample size"));
|
||||
}
|
||||
let frame_bytes = self.channels / 2 * ((n + 4) * 2 / 8);
|
||||
let audio_bytes = frames * frame_bytes;
|
||||
let code = match self.bits {
|
||||
16 => 0u16,
|
||||
20 => 1,
|
||||
_ => 2,
|
||||
};
|
||||
let word = (((self.channels / 2 - 1) as u16) << 14) | (u16::from(self.channel_id) << 6) | (code << 4);
|
||||
let mut out = Vec::with_capacity(4 + audio_bytes);
|
||||
out.extend((audio_bytes as u16).to_be_bytes());
|
||||
out.extend(word.to_be_bytes());
|
||||
out.resize(4 + audio_bytes, 0);
|
||||
for (f, frame) in samples.chunks_exact(self.channels).enumerate() {
|
||||
let start = (self.frames + f as u64).is_multiple_of(192);
|
||||
let base = 4 + f * frame_bytes;
|
||||
for (c, &s) in frame.iter().enumerate() {
|
||||
let pos = c * (n + 4);
|
||||
let v = (s as u32) & ((1u32 << n) - 1);
|
||||
for k in 0..n {
|
||||
set_bit(&mut out, base, pos + k, (v >> k) & 1);
|
||||
}
|
||||
// flags V, U, C, then the frame-start flag on the left subframe of each pair
|
||||
if c % 2 == 0 && start {
|
||||
set_bit(&mut out, base, pos + n + 3, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.frames += frames as u64;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn set_bit(out: &mut [u8], base: usize, i: usize, v: u32) {
|
||||
if v != 0
|
||||
&& let Some(b) = out.get_mut(base + i / 8)
|
||||
{
|
||||
*b |= 0x80 >> (i % 8);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_packet() {
|
||||
// stereo 16-bit, one frame: L = 0x1234, R = 0xFEFF, the first frame of a block
|
||||
let packet = [0x00, 0x05, 0x00, 0x00, 0x2c, 0x48, 0x1f, 0xf7, 0xf0];
|
||||
let d = decode(&packet).unwrap();
|
||||
assert_eq!(d.samples, vec![0x1234, -257]);
|
||||
assert_eq!((d.header.channels, d.header.bits), (2, 16));
|
||||
let mut e = Encoder::new(2, 16).unwrap();
|
||||
assert_eq!(e.encode(&[0x1234, -257]).unwrap(), packet);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_and_packets_are_checked() {
|
||||
assert!(Encoder::new(1, 16).is_err());
|
||||
assert!(Encoder::new(2, 18).is_err());
|
||||
let mut e = Encoder::new(2, 16).unwrap();
|
||||
assert!(e.encode(&[]).is_err());
|
||||
assert!(e.encode(&[1]).is_err());
|
||||
assert!(e.encode(&[40_000, 0]).is_err());
|
||||
assert!(decode(&[0, 1]).is_err());
|
||||
assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err());
|
||||
assert!(decode(&[0, 5, 0, 0, 0, 0]).is_err());
|
||||
assert!(decode(&[0, 4, 0, 0, 0, 0, 0, 0]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_frame_bytes_overflow_does_not_panic() {
|
||||
let h = Header { channels: usize::MAX, channel_id: 0, bits: 24, alignment: 0, audio_bytes: 0 };
|
||||
assert_eq!(h.frame_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_frame_bytes_rejects_unsupported_depth() {
|
||||
let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 };
|
||||
assert_eq!(h_max.frame_bytes(), 0);
|
||||
|
||||
let h_unsupported = Header { channels: 2, channel_id: 0, bits: 18, alignment: 0, audio_bytes: 0 };
|
||||
assert_eq!(h_unsupported.frame_bytes(), 0);
|
||||
|
||||
let h_zero = Header { channels: 2, channel_id: 0, bits: 0, alignment: 0, audio_bytes: 0 };
|
||||
assert_eq!(h_zero.frame_bytes(), 0);
|
||||
}
|
||||
}
|
||||
+60
-351
@@ -1,7 +1,7 @@
|
||||
//! The coded formats of [`FileEncoder`](crate::FileEncoder): AAC-LC and ALAC in M4A (through
|
||||
//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] maps the caller's
|
||||
//! WAV-order channels onto the encoder's order, drives the packet encoder, and for M4A records the
|
||||
//! encoder's priming and the exact length in the edit list.
|
||||
//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] drives a
|
||||
//! [`PacketEncoder`], which maps the caller's WAV-order channels onto the codec's order, and for
|
||||
//! M4A records the encoder's priming and the exact length in the edit list.
|
||||
|
||||
// Each codec is its own feature, and so are the two sinks: with only some of them built, the
|
||||
// other halves of the shared code are unused.
|
||||
@@ -11,271 +11,10 @@
|
||||
)]
|
||||
|
||||
use super::failed_write_error;
|
||||
use super::pcm::validate_layout;
|
||||
use crate::layout::channel_map;
|
||||
use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, RateControl, Result};
|
||||
use crate::packet::{EncodedPacket, PacketEncoder};
|
||||
use crate::{AudioBuffer, AudioError, CodecId, EncodeFormat, EncodeOptions, Result};
|
||||
use std::io::{Cursor, Seek, Write};
|
||||
|
||||
/// Frames handed to the encoder at a time, so its buffers and the packets waiting to be written
|
||||
/// stay small however long a block is. Also the frames of an ALAC packet.
|
||||
const CHUNK: usize = 4096;
|
||||
|
||||
/// Bits per second per channel when no rate is asked for: AAC.
|
||||
const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000;
|
||||
/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per
|
||||
/// full-bandwidth channel).
|
||||
const DEFAULT_KBPS_PER_CHANNEL: u32 = 96;
|
||||
|
||||
/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`.
|
||||
fn labels(mask: u32) -> String {
|
||||
ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// [`channel_map`] for a format with one layout per channel count ([`EncodeFormat::layout_masks`]),
|
||||
/// or why the audio does not fit.
|
||||
fn fixed_map(format: EncodeFormat, name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<Vec<usize>> {
|
||||
let Some(&mask) = format.layout_masks(layout.channels()).first() else {
|
||||
return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels())));
|
||||
};
|
||||
channel_map(mask, order, layout).ok_or_else(|| {
|
||||
AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout)))
|
||||
})
|
||||
}
|
||||
|
||||
/// The speakers of the caller's layout, for an error message.
|
||||
fn given(layout: &ChannelLayout) -> String {
|
||||
layout.mask().map_or_else(|| "without speaker assignment".into(), labels)
|
||||
}
|
||||
|
||||
/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for 8 channels
|
||||
/// configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc.
|
||||
#[cfg(feature = "aac-encode")]
|
||||
fn aac_order(channels: usize) -> Option<&'static [usize]> {
|
||||
if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) }
|
||||
}
|
||||
|
||||
/// The lowest AAC bit rate the writer uses, per channel: 6 kbit/s, and a quarter of the sample
|
||||
/// rate (256 bits a frame). The encoder accepts less, and from about half of this down codes
|
||||
/// silence; a file of silence is no answer to a low bit rate (or to kbit/s given as bit/s).
|
||||
#[cfg(feature = "aac-encode")]
|
||||
fn aac_floor_per_channel(sample_rate: u32) -> u32 {
|
||||
(sample_rate / 4).max(6000)
|
||||
}
|
||||
|
||||
/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a
|
||||
/// quality of 0–1 spans the encoder's VBR range.
|
||||
#[cfg(feature = "aac-encode")]
|
||||
fn aac_mode(rate: Option<RateControl>, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode {
|
||||
use crate::aac::BitrateMode;
|
||||
let (lo, hi) = crate::aac::cbr_range(sample_rate, channels);
|
||||
let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo));
|
||||
// An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone.
|
||||
let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps };
|
||||
match rate {
|
||||
None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))),
|
||||
Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)),
|
||||
// NaN stays NaN, which the encoder refuses.
|
||||
Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit rate in kbit/s for a codec with constant bit rates only.
|
||||
fn constant_kbps(name: &str, rate: Option<RateControl>, default: u32) -> Result<u32> {
|
||||
match rate {
|
||||
None => Ok(default),
|
||||
Some(RateControl::Bitrate(bps)) => Ok(bps / 1000),
|
||||
Some(RateControl::Quality(_)) => {
|
||||
Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding
|
||||
/// mode whose speakers the layout names, at the nearest bit rate the stream can carry.
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
fn ac3_config(
|
||||
codec: crate::ac3::encoder::Codec,
|
||||
sample_rate: u32,
|
||||
layout: &ChannelLayout,
|
||||
rate: Option<RateControl>,
|
||||
) -> Result<(crate::ac3::encoder::Config, Vec<usize>)> {
|
||||
use crate::ac3::encoder::{Codec, CodingMode, Config};
|
||||
use CodingMode::*;
|
||||
let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" };
|
||||
let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71];
|
||||
let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| {
|
||||
// 7.1 is an E-AC-3 programme with an LFE; the encoder has no other.
|
||||
if mode == Surround71 && (codec != Codec::Eac3 || !lfe) {
|
||||
return None;
|
||||
}
|
||||
let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe };
|
||||
let map = channel_map(config.channel_layout().mask()?, None, layout)?;
|
||||
Some((config, map))
|
||||
});
|
||||
let Some((mut config, map)) = found else {
|
||||
return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout))));
|
||||
};
|
||||
let full = config.mode.channels() as u32;
|
||||
let want = constant_kbps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full)?;
|
||||
// What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of
|
||||
// the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold.
|
||||
let least = if config.mode == Surround71 { 384 } else { 32 * full };
|
||||
config.bitrate_kbps = match codec {
|
||||
Codec::Ac3 => {
|
||||
let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least);
|
||||
crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor)
|
||||
}
|
||||
Codec::Eac3 => {
|
||||
let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 };
|
||||
want.clamp(least, most.max(least))
|
||||
}
|
||||
};
|
||||
Ok((config, map))
|
||||
}
|
||||
|
||||
/// One encoded packet and the frames it decodes to.
|
||||
struct Packet {
|
||||
data: Vec<u8>,
|
||||
frames: u32,
|
||||
}
|
||||
|
||||
/// A packet encoder of any of the codecs, taking planar `f32` in its own channel order.
|
||||
enum Codec {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Aac(Box<crate::aac::Encoder>),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Alac {
|
||||
enc: Box<crate::alac::Encoder>,
|
||||
quantizers: Vec<super::pcm::Quantizer>,
|
||||
/// Quantized samples of the packet being filled, per channel.
|
||||
pending: Vec<Vec<i32>>,
|
||||
},
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Mp3(Box<crate::mp3::Encoder>),
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Ac3 {
|
||||
enc: Box<crate::ac3::encoder::Encoder>,
|
||||
/// The block with every sample finite and within ±1, as the encoder requires.
|
||||
planes: Vec<Vec<f32>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Codec {
|
||||
/// Encodes `planes` (one slice per encoder channel, equally long, at most [`CHUNK`] frames)
|
||||
/// and appends the packets completed.
|
||||
fn push(&mut self, planes: &[&[f32]], out: &mut Vec<Packet>) -> Result<()> {
|
||||
match self {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Codec::Aac(enc) => out.extend(enc.encode(planes).into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Codec::Alac { enc, quantizers, pending } => {
|
||||
let frames = planes.first().map_or(0, |p| p.len());
|
||||
let mut at = 0;
|
||||
while at < frames {
|
||||
let filled = pending.first().map_or(0, Vec::len);
|
||||
let end = frames.min(at + CHUNK.saturating_sub(filled).max(1));
|
||||
for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) {
|
||||
dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s)));
|
||||
}
|
||||
at = end;
|
||||
if pending.first().is_some_and(|p| p.len() >= CHUNK) {
|
||||
alac_packet(enc, pending, out)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Codec::Mp3(enc) => {
|
||||
let data = enc.encode(planes);
|
||||
if !data.is_empty() {
|
||||
out.push(Packet { data, frames: 0 });
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Codec::Ac3 { enc, planes: clean } => {
|
||||
for (dst, src) in clean.iter_mut().zip(planes) {
|
||||
dst.clear();
|
||||
dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }));
|
||||
}
|
||||
let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect();
|
||||
out.extend(enc.push(&refs)?.into_iter().map(|p| Packet { data: p.data, frames: p.samples }));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encodes what the encoder still holds and appends the last packets.
|
||||
fn finish(&mut self, out: &mut Vec<Packet>) -> Result<()> {
|
||||
match self {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Codec::Aac(enc) => out.extend(enc.flush().into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })),
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Codec::Alac { enc, pending, .. } => {
|
||||
if pending.first().is_some_and(|p| !p.is_empty()) {
|
||||
alac_packet(enc, pending, out)?;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
Codec::Mp3(enc) => {
|
||||
let data = enc.flush();
|
||||
if !data.is_empty() {
|
||||
out.push(Packet { data, frames: 0 });
|
||||
}
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
Codec::Ac3 { enc, .. } => out.extend(enc.finish()?.packets.into_iter().map(|p| Packet { data: p.data, frames: p.samples })),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decoded frames before the first frame of the audio.
|
||||
fn priming(&self) -> u32 {
|
||||
match self {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Codec::Aac(enc) => enc.priming_samples(),
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames`
|
||||
/// frames in all): the configuration a decoder needs, with the average bit rate.
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
fn sample_entry(&self, sample_rate: u32, channels: u32, bytes: u64, frames: u64) -> Option<craft_media::isobmff::SampleEntry> {
|
||||
use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry};
|
||||
match self {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
Codec::Aac(enc) => {
|
||||
let mut entry = SampleEntry::aac(enc.audio_specific_config(), channels, sample_rate);
|
||||
if let CodecConfig::Aac(config) = &mut entry.codec
|
||||
&& frames > 0
|
||||
{
|
||||
let bps = u128::from(bytes) * 8 * u128::from(sample_rate) / u128::from(frames);
|
||||
config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX);
|
||||
}
|
||||
Some(entry)
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
Codec::Alac { enc, .. } => {
|
||||
let bits = u16::from(enc.encoder_config().bit_depth);
|
||||
Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.cookie() }, channels, f64::from(sample_rate), bits))
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes the pending samples as one ALAC packet and empties them.
|
||||
#[cfg(feature = "alac-encode")]
|
||||
fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec<i32>], out: &mut Vec<Packet>) -> Result<()> {
|
||||
let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect();
|
||||
let frames = refs.first().map_or(0, |p| p.len()) as u32;
|
||||
let data = enc.encode(&refs)?;
|
||||
pending.iter_mut().for_each(Vec::clear);
|
||||
out.push(Packet { data, frames });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A muxer's error as this crate's: a failed write stays an I/O error.
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
fn mux_error(e: craft_media::isobmff::Error) -> AudioError {
|
||||
@@ -285,6 +24,31 @@ fn mux_error(e: craft_media::isobmff::Error) -> AudioError {
|
||||
}
|
||||
}
|
||||
|
||||
/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` frames in
|
||||
/// all): the configuration a decoder needs, with the average bit rate.
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
fn sample_entry(enc: &PacketEncoder, bytes: u64, frames: u64) -> Option<craft_media::isobmff::SampleEntry> {
|
||||
use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry};
|
||||
let (rate, channels) = (enc.sample_rate(), u32::from(enc.channels()));
|
||||
match enc.codec() {
|
||||
CodecId::Aac => {
|
||||
let mut entry = SampleEntry::aac(enc.extradata(), channels, rate);
|
||||
if let CodecConfig::Aac(config) = &mut entry.codec
|
||||
&& frames > 0
|
||||
{
|
||||
let bps = u128::from(bytes) * 8 * u128::from(rate) / u128::from(frames);
|
||||
config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX);
|
||||
}
|
||||
Some(entry)
|
||||
}
|
||||
CodecId::Alac => {
|
||||
let bits = u16::from(enc.bit_depth().unwrap_or(16));
|
||||
Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.extradata() }, channels, f64::from(rate), bits))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// An M4A file being written: one audio track whose samples are the packets.
|
||||
///
|
||||
/// The last packet is held back until the length is known: its duration is cut to the audio's
|
||||
@@ -298,9 +62,8 @@ struct M4a<W: Write + Seek> {
|
||||
track: Option<usize>,
|
||||
entry: craft_media::isobmff::SampleEntry,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
priming: u32,
|
||||
held: Option<Packet>,
|
||||
held: Option<EncodedPacket>,
|
||||
/// Frames and bytes of the packets written, the held one not counted.
|
||||
frames: u64,
|
||||
bytes: u64,
|
||||
@@ -308,13 +71,14 @@ struct M4a<W: Write + Seek> {
|
||||
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
impl<W: Write + Seek> M4a<W> {
|
||||
fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> Result<Self> {
|
||||
fn new(out: W, enc: &PacketEncoder) -> Result<Self> {
|
||||
use craft_media::isobmff::{Brand, Mp4Writer, WriterOptions};
|
||||
let entry = codec.sample_entry(sample_rate, channels, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?;
|
||||
let entry = sample_entry(enc, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?;
|
||||
let sample_rate = enc.sample_rate();
|
||||
let mut options = WriterOptions::new(Brand::Mp4);
|
||||
options.movie_timescale = sample_rate;
|
||||
let mux = Mp4Writer::new(out, options).map_err(mux_error)?;
|
||||
Ok(M4a { mux, track: None, entry, sample_rate, channels, priming: codec.priming(), held: None, frames: 0, bytes: 0 })
|
||||
Ok(M4a { mux, track: None, entry, sample_rate, priming: enc.priming(), held: None, frames: 0, bytes: 0 })
|
||||
}
|
||||
|
||||
fn track(&mut self, has_audio: bool) -> Result<usize> {
|
||||
@@ -333,7 +97,7 @@ impl<W: Write + Seek> M4a<W> {
|
||||
Ok(track)
|
||||
}
|
||||
|
||||
fn sample(&mut self, packet: &Packet, duration: u32) -> Result<()> {
|
||||
fn sample(&mut self, packet: &EncodedPacket, duration: u32) -> Result<()> {
|
||||
let track = self.track(true)?;
|
||||
let sample = craft_media::isobmff::WriteSample { data: &packet.data, duration, composition_offset: 0, is_sync: true };
|
||||
self.mux.write_sample(track, sample).map_err(mux_error)?;
|
||||
@@ -342,22 +106,22 @@ impl<W: Write + Seek> M4a<W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write(&mut self, packet: Packet) -> Result<()> {
|
||||
fn write(&mut self, packet: EncodedPacket) -> Result<()> {
|
||||
if let Some(held) = self.held.replace(packet) {
|
||||
self.sample(&held, held.frames)?;
|
||||
self.sample(&held, held.duration)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes the last packet, cut to the end of `audio_frames` frames of audio, and the `moov`.
|
||||
fn finish(mut self, codec: &Codec, audio_frames: u64) -> Result<W> {
|
||||
/// Writes the last packet, cut to the end of the audio the encoder took, and the `moov`.
|
||||
fn finish(mut self, enc: &PacketEncoder) -> Result<W> {
|
||||
if let Some(held) = self.held.take() {
|
||||
let rest = (u64::from(self.priming) + audio_frames).saturating_sub(self.frames);
|
||||
self.sample(&held, rest.min(u64::from(held.frames)) as u32)?;
|
||||
let rest = (u64::from(self.priming) + enc.frames()).saturating_sub(self.frames);
|
||||
self.sample(&held, rest.min(u64::from(held.duration)) as u32)?;
|
||||
}
|
||||
let track = self.track(false)?;
|
||||
// The configuration is complete only now: the bit rate, and ALAC's largest packet.
|
||||
if let Some(entry) = codec.sample_entry(self.sample_rate, self.channels, self.bytes, self.frames) {
|
||||
if let Some(entry) = sample_entry(enc, self.bytes, self.frames) {
|
||||
self.mux.set_sample_entry(track, entry).map_err(mux_error)?;
|
||||
}
|
||||
self.mux.finish().map_err(mux_error)
|
||||
@@ -374,15 +138,8 @@ enum Sink<W: Write + Seek> {
|
||||
|
||||
/// A file of one of the coded formats written block by block.
|
||||
pub(crate) struct Writer<W: Write + Seek> {
|
||||
codec: Codec,
|
||||
enc: PacketEncoder,
|
||||
sink: Sink<W>,
|
||||
/// For each encoder channel, the caller's channel that feeds it.
|
||||
map: Vec<usize>,
|
||||
/// The constant bit rate the encoder was set to, bits per second; `None` for ALAC and for
|
||||
/// AAC at a constant quality.
|
||||
bitrate: Option<u32>,
|
||||
frames: u64,
|
||||
packets: Vec<Packet>,
|
||||
/// Set when a write has failed: the encoder and the sink no longer agree, so the writer
|
||||
/// refuses every later call.
|
||||
failed: bool,
|
||||
@@ -390,68 +147,23 @@ pub(crate) struct Writer<W: Write + Seek> {
|
||||
|
||||
impl<W: Write + Seek> Writer<W> {
|
||||
pub(crate) fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: usize) -> Result<Self> {
|
||||
validate_layout(channels, sample_rate)?;
|
||||
let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels as u16));
|
||||
let (codec, map, bitrate) = match opts.format {
|
||||
#[cfg(feature = "aac-encode")]
|
||||
EncodeFormat::Aac => {
|
||||
let map = fixed_map(EncodeFormat::Aac, "AAC", aac_order(channels), &layout)?;
|
||||
let mode = aac_mode(opts.rate_control, sample_rate, channels);
|
||||
let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, channels, 0) };
|
||||
let bitrate = match mode {
|
||||
crate::aac::BitrateMode::Cbr(bps) => Some(bps),
|
||||
crate::aac::BitrateMode::Vbr(_) => None,
|
||||
};
|
||||
(Codec::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, bitrate)
|
||||
}
|
||||
#[cfg(feature = "alac-encode")]
|
||||
EncodeFormat::Alac => {
|
||||
let count = u8::try_from(channels).unwrap_or(u8::MAX);
|
||||
let map = fixed_map(EncodeFormat::Alac, "ALAC", crate::alac::alac_order(count), &layout)?;
|
||||
let bits = match opts.bit_depth {
|
||||
crate::BitDepth::Int16 => 16,
|
||||
crate::BitDepth::Int24 => 24,
|
||||
crate::BitDepth::Int32 => 32,
|
||||
crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())),
|
||||
};
|
||||
let enc = crate::alac::Encoder::new(crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32))?;
|
||||
let quantizers = super::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, channels);
|
||||
(Codec::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); channels] }, map, None)
|
||||
}
|
||||
#[cfg(feature = "mp3-encode")]
|
||||
EncodeFormat::Mp3 => {
|
||||
let map = fixed_map(EncodeFormat::Mp3, "MP3", None, &layout)?;
|
||||
let want = constant_kbps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * channels as u32)?;
|
||||
// A sample rate MP3 has not is the encoder's to refuse.
|
||||
let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want);
|
||||
let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, channels, kbps))?;
|
||||
(Codec::Mp3(Box::new(enc)), map, Some(kbps.saturating_mul(1000)))
|
||||
}
|
||||
#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))]
|
||||
EncodeFormat::Ac3 | EncodeFormat::Eac3 => {
|
||||
let codec = if opts.format == EncodeFormat::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 };
|
||||
let (config, map) = ac3_config(codec, sample_rate, &layout, opts.rate_control)?;
|
||||
let enc = crate::ac3::encoder::Encoder::new(config)?;
|
||||
(Codec::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); channels] }, map, Some(config.bitrate_kbps.saturating_mul(1000)))
|
||||
}
|
||||
#[allow(unreachable_patterns)]
|
||||
f => return Err(AudioError::Unsupported(format!("writing {f:?}"))),
|
||||
};
|
||||
let channels = u16::try_from(channels).map_err(|_| AudioError::Encode("too many channels".into()))?;
|
||||
let enc = PacketEncoder::new(opts.format.codec(), opts, sample_rate, channels)?;
|
||||
let sink = match opts.format {
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &codec, sample_rate, channels as u32)?)),
|
||||
EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &enc)?)),
|
||||
_ => Sink::Raw(out),
|
||||
};
|
||||
Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false })
|
||||
Ok(Writer { enc, sink, failed: false })
|
||||
}
|
||||
|
||||
pub(crate) fn bitrate(&self) -> Option<u32> {
|
||||
self.bitrate
|
||||
self.enc.bitrate()
|
||||
}
|
||||
|
||||
/// Hands the packets waiting to the sink.
|
||||
fn drain(&mut self) -> Result<()> {
|
||||
for packet in self.packets.drain(..) {
|
||||
/// Hands `packets` to the sink.
|
||||
fn drain(&mut self, packets: Vec<EncodedPacket>) -> Result<()> {
|
||||
for packet in packets {
|
||||
match &mut self.sink {
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
Sink::M4a(m4a) => m4a.write(packet)?,
|
||||
@@ -466,16 +178,16 @@ impl<W: Write + Seek> Writer<W> {
|
||||
if self.failed {
|
||||
return Err(failed_write_error());
|
||||
}
|
||||
for at in (0..frames).step_by(CHUNK) {
|
||||
let end = frames.min(at + CHUNK);
|
||||
let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect();
|
||||
let written = self.codec.push(&planes, &mut self.packets).and_then(|()| self.drain());
|
||||
// A block at a time, so the packets waiting for the sink stay few however long it is.
|
||||
for at in (0..frames).step_by(crate::packet::CHUNK) {
|
||||
let end = frames.min(at + crate::packet::CHUNK);
|
||||
let part: Vec<&[f32]> = block.iter().map(|c| c.as_ref().get(at..end).unwrap_or_default()).collect();
|
||||
let written = self.enc.encode(&part, end - at).and_then(|packets| self.drain(packets));
|
||||
if let Err(e) = written {
|
||||
self.failed = true;
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
self.frames = self.frames.saturating_add(frames as u64);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -483,11 +195,11 @@ impl<W: Write + Seek> Writer<W> {
|
||||
if self.failed {
|
||||
return Err(failed_write_error());
|
||||
}
|
||||
self.codec.finish(&mut self.packets)?;
|
||||
self.drain()?;
|
||||
let last = self.enc.finish()?;
|
||||
self.drain(last)?;
|
||||
match self.sink {
|
||||
#[cfg(any(feature = "aac-encode", feature = "alac-encode"))]
|
||||
Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames),
|
||||
Sink::M4a(m4a) => m4a.finish(&self.enc),
|
||||
Sink::Raw(mut out) => {
|
||||
out.flush()?;
|
||||
Ok(out)
|
||||
@@ -501,6 +213,3 @@ pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result<Vec<u8>>
|
||||
w.write(&buf.channels, buf.frames())?;
|
||||
Ok(w.finish()?.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -8,7 +8,7 @@ mod aiff;
|
||||
mod coded;
|
||||
#[cfg(feature = "flac-encode")]
|
||||
pub(crate) mod flac;
|
||||
mod pcm;
|
||||
pub(crate) mod pcm;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
mod vorbis;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
|
||||
@@ -153,3 +153,39 @@ fn ffmpeg_decodes_our_alac_exactly() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quiet and silent passages at 24 and 32 bits, which our encoder codes with fewer shifted-off
|
||||
/// low bytes than Apple's reference (#1368), decode exactly in ffmpeg. The packets alternate
|
||||
/// between silence, audio within 12 bits, audio at the narrower widths' edges and full scale, so
|
||||
/// one stream changes its shift from packet to packet.
|
||||
#[test]
|
||||
fn ffmpeg_decodes_our_quiet_alac_exactly() {
|
||||
let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return };
|
||||
for (channels, bits) in [(1, 24), (2, 24), (6, 24), (1, 32), (2, 32)] {
|
||||
let full = input(channels, bits, 4 * 4096);
|
||||
let wav: Vec<Vec<i32>> = full
|
||||
.iter()
|
||||
.map(|c| {
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &x)| match i / 4096 {
|
||||
0 => 0,
|
||||
1 => x >> (bits - 12),
|
||||
2 => (x >> (bits - 15)) << (bits - 24),
|
||||
_ => x,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
// ffmpeg does not decode escaped 32-bit stereo frames: keep the full-scale packet for 24
|
||||
let wav: Vec<Vec<i32>> = if bits == 32 { wav.iter().map(|c| c[..3 * 4096].to_vec()).collect() } else { wav };
|
||||
let m4a = our_m4a(&wav, bits, 4096);
|
||||
let path = dir().join(format!("ours_quiet_{channels}ch_{bits}.m4a"));
|
||||
std::fs::write(&path, &m4a).unwrap();
|
||||
let theirs = ffmpeg_decode(&ff, &path, channels, bits);
|
||||
assert!(theirs == wav, "{channels} ch, {bits} bits: ffmpeg's decode differs from the input");
|
||||
if bits <= 24 {
|
||||
assert!(our_decode(&m4a, bits) == wav, "{channels} ch, {bits} bits: our decode differs");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ mod mp3_encoder_oracle;
|
||||
mod mpa_oracle;
|
||||
mod opus;
|
||||
mod opusenc;
|
||||
mod packet_encoder;
|
||||
mod routing_oracle;
|
||||
mod track_decoder;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
|
||||
@@ -268,9 +268,7 @@ fn extreme_inputs_stay_decodable() {
|
||||
let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw).unwrap(), &planar);
|
||||
assert!(packets.iter().all(|p| p.len() >= 3 && p.len() <= 1276), "{name} {mode:?}: packet sizes");
|
||||
let dec = decode(&enc.opus_head(), &packets);
|
||||
let peak = dec.iter().flatten().fold(0f32, |m, v| m.max(v.abs()));
|
||||
let snr = if name == "nan" { f64::NAN } else { snr_search(&planar[0], &dec[0], 2).0 };
|
||||
eprintln!("{name} {mode:?}/{bw:?} {c} ch: peak {peak:.2}, SNR {snr:.1} dB, {:.1} kb/s", bitrate(&packets) / 1000.0);
|
||||
assert_eq!(dec.len(), c, "{name} {mode:?}/{bw:?} {c} ch: decoded channels");
|
||||
assert!(dec.iter().all(|ch| ch.iter().all(|v| v.is_finite() && v.abs() <= 4.0)), "{name} {mode:?}/{bw:?} {c} ch: bad output");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! `PacketEncoder`: every codec round-trips through `TrackDecoder` from the description the
|
||||
//! encoder gives, at the length that was encoded and with each channel on its speaker.
|
||||
|
||||
use std::io::Cursor;
|
||||
|
||||
use craft_audio::{
|
||||
AudioError, BitDepth, ChannelLayout, CodecId, EncodeFormat, EncodeOptions, EncodedPacket, FileEncoder, PacketEncoder, TrackDecoder,
|
||||
};
|
||||
|
||||
/// `channels` channels of `frames` frames, each a tone of its own frequency low enough for an LFE.
|
||||
fn tones(sample_rate: u32, channels: usize, frames: usize) -> Vec<Vec<f32>> {
|
||||
(0..channels)
|
||||
.map(|c| {
|
||||
let step = (40.0 + 9.0 * c as f32) * std::f32::consts::TAU / sample_rate as f32;
|
||||
(0..frames).map(|i| ((i as f32 * step).sin() * 0.4 * 32768.0).round() / 32768.0).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Normalised correlation of two signals over the samples both have.
|
||||
fn correlation(a: &[f32], b: &[f32]) -> f64 {
|
||||
let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64);
|
||||
for (&x, &y) in a.iter().zip(b) {
|
||||
let (x, y) = (f64::from(x), f64::from(y));
|
||||
ab += x * y;
|
||||
aa += x * x;
|
||||
bb += y * y;
|
||||
}
|
||||
ab / (aa * bb).sqrt().max(1e-30)
|
||||
}
|
||||
|
||||
/// Encodes `input` in uneven blocks and returns the packets.
|
||||
fn encode(enc: &mut PacketEncoder, input: &[Vec<f32>]) -> Vec<EncodedPacket> {
|
||||
let frames = input[0].len();
|
||||
let mut packets = Vec::new();
|
||||
let mut at = 0;
|
||||
for n in [1, 999, 4096, 10_000, 7, usize::MAX].into_iter().cycle() {
|
||||
let n = n.min(frames - at);
|
||||
let block: Vec<&[f32]> = input.iter().map(|c| &c[at..at + n]).collect();
|
||||
packets.extend(enc.encode(&block, n).unwrap());
|
||||
at += n;
|
||||
if at == frames {
|
||||
break;
|
||||
}
|
||||
}
|
||||
packets.extend(enc.finish().unwrap());
|
||||
packets
|
||||
}
|
||||
|
||||
/// Encodes, checks the timing the packets carry, decodes them from the encoder's description, and
|
||||
/// returns the decoded audio from the first input frame on, cut to the input's length, and the
|
||||
/// layout the decoder reports.
|
||||
fn decode_back(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec<f32>]) -> (PacketEncoder, Vec<Vec<f32>>, ChannelLayout) {
|
||||
let frames = input[0].len();
|
||||
let mut enc = PacketEncoder::new(codec, opts, sample_rate, input.len() as u16).unwrap();
|
||||
let packets = encode(&mut enc, input);
|
||||
assert_eq!(enc.frames(), frames as u64);
|
||||
// The packets follow one another, and add up to the priming, the audio and the padding.
|
||||
let mut pts = 0;
|
||||
for p in &packets {
|
||||
assert_eq!(p.pts, pts, "{codec:?}");
|
||||
pts += u64::from(p.duration);
|
||||
}
|
||||
assert_eq!(pts, u64::from(enc.priming()) + frames as u64 + enc.padding(), "{codec:?}");
|
||||
let last = packets.last().map_or(0, |p| u64::from(p.duration));
|
||||
assert!(enc.padding() < last, "{codec:?}: {} samples of padding after a packet of {last}", enc.padding());
|
||||
|
||||
let lookahead: Vec<&[u8]> = packets.iter().take(craft_audio::LOOKAHEAD_PACKETS).map(|p| p.data.as_slice()).collect();
|
||||
let mut dec = TrackDecoder::new(&enc.codec_params(), &lookahead).unwrap();
|
||||
assert_eq!((dec.codec(), dec.sample_rate()), (codec, sample_rate), "{codec:?}");
|
||||
let mut out = vec![Vec::new(); usize::from(dec.channels())];
|
||||
for p in &packets {
|
||||
let block = dec.decode(&p.data).unwrap();
|
||||
assert_eq!(block.frames(), p.duration as usize, "{codec:?}: a packet's duration is what it decodes to");
|
||||
for (o, c) in out.iter_mut().zip(block.channels) {
|
||||
o.extend(c);
|
||||
}
|
||||
}
|
||||
let skip = enc.priming() as usize;
|
||||
let out = out.into_iter().map(|c| c[skip..skip + frames].to_vec()).collect();
|
||||
(enc, out, dec.layout())
|
||||
}
|
||||
|
||||
/// [`decode_back`] for a codec whose decoder returns every channel: on the speakers encoded.
|
||||
fn round_trip(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec<f32>]) -> (PacketEncoder, Vec<Vec<f32>>) {
|
||||
let (enc, out, layout) = decode_back(codec, opts, sample_rate, input);
|
||||
assert_eq!(layout, enc.layout(), "{codec:?}");
|
||||
(enc, out)
|
||||
}
|
||||
|
||||
/// Each decoded channel is its input channel, in place: it matches that channel and no other. The
|
||||
/// AC-3 encoders low-pass the LFE, which shifts its phase, so the match is by magnitude.
|
||||
fn assert_in_place(codec: CodecId, input: &[Vec<f32>], output: &[Vec<f32>], least: f64) {
|
||||
for (c, got) in output.iter().enumerate() {
|
||||
let scores: Vec<f64> = input.iter().map(|want| correlation(want, got).abs()).collect();
|
||||
let least = if matches!(codec, CodecId::Ac3 | CodecId::Eac3) && c == 3 { 0.5 } else { least };
|
||||
assert!(scores[c] > least, "{codec:?} channel {c}: {scores:?}");
|
||||
for (other, &score) in scores.iter().enumerate().filter(|&(o, _)| o != c) {
|
||||
assert!(score < scores[c] - 0.3, "{codec:?} channel {c} matches channel {other}: {scores:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aac_round_trips_in_place() {
|
||||
let input = tones(48_000, 6, 30_001);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(384_000);
|
||||
let (enc, out) = round_trip(CodecId::Aac, &opts, 48_000, &input);
|
||||
assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (1024, ChannelLayout::SURROUND_5_1_SIDE, Some(384_000)));
|
||||
assert_eq!(enc.extradata().len(), 2, "an AudioSpecificConfig for channel configuration 6");
|
||||
assert_in_place(CodecId::Aac, &input, &out, 0.95);
|
||||
}
|
||||
|
||||
/// 16-bit ALAC is lossless: the input comes back bit for bit.
|
||||
#[test]
|
||||
fn alac_round_trips_exactly() {
|
||||
let input = tones(44_100, 6, 10_000);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1);
|
||||
let (enc, out) = round_trip(CodecId::Alac, &opts, 44_100, &input);
|
||||
assert_eq!((enc.priming(), enc.padding(), enc.bit_depth(), enc.layout()), (0, 0, Some(16), ChannelLayout::SURROUND_5_1));
|
||||
assert_eq!(out, input);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mp3_round_trips_in_place() {
|
||||
for (rate, frame) in [(48_000, 1152), (44_100, 1152), (24_000, 576)] {
|
||||
let input = tones(rate, 2, 20_000);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(192_000);
|
||||
let mut enc = PacketEncoder::new(CodecId::Mp3, &opts, rate, 2).unwrap();
|
||||
let packets = encode(&mut enc, &input);
|
||||
assert!(packets.iter().all(|p| p.duration == frame && p.data[0] == 0xFF), "{rate} Hz");
|
||||
let (enc, out) = round_trip(CodecId::Mp3, &opts, rate, &input);
|
||||
assert_eq!((enc.priming(), enc.extradata()), (1057, vec![]));
|
||||
assert_in_place(CodecId::Mp3, &input, &out, 0.95);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ac3_round_trips_in_place() {
|
||||
let input = tones(48_000, 6, 20_000);
|
||||
let (enc, out) = round_trip(CodecId::Ac3, &EncodeOptions::new(EncodeFormat::Ac3), 48_000, &input);
|
||||
assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (256, ChannelLayout::SURROUND_5_1_SIDE, Some(448_000)));
|
||||
assert_in_place(CodecId::Ac3, &input, &out, 0.9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eac3_round_trips_in_place() {
|
||||
let input = tones(48_000, 6, 20_000);
|
||||
let (enc, out) = round_trip(CodecId::Eac3, &EncodeOptions::new(EncodeFormat::Eac3), 48_000, &input);
|
||||
assert_eq!((enc.priming(), enc.layout()), (256, ChannelLayout::SURROUND_5_1_SIDE));
|
||||
assert_in_place(CodecId::Eac3, &input, &out, 0.9);
|
||||
}
|
||||
|
||||
/// 7.1 E-AC-3 is encoded as 7.1; `TrackDecoder` plays its 5.1 independent substream (see the
|
||||
/// README), at the same length.
|
||||
#[test]
|
||||
fn eac3_7_1_decodes_as_its_5_1_substream() {
|
||||
let input = tones(48_000, 8, 20_000);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_7_1);
|
||||
let (enc, out, layout) = decode_back(CodecId::Eac3, &opts, 48_000, &input);
|
||||
assert_eq!((enc.layout(), enc.channels(), layout), (ChannelLayout::SURROUND_7_1, 8, ChannelLayout::SURROUND_5_1_SIDE));
|
||||
assert!(out.iter().all(|c| c.len() == 20_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opus_round_trips_in_place() {
|
||||
for channels in [1, 2] {
|
||||
let input = tones(48_000, channels, 20_000);
|
||||
let opts = EncodeOptions::default().with_bitrate(128_000);
|
||||
let (enc, out) = round_trip(CodecId::Opus, &opts, 48_000, &input);
|
||||
let head = enc.extradata();
|
||||
assert_eq!((&head[..8], head[9], u32::from(u16::from_le_bytes([head[10], head[11]]))), (&b"OpusHead"[..], channels as u8, enc.priming()));
|
||||
assert_in_place(CodecId::Opus, &input, &out, 0.9);
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw streams `FileEncoder` writes are the packets in a row.
|
||||
#[test]
|
||||
fn file_encoder_writes_the_packets() {
|
||||
for (format, layout) in [(EncodeFormat::Mp3, ChannelLayout::STEREO), (EncodeFormat::Ac3, ChannelLayout::SURROUND_5_1)] {
|
||||
let input = tones(48_000, usize::from(layout.channels()), 12_345);
|
||||
let opts = EncodeOptions::new(format).with_layout(layout);
|
||||
let mut file = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, layout.channels()).unwrap();
|
||||
file.write(&input, 12_345).unwrap();
|
||||
let file = file.finish().unwrap().into_inner();
|
||||
let mut enc = PacketEncoder::new(format.codec(), &opts, 48_000, layout.channels()).unwrap();
|
||||
let packets: Vec<u8> = encode(&mut enc, &input).into_iter().flat_map(|p| p.data).collect();
|
||||
assert_eq!(file, packets, "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What a codec cannot take is refused, and as `EncodeOptions::check` refuses it for the format.
|
||||
#[test]
|
||||
fn unsupported_settings_are_refused() {
|
||||
let unsupported =
|
||||
|codec, opts: &EncodeOptions, rate, channels| matches!(PacketEncoder::new(codec, opts, rate, channels), Err(AudioError::Unsupported(_)));
|
||||
let opts = EncodeOptions::default();
|
||||
assert!(unsupported(CodecId::Vorbis, &opts, 48_000, 2));
|
||||
assert!(unsupported(CodecId::Flac, &opts, 48_000, 2));
|
||||
assert!(unsupported(CodecId::Opus, &opts, 44_100, 2));
|
||||
assert!(unsupported(CodecId::Opus, &opts, 48_000, 3));
|
||||
assert!(unsupported(CodecId::Opus, &opts.clone().with_quality(0.5), 48_000, 2));
|
||||
for (codec, format, rate, channels) in [
|
||||
(CodecId::Mp3, EncodeFormat::Mp3, 96_000, 2),
|
||||
(CodecId::Mp3, EncodeFormat::Mp3, 48_000, 0),
|
||||
(CodecId::Mp3, EncodeFormat::Mp3, 48_000, 6),
|
||||
(CodecId::Ac3, EncodeFormat::Ac3, 48_000, 8),
|
||||
(CodecId::Aac, EncodeFormat::Aac, 44_000, 2),
|
||||
] {
|
||||
let opts = EncodeOptions::new(format);
|
||||
let (packets, file) = (PacketEncoder::new(codec, &opts, rate, channels).map(drop), opts.check(rate, channels));
|
||||
assert_eq!(format!("{packets:?}"), format!("{file:?}"), "{codec:?} {rate} {channels}");
|
||||
assert!(packets.is_err());
|
||||
}
|
||||
assert!(unsupported(CodecId::Alac, &opts.clone().with_bit_depth(BitDepth::Float32), 48_000, 2));
|
||||
assert!(unsupported(CodecId::Ac3, &opts.clone().with_layout(ChannelLayout::unordered(2)), 48_000, 2));
|
||||
// A layout for another channel count is the caller's mistake.
|
||||
assert!(matches!(PacketEncoder::new(CodecId::Aac, &opts.with_layout(ChannelLayout::STEREO), 48_000, 1), Err(AudioError::Encode(_))));
|
||||
}
|
||||
|
||||
/// Blocks that do not fit, and calls after `finish`, are errors that leave the stream as it was.
|
||||
#[test]
|
||||
fn misuse_is_an_error() {
|
||||
let mut enc = PacketEncoder::new(CodecId::Aac, &EncodeOptions::new(EncodeFormat::Aac), 48_000, 2).unwrap();
|
||||
let short = [vec![0.0f32; 10], vec![0.0; 5]];
|
||||
assert!(matches!(enc.encode(&short, 10), Err(AudioError::Encode(_))));
|
||||
assert!(matches!(enc.encode(&short[..1], 5), Err(AudioError::Encode(_))));
|
||||
assert_eq!(enc.frames(), 0);
|
||||
assert!(enc.encode(&short, 5).unwrap().is_empty());
|
||||
assert_eq!(enc.finish().unwrap().len(), 2, "5 frames after 1024 of priming fit in two packets");
|
||||
assert!(matches!(enc.finish(), Err(AudioError::Encode(_))));
|
||||
assert!(matches!(enc.encode(&short, 5), Err(AudioError::Encode(_))));
|
||||
// An encoder given nothing returns nothing: no packets, no frames and no padding. `priming`
|
||||
// is the codec's delay either way, so it equals that of an encoder that was given input.
|
||||
for codec in [CodecId::Aac, CodecId::Alac, CodecId::Mp3, CodecId::Ac3, CodecId::Eac3, CodecId::Opus] {
|
||||
let mut enc = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap();
|
||||
assert!(enc.finish().unwrap().is_empty(), "{codec:?}");
|
||||
assert_eq!((enc.frames(), enc.padding()), (0, 0), "{codec:?}");
|
||||
let mut fed = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap();
|
||||
fed.encode(&short, 5).unwrap();
|
||||
fed.finish().unwrap();
|
||||
assert_eq!(enc.priming(), fed.priming(), "{codec:?}");
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,9 @@ mod mp2_encoder_oracle;
|
||||
#[cfg(feature = "qoa")]
|
||||
#[path = "qoa_oracle.rs"]
|
||||
mod qoa_oracle;
|
||||
#[cfg(feature = "s302m")]
|
||||
#[path = "s302m_oracle.rs"]
|
||||
mod s302m_oracle;
|
||||
#[cfg(feature = "sbc")]
|
||||
#[path = "sbc_oracle.rs"]
|
||||
mod sbc_oracle;
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! SMPTE 302M (feature `s302m`) against ffmpeg (oracle; skipped when ffmpeg is absent, a failure
|
||||
//! with `CRAFT_MEDIA_REQUIRE_ORACLES=1`): we decode the packets ffmpeg's encoder puts in a transport
|
||||
//! stream to the samples ffmpeg decodes, our encoder writes the same bytes, and ffmpeg decodes
|
||||
//! packets of ours (patched into a transport stream) to our samples.
|
||||
|
||||
use craft_audio::s302m::{Encoder, decode, parse_header};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn signal(channels: usize, frames: usize, seed: u32) -> Vec<i32> {
|
||||
let mut x = seed | 1;
|
||||
let mut out = Vec::with_capacity(frames * channels);
|
||||
for i in 0..frames {
|
||||
for c in 0..channels {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
let tone = ((i as f64) * (0.03 + 0.011 * c as f64)).sin() * 0.6;
|
||||
let noise = f64::from(x % 2000) / 2000.0 - 0.5;
|
||||
out.push(((tone + 0.3 * noise) * f64::from(i32::MAX)) as i32);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_every_size_and_channel_count() {
|
||||
for channels in [2usize, 4, 6, 8] {
|
||||
for bits in [16u32, 20, 24] {
|
||||
let max = 1i64 << (bits - 1);
|
||||
let mut e = Encoder::new(channels, bits).expect("encoder");
|
||||
let frames = 500;
|
||||
let samples: Vec<i32> = signal(channels, frames, 3).iter().map(|&v| (i64::from(v) * max / (1 << 31)) as i32).collect();
|
||||
let mut all = Vec::new();
|
||||
for chunk in samples.chunks(channels * 193) {
|
||||
let p = e.encode(chunk).expect("encode");
|
||||
let d = decode(&p).expect("decode");
|
||||
assert_eq!((d.header.channels, d.header.bits), (channels, bits));
|
||||
all.extend(d.samples);
|
||||
}
|
||||
assert_eq!(all, samples, "{channels}ch {bits} bits");
|
||||
}
|
||||
}
|
||||
// the extremes
|
||||
for bits in [16u32, 20, 24] {
|
||||
let (lo, hi) = (-(1i32 << (bits - 1)), (1i32 << (bits - 1)) - 1);
|
||||
let mut e = Encoder::new(2, bits).expect("encoder");
|
||||
assert_eq!(decode(&e.encode(&[lo, hi, hi, lo, 0, -1]).expect("encode")).expect("decode").samples, vec![lo, hi, hi, lo, 0, -1]);
|
||||
assert!(e.encode(&[hi + 1, 0]).is_err());
|
||||
assert!(e.encode(&[lo - 1, 0]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_packet_size_limit_and_headers_are_checked() {
|
||||
let mut e = Encoder::new(2, 16).expect("encoder");
|
||||
let max = e.max_frames();
|
||||
assert!(e.encode(&vec![0; max * 2]).is_ok());
|
||||
assert!(e.encode(&vec![0; (max + 1) * 2]).is_err());
|
||||
let p = Encoder::new(8, 24).expect("encoder").channel_id(0x55).encode(&[0; 8]).expect("encode");
|
||||
let h = parse_header(&p).expect("header");
|
||||
assert_eq!((h.channels, h.channel_id, h.bits, h.audio_bytes), (8, 0x55, 24, 28));
|
||||
assert_eq!(h.frame_bytes(), 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_packets_are_errors_never_panics() {
|
||||
let mut e = Encoder::new(4, 24).expect("encoder");
|
||||
let p = e.encode(&signal(4, 40, 5).iter().map(|&v| v >> 8).collect::<Vec<_>>()).expect("encode");
|
||||
for n in 0..p.len() {
|
||||
let _ = decode(&p[..n]);
|
||||
}
|
||||
let mut x = 9u32;
|
||||
for i in 0..p.len() {
|
||||
let mut d = p.clone();
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
d[i] ^= (x >> 8) as u8 | 1;
|
||||
let _ = decode(&d);
|
||||
}
|
||||
assert!(decode(&[]).is_err());
|
||||
assert!(decode(&[0xFF, 0xFF, 0, 0, 1, 2, 3]).is_err());
|
||||
assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err(), "the reserved size code");
|
||||
}
|
||||
|
||||
// ---- ffmpeg as the reference
|
||||
|
||||
fn ffmpeg(ff: &Path, args: &[&str]) {
|
||||
let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg");
|
||||
assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn s(p: &Path) -> String {
|
||||
p.to_str().expect("path").to_string()
|
||||
}
|
||||
|
||||
/// The elementary-stream bytes of every PES packet of PID 0x100 in a transport stream, each as
|
||||
/// the list of (offset in the file, length) pieces it is spread over.
|
||||
fn pes_pieces(ts: &[u8]) -> Vec<Vec<(usize, usize)>> {
|
||||
let mut out: Vec<Vec<(usize, usize)>> = Vec::new();
|
||||
for (i, p) in ts.as_chunks::<188>().0.iter().enumerate() {
|
||||
if p[0] != 0x47 || ((usize::from(p[1] & 0x1F) << 8) | usize::from(p[2])) != 0x100 {
|
||||
continue;
|
||||
}
|
||||
let mut off = 4;
|
||||
if p[3] & 0x20 != 0 {
|
||||
off += 1 + usize::from(p[4]);
|
||||
}
|
||||
if p[3] & 0x10 == 0 || off >= 188 {
|
||||
continue;
|
||||
}
|
||||
let mut start = off;
|
||||
if p[1] & 0x40 != 0 {
|
||||
// a new PES packet: skip its header (00 00 01 id, length, flags, flags, header length, header)
|
||||
assert_eq!(&p[off..off + 3], &[0, 0, 1]);
|
||||
start = off + 9 + usize::from(p[off + 8]);
|
||||
out.push(Vec::new());
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.push((i * 188 + start, 188 - start));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn gather(ts: &[u8], pieces: &[(usize, usize)]) -> Vec<u8> {
|
||||
pieces.iter().flat_map(|&(o, n)| ts[o..o + n].iter().copied()).collect()
|
||||
}
|
||||
|
||||
fn pcm_bytes(samples: &[i32], wide: bool) -> Vec<u8> {
|
||||
if wide {
|
||||
samples.iter().flat_map(|v| v.to_le_bytes()).collect()
|
||||
} else {
|
||||
samples.iter().flat_map(|&v| ((v >> 16) as i16).to_le_bytes()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn decoded_by_ffmpeg(ff: &Path, ts: &Path, out: &Path, wide: bool) -> Vec<i32> {
|
||||
ffmpeg(ff, &["-i", &s(ts), "-f", if wide { "s32le" } else { "s16le" }, "-acodec", if wide { "pcm_s32le" } else { "pcm_s16le" }, &s(out)]);
|
||||
let bytes = std::fs::read(out).expect("read");
|
||||
if wide {
|
||||
bytes.as_chunks::<4>().0.iter().map(|b| i32::from_le_bytes(*b)).collect()
|
||||
} else {
|
||||
bytes.as_chunks::<2>().0.iter().map(|b| i32::from(i16::from_le_bytes(*b))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn we_decode_and_encode_what_ffmpeg_encodes_and_ffmpeg_decodes_ours() {
|
||||
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
|
||||
let dir = craft_media_testkit::fixture_subdir("s302m");
|
||||
for (channels, bits) in [(2usize, 16u32), (2, 20), (2, 24), (4, 20), (4, 24), (6, 16), (6, 20), (8, 20), (8, 24)] {
|
||||
let name = format!("{channels}ch{bits}");
|
||||
let frames = 6000;
|
||||
let wide = bits > 16;
|
||||
let pcm = signal(channels, frames, 17);
|
||||
let raw = dir.join(format!("{name}.pcm"));
|
||||
std::fs::write(&raw, pcm_bytes(&pcm, wide)).expect("write");
|
||||
let ts = dir.join(format!("{name}.ts"));
|
||||
let ch_str = channels.to_string();
|
||||
let raw_str = s(&raw);
|
||||
let ts_str = s(&ts);
|
||||
let mut ff_args = vec![
|
||||
"-f",
|
||||
if wide { "s32le" } else { "s16le" },
|
||||
"-ar",
|
||||
"48000",
|
||||
"-ac",
|
||||
&ch_str,
|
||||
"-i",
|
||||
&raw_str,
|
||||
"-af",
|
||||
"asetnsamples=n=1024:p=0",
|
||||
"-c:a",
|
||||
"s302m",
|
||||
"-strict",
|
||||
"-2",
|
||||
];
|
||||
if bits == 20 {
|
||||
ff_args.extend(["-bits_per_raw_sample", "20"]);
|
||||
}
|
||||
ff_args.extend(["-f", "mpegts", &ts_str]);
|
||||
ffmpeg(&ff, &ff_args);
|
||||
let bytes = std::fs::read(&ts).expect("read");
|
||||
let pieces = pes_pieces(&bytes);
|
||||
assert!(pieces.len() >= 2, "{name}: {} packets", pieces.len());
|
||||
let theirs = decoded_by_ffmpeg(&ff, &ts, &dir.join(format!("{name}.out.pcm")), wide);
|
||||
|
||||
let mut enc = Encoder::new(channels, bits).expect("encoder");
|
||||
let mut ours: Vec<i32> = Vec::new();
|
||||
let mut frames_seen = 0usize;
|
||||
for pes in &pieces {
|
||||
// the ES bytes of the packet: its own size field says how much of them is the packet
|
||||
let es = gather(&bytes, pes);
|
||||
let h = parse_header(&es).expect("header");
|
||||
let packet = &es[..4 + h.audio_bytes];
|
||||
let d = decode(packet).expect("decode");
|
||||
assert_eq!((d.header.channels, d.header.bits), (channels, bits), "{name}");
|
||||
// our encoder writes the same bytes ffmpeg's does
|
||||
assert!(enc.encode(&d.samples).expect("encode") == packet, "{name}: our packet differs from ffmpeg's at frame {frames_seen}");
|
||||
frames_seen += d.samples.len() / channels;
|
||||
// 20-bit and 24-bit samples are scaled to 32 bits by ffmpeg's decoder; 16-bit ones are not
|
||||
ours.extend(d.samples.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) }));
|
||||
}
|
||||
let n = ours.len().min(theirs.len());
|
||||
assert!(n >= (frames - 1600) * channels, "{name}: {n} samples");
|
||||
assert!(ours[..n] == theirs[..n], "{name}: our decode differs from ffmpeg's");
|
||||
|
||||
// ffmpeg decodes our packets: patch them over the same-sized ones in the stream
|
||||
let mine = signal(channels, frames, 23);
|
||||
let mut patched = bytes.clone();
|
||||
let mut enc = Encoder::new(channels, bits).expect("encoder");
|
||||
let mut expect: Vec<i32> = Vec::new();
|
||||
for pes in &pieces {
|
||||
let es = gather(&bytes, pes);
|
||||
let h = parse_header(&es).expect("header");
|
||||
let n_frames = h.audio_bytes / h.frame_bytes();
|
||||
let at = expect.len();
|
||||
let src: Vec<i32> = mine[at..at + n_frames * channels].iter().map(|&v| v >> (32 - bits)).collect();
|
||||
let packet = enc.encode(&src).expect("encode");
|
||||
assert_eq!(packet.len(), 4 + h.audio_bytes);
|
||||
expect.extend(src.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) }));
|
||||
let mut k = 0;
|
||||
for &(o, len) in pes {
|
||||
let take = len.min(packet.len() - k);
|
||||
patched[o..o + take].copy_from_slice(&packet[k..k + take]);
|
||||
k += take;
|
||||
}
|
||||
assert!(k >= packet.len());
|
||||
}
|
||||
let ours_ts = dir.join(format!("{name}.ours.ts"));
|
||||
std::fs::write(&ours_ts, patched).expect("write");
|
||||
let theirs = decoded_by_ffmpeg(&ff, &ours_ts, &dir.join(format!("{name}.ours.pcm")), wide);
|
||||
let n = expect.len().min(theirs.len());
|
||||
assert!(n >= (frames - 1600) * channels, "{name}: {n} samples");
|
||||
assert!(expect[..n] == theirs[..n], "{name}: ffmpeg decodes our packets differently");
|
||||
println!("{name}: {} PES packets, {n} samples identical both ways", pieces.len());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-captions"
|
||||
description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML/IMSC1/DFXP readers and writers with exact time, and CEA-608/708 coding"
|
||||
description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL, ASS, TTML/IMSC1/DFXP and the legacy text formats (MicroDVD, MPL2, SubViewer, VPlayer, SAMI) readers and writers with exact time, and CEA-608/708 coding"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -60,6 +60,11 @@ lists at most 20 characters per stream.
|
||||
| TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `<p>` per cue, `<br/>`, styled `<span>`s for `<i>` / `<b>` / `<u>`, `ttm:agent` speakers, exact frame times (`123f`) at the sequence rate. Reads any TTML (TTML1, TTML2, the 2006 `ttaf1` drafts): clock / frame / offset / tick times, `dur`, nested time containers (`body` / `div` begins offset and ends clip their contents; `seq` containers are read as `par` with a warning), timed spans, referenced styles. |
|
||||
| DFXP `.dfxp` | yes | yes | TTML1 with the DFXP presentation profile; clock times in milliseconds (frame-exact after `snap_to_frames`). |
|
||||
| ASS / SSA `.ass`, `.ssa` | yes | yes (ASS v4+) | The `[Events]` section: `Dialogue:` lines through the file's `Format:` line, `Name` as the speaker, `\N`, `\n`, `\h` and the `\i`, `\b`, `\u` override tags kept (as `<i>`, `<b>`, `<u>`); other override tags and drawing lines are dropped. Times are centiseconds. Written files have one `Default` style. |
|
||||
| MicroDVD `.sub` | yes | yes | `{first}{last}text` with frame numbers; the `{1}{1}fps` line or 23.976 fps. `\|` breaks a line; `{y:i,b,u}` and `{c:$BBGGRR}` style a line (capital `Y` / `C`: the rest of the cue too); other controls are dropped. Writing always names the rate (`WriteOptions::rate`, 23.976 by default) and styles only a line that `<i>`, `<b>` or `<u>` wraps whole. |
|
||||
| MPL2 `.mpl` | yes | yes | `[start][end]text` in tenths of a second; `\|` breaks a line, a leading `/` makes it italic. |
|
||||
| SubViewer 2 `.sbv` (also `.sub`) | yes | yes | `start,end` in hundredths of a second after the `[INFORMATION]` header; `[br]` breaks a line. Text only; no styles. |
|
||||
| VPlayer `.vpl` (also `.txt`) | yes | yes | `HH:MM:SS[.cc]=text` (`:` or a space also separate); only start times, a caption lasts to the next line (empty text clears), four seconds for the last. Text only. |
|
||||
| SAMI `.smi` | yes | yes | `<SYNC Start=ms>` blocks, ` ` clears; `<br>`, `<i>`, `<b>`, `<u>`, `<font color>` kept; first language class only. |
|
||||
|
||||
All cue times are exact `Tick`s. Milliseconds convert exactly (1 ms = 254 016 000 ticks); SCC
|
||||
frames map through `FrameRate::FPS_29_97`. `Document::snap_to_frames` snaps cues to a frame grid and
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! - **Files:** [SubRip](srt) (`.srt`), [WebVTT](vtt) (`.vtt`), [Scenarist SCC](scc) (`.scc`,
|
||||
//! CEA-608 pop-on, roll-up and paint-on on read; pop-on on write), [MacCaption MCC](mcc)
|
||||
//! (`.mcc`, SMPTE ST 334-2 packets with CEA-608 and CEA-708), [EBU STL](stl) (`.stl`, EBU
|
||||
//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a
|
||||
//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`), the legacy text formats [MicroDVD](microdvd) (`.sub`), [MPL2](mpl2) (`.mpl`), [SubViewer 2](subviewer) (`.sub`), [VPlayer](vplayer) (`.vpl`) and [SAMI](sami) (`.smi`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a
|
||||
//! [`Document`] of [`Cue`]s and write back. Readers are forgiving (BOM, UTF-16, Windows-1252
|
||||
//! fallback, CRLF/CR, missing SRT indexes, `,` or `.` milliseconds, missing hours, no blank
|
||||
//! line between cues); writers are strict. WebVTT cue identifiers, cue settings, `<v Speaker>`
|
||||
@@ -36,17 +36,22 @@ pub mod ass;
|
||||
pub mod cea608;
|
||||
pub mod jacosub;
|
||||
pub mod mcc;
|
||||
pub mod microdvd;
|
||||
#[cfg(feature = "mov-text")]
|
||||
pub mod mov_text;
|
||||
pub mod mpl2;
|
||||
pub mod pjs;
|
||||
pub mod realtext;
|
||||
pub mod sami;
|
||||
pub mod scc;
|
||||
pub mod srt;
|
||||
pub mod stl;
|
||||
pub mod subviewer;
|
||||
mod text;
|
||||
/// Exact time: `craft-timeline`'s ticks, frame rates and timecode fields.
|
||||
pub use craft_timeline::time;
|
||||
pub mod ttml;
|
||||
pub mod vplayer;
|
||||
pub mod vtt;
|
||||
|
||||
pub use text::{decode_entities, entity_at, plain_text};
|
||||
@@ -77,6 +82,16 @@ pub enum Format {
|
||||
Dfxp,
|
||||
/// Advanced SubStation Alpha (also reads SubStation Alpha).
|
||||
Ass,
|
||||
/// MicroDVD (frame-numbered text).
|
||||
MicroDvd,
|
||||
/// MPL2 (times in tenths of a second).
|
||||
Mpl2,
|
||||
/// SubViewer 2.
|
||||
SubViewer,
|
||||
/// VPlayer (start times only).
|
||||
VPlayer,
|
||||
/// SAMI (HTML-like).
|
||||
Sami,
|
||||
/// Phoenix Japanimation Society (PJS) subtitles.
|
||||
Pjs,
|
||||
/// RealText streaming timed text markup.
|
||||
@@ -86,7 +101,7 @@ pub enum Format {
|
||||
}
|
||||
|
||||
impl Format {
|
||||
pub const ALL: [Format; 11] = [
|
||||
pub const ALL: [Format; 16] = [
|
||||
Format::Srt,
|
||||
Format::WebVtt,
|
||||
Format::Scc,
|
||||
@@ -95,6 +110,11 @@ impl Format {
|
||||
Format::Ttml,
|
||||
Format::Dfxp,
|
||||
Format::Ass,
|
||||
Format::MicroDvd,
|
||||
Format::Mpl2,
|
||||
Format::SubViewer,
|
||||
Format::VPlayer,
|
||||
Format::Sami,
|
||||
Format::Pjs,
|
||||
Format::RealText,
|
||||
Format::JacoSub,
|
||||
@@ -109,6 +129,11 @@ impl Format {
|
||||
Format::Ttml => "TTML (IMSC1)",
|
||||
Format::Dfxp => "DFXP (TTML1)",
|
||||
Format::Ass => "Advanced SubStation Alpha (ASS)",
|
||||
Format::MicroDvd => "MicroDVD",
|
||||
Format::Mpl2 => "MPL2",
|
||||
Format::SubViewer => "SubViewer 2",
|
||||
Format::VPlayer => "VPlayer",
|
||||
Format::Sami => "SAMI",
|
||||
Format::Pjs => "PJS",
|
||||
Format::RealText => "RealText",
|
||||
Format::JacoSub => "JACOsub",
|
||||
@@ -124,6 +149,12 @@ impl Format {
|
||||
Format::Ttml => "ttml",
|
||||
Format::Dfxp => "dfxp",
|
||||
Format::Ass => "ass",
|
||||
Format::MicroDvd => "sub",
|
||||
Format::Mpl2 => "mpl",
|
||||
// SubViewer files are `.sub` too, as MicroDVD ones are; `.sbv` tells the two apart.
|
||||
Format::SubViewer => "sbv",
|
||||
Format::VPlayer => "vpl",
|
||||
Format::Sami => "smi",
|
||||
Format::Pjs => "pjs",
|
||||
Format::RealText => "rt",
|
||||
Format::JacoSub => "jss",
|
||||
@@ -139,6 +170,11 @@ impl Format {
|
||||
"ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml),
|
||||
"dfxp" => Some(Format::Dfxp),
|
||||
"ass" | "ssa" => Some(Format::Ass),
|
||||
"sub" | "microdvd" => Some(Format::MicroDvd),
|
||||
"mpl" | "mpl2" => Some(Format::Mpl2),
|
||||
"subviewer" | "sbv" => Some(Format::SubViewer),
|
||||
"vplayer" | "vpl" => Some(Format::VPlayer),
|
||||
"smi" | "sami" => Some(Format::Sami),
|
||||
"pjs" => Some(Format::Pjs),
|
||||
"rt" | "realtext" => Some(Format::RealText),
|
||||
"jss" | "js" | "jacosub" => Some(Format::JacoSub),
|
||||
@@ -292,28 +328,51 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option<Format> {
|
||||
if head.starts_with("[Script Info]") {
|
||||
return Some(Format::Ass);
|
||||
}
|
||||
if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case("<sami"))
|
||||
&& head.as_bytes().get(5).is_some_and(|&b| b.is_ascii_whitespace() || b == b'>' || b == b'/')
|
||||
{
|
||||
return Some(Format::Sami);
|
||||
}
|
||||
if subviewer::is_header(head) {
|
||||
return Some(Format::SubViewer);
|
||||
}
|
||||
if realtext::is_realtext(head) {
|
||||
return Some(Format::RealText);
|
||||
}
|
||||
let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase());
|
||||
let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some());
|
||||
let first_lines: Vec<&str> = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect();
|
||||
if first_lines.first().is_some_and(|l| microdvd::is_cue(l)) {
|
||||
return Some(Format::MicroDvd);
|
||||
}
|
||||
if first_lines.first().is_some_and(|l| mpl2::split_cue(l).is_some()) {
|
||||
return Some(Format::Mpl2);
|
||||
}
|
||||
if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) {
|
||||
return Some(Format::SubViewer);
|
||||
}
|
||||
if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) {
|
||||
return Some(Format::VPlayer);
|
||||
}
|
||||
if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) {
|
||||
return Some(Format::Pjs);
|
||||
}
|
||||
if first_lines.iter().any(|l| jacosub::is_timed_line(l)) || (head.starts_with('#') && (head.contains("TimeRes") || head.contains("#T"))) {
|
||||
return Some(Format::JacoSub);
|
||||
}
|
||||
let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase());
|
||||
if (head.starts_with('<') && (head.contains("<tt ") || head.contains("<tt>") || head.contains(":tt ")))
|
||||
&& (head.contains("ns/ttml") || head.contains("ttaf1"))
|
||||
{
|
||||
let legacy = head.contains("ttaf1") || head.contains("dfxp");
|
||||
return Some(if ext.as_deref() == Some("dfxp") || (legacy && ext.as_deref() != Some("ttml")) { Format::Dfxp } else { Format::Ttml });
|
||||
}
|
||||
let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some());
|
||||
match ext.as_deref() {
|
||||
Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt),
|
||||
Some("vtt") if has_arrow_timing => Some(Format::WebVtt),
|
||||
Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "pjs" | "rt" | "jss" | "js") => None,
|
||||
Some(
|
||||
"srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "sub" | "mpl" | "vpl" | "smi" | "sami" | "pjs" | "rt"
|
||||
| "jss" | "js",
|
||||
) => None,
|
||||
_ if has_arrow_timing => Some(Format::Srt),
|
||||
_ => None,
|
||||
}
|
||||
@@ -348,6 +407,11 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result<Document> {
|
||||
Format::Mcc => mcc::parse(&text),
|
||||
Format::Ttml | Format::Dfxp => ttml::parse(&text),
|
||||
Format::Ass => ass::parse(&text),
|
||||
Format::MicroDvd => microdvd::parse(&text),
|
||||
Format::Mpl2 => mpl2::parse(&text),
|
||||
Format::SubViewer => subviewer::parse(&text),
|
||||
Format::VPlayer => vplayer::parse(&text),
|
||||
Format::Sami => sami::parse(&text),
|
||||
Format::Pjs => pjs::parse(&text),
|
||||
Format::RealText => realtext::parse(&text),
|
||||
Format::JacoSub => jacosub::parse(&text),
|
||||
@@ -389,6 +453,11 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec<u8> {
|
||||
Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(),
|
||||
Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(),
|
||||
Format::Ass => ass::write(doc).into_bytes(),
|
||||
Format::MicroDvd => microdvd::write(doc, opts.rate).into_bytes(),
|
||||
Format::Mpl2 => mpl2::write(doc).into_bytes(),
|
||||
Format::SubViewer => subviewer::write(doc).into_bytes(),
|
||||
Format::VPlayer => vplayer::write(doc).into_bytes(),
|
||||
Format::Sami => sami::write(doc).into_bytes(),
|
||||
Format::Pjs => pjs::write(doc).into_bytes(),
|
||||
Format::RealText => realtext::write(doc).into_bytes(),
|
||||
Format::JacoSub => jacosub::write(doc).into_bytes(),
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
//! MicroDVD (`.sub`): frame-numbered text.
|
||||
//!
|
||||
//! ```text
|
||||
//! {1}{1}23.976
|
||||
//! {24}{72}First line|{y:i}second line in italics
|
||||
//! ```
|
||||
//!
|
||||
//! A line is `{first frame}{last frame}text`; `|` starts a new line. A first cue `{1}{1}` or `{0}{0}`
|
||||
//! whose text is a number gives the frame rate; without it the rate is 23.976 fps (the rate other
|
||||
//! readers assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together)
|
||||
//! and `{c:$BBGGRR}` (colour) style the line they start; the capital forms `{Y:…}` and `{C:…}`
|
||||
//! style every later line of the cue too. Other controls (`{f:…}` font, `{s:…}` size, `{h:…}`, …)
|
||||
//! are dropped. Writing always starts with the `{1}{1}` rate line and styles a line only when
|
||||
//! `<i>`, `<b>` or `<u>` wraps all of it; other tags are dropped, and `{`, `}` and `|` in the
|
||||
//! text become the full-width `{`, `}` and `|`.
|
||||
|
||||
use crate::text::{LineStyle, escape_markup, number, plain_text, whole_line_style, wrap_style};
|
||||
use crate::time::FrameRate;
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
/// The frame rate of a file that does not name one.
|
||||
pub const DEFAULT_RATE: FrameRate = FrameRate::FPS_23_976;
|
||||
|
||||
/// `{a}{b}text` as its parts.
|
||||
fn split_cue(line: &str) -> Option<(i64, i64, &str)> {
|
||||
let rest = line.strip_prefix('{')?;
|
||||
let (a, rest) = rest.split_once('}')?;
|
||||
let rest = rest.strip_prefix('{')?;
|
||||
let (b, text) = rest.split_once('}')?;
|
||||
Some((number(a.trim())?, number(b.trim())?, text))
|
||||
}
|
||||
|
||||
/// Whether `line` is a `{first}{last}text` cue line.
|
||||
pub(crate) fn is_cue(line: &str) -> bool {
|
||||
split_cue(line).is_some()
|
||||
}
|
||||
|
||||
/// The frame rate a header cue's text names.
|
||||
fn header_rate(text: &str) -> Option<FrameRate> {
|
||||
let fps: f64 = text.trim().parse().ok()?;
|
||||
(fps.is_finite() && (1.0..=1000.0).contains(&fps)).then(|| FrameRate::from_f64(fps))
|
||||
}
|
||||
|
||||
/// A `$BBGGRR` colour as `#rrggbb`.
|
||||
fn colour(value: &str) -> Option<String> {
|
||||
let hex = value.trim().strip_prefix('$')?;
|
||||
if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let (b, rest) = hex.split_at(2);
|
||||
let (g, r) = rest.split_at(2);
|
||||
Some(format!("#{}{}{}", r.to_ascii_lowercase(), g.to_ascii_lowercase(), b.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
/// What the styling controls of a cue's lines set.
|
||||
#[derive(Default)]
|
||||
struct Sticky {
|
||||
style: LineStyle,
|
||||
colour: Option<String>,
|
||||
}
|
||||
|
||||
/// The text of one line without its `{x:…}` controls, and the controls in order.
|
||||
fn split_controls(line: &str) -> (String, Vec<(char, String)>) {
|
||||
let mut text = String::new();
|
||||
let mut controls = Vec::new();
|
||||
let mut rest = line;
|
||||
while let Some(open) = rest.find('{') {
|
||||
text.push_str(rest.get(..open).unwrap_or(""));
|
||||
let after = rest.get(open + 1..).unwrap_or("");
|
||||
// Check the fixed-size control prefix before scanning its body. Invalid opening
|
||||
// braces must not repeatedly scan the same suffix for a closing brace.
|
||||
let name = after.as_bytes().first().copied().filter(u8::is_ascii_alphabetic);
|
||||
if let Some(name) = name.filter(|_| after.as_bytes().get(1) == Some(&b':')) {
|
||||
if let Some((body, tail)) = after.get(2..).and_then(|s| s.split_once('}')) {
|
||||
controls.push((char::from(name), body.to_string()));
|
||||
rest = tail;
|
||||
} else {
|
||||
// No later control can close either: preserve the entire remaining text.
|
||||
text.push('{');
|
||||
text.push_str(after);
|
||||
rest = "";
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
text.push('{');
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
text.push_str(rest);
|
||||
(text, controls)
|
||||
}
|
||||
|
||||
fn apply_style(value: &str, style: &mut LineStyle) {
|
||||
for flag in value.split([',', ' ', '/']) {
|
||||
match flag.trim().to_ascii_lowercase().as_str() {
|
||||
"i" => style.italic = true,
|
||||
"b" => style.bold = true,
|
||||
"u" => style.underline = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cue_text(raw: &str) -> String {
|
||||
let mut sticky = Sticky::default();
|
||||
let mut lines = Vec::new();
|
||||
for line in raw.split('|') {
|
||||
let (text, controls) = split_controls(line);
|
||||
let mut style = sticky.style;
|
||||
let mut line_colour = sticky.colour.clone();
|
||||
for (name, value) in controls {
|
||||
match name {
|
||||
'y' => apply_style(&value, &mut style),
|
||||
'Y' => {
|
||||
apply_style(&value, &mut style);
|
||||
apply_style(&value, &mut sticky.style);
|
||||
}
|
||||
'c' => line_colour = colour(&value).or(line_colour),
|
||||
'C' => {
|
||||
line_colour = colour(&value).or(line_colour);
|
||||
sticky.colour = line_colour.clone();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
lines.push(wrap_style(style, line_colour.as_deref(), &escape_markup(text)));
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let mut rows = Vec::new();
|
||||
let mut rate = DEFAULT_RATE;
|
||||
let mut has_rate_line = false;
|
||||
let mut doc = Document::default();
|
||||
for (n, line) in text.lines().enumerate() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match split_cue(line) {
|
||||
Some((0, 0, t) | (1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => {
|
||||
rate = header_rate(t).unwrap_or(rate);
|
||||
has_rate_line = true;
|
||||
}
|
||||
Some(row) => rows.push(row),
|
||||
None => doc.warnings.push(format!("line {}: not a MicroDVD cue, skipped", n + 1)),
|
||||
}
|
||||
}
|
||||
if rows.is_empty() && !has_rate_line && !text.trim().is_empty() {
|
||||
return Err(Error::NotFormat("MicroDVD"));
|
||||
}
|
||||
for (first, last, raw) in rows {
|
||||
let (start, end) = (rate.tick_of(first), rate.tick_of(last));
|
||||
let text = cue_text(raw);
|
||||
if end <= start || text.is_empty() {
|
||||
doc.warnings.push(format!("the cue at frame {first} is empty or ends at frame {last}; skipped"));
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start, end, text, ..Default::default() });
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// Write `doc` with its frames counted at `rate` (None: [`DEFAULT_RATE`]).
|
||||
pub fn write(doc: &Document, rate: Option<FrameRate>) -> String {
|
||||
let rate = rate.map_or(DEFAULT_RATE, FrameRate::sane);
|
||||
let mut out = format!("{{1}}{{1}}{:.3}\n", rate.as_f64());
|
||||
let frame = |t| rate.frame_at(rate.snap_nearest(t)).max(0);
|
||||
for c in &doc.cues {
|
||||
let first = frame(c.start);
|
||||
let last = frame(c.end).max(first.saturating_add(1));
|
||||
let mut lines = Vec::new();
|
||||
for line in c.text.lines() {
|
||||
let (style, inner) = whole_line_style(line);
|
||||
let text = plain_text(inner).trim().replace('{', "\u{ff5b}").replace('}', "\u{ff5d}").replace('|', "\u{ff5c}");
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut flags = Vec::new();
|
||||
for (on, f) in [(style.italic, "i"), (style.bold, "b"), (style.underline, "u")] {
|
||||
if on {
|
||||
flags.push(f);
|
||||
}
|
||||
}
|
||||
lines.push(if flags.is_empty() { text } else { format!("{{y:{}}}{text}", flags.join(",")) });
|
||||
}
|
||||
if lines.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push_str(&format!("{{{first}}}{{{last}}}{}\n", lines.join("|")));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn controls_style_lines() {
|
||||
assert_eq!(cue_text("{y:i,b}x|plain"), "<i><b>x</b></i>\nplain");
|
||||
assert_eq!(cue_text("{Y:i}a|b"), "<i>a</i>\n<i>b</i>");
|
||||
assert_eq!(cue_text("{c:$0000ff}red"), "<font color=\"#ff0000\">red</font>");
|
||||
assert_eq!(cue_text("{f:Arial}{s:20}a & b {x"), "a & b {x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_controls_inside_valid_cues_are_preserved() {
|
||||
for raw in ["{".repeat(32_768), "{y:".repeat(16_384)] {
|
||||
let doc = parse(&format!("{{0}}{{25}}{raw}")).unwrap();
|
||||
assert_eq!(doc.cues.len(), 1);
|
||||
assert_eq!(doc.cues[0].text, raw);
|
||||
}
|
||||
assert_eq!(cue_text("{{y:i}hello"), "<i>{hello</i>");
|
||||
assert_eq!(cue_text("{xx:no}{y:b}hello"), "<b>{xx:no}hello</b>");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_header() {
|
||||
let d = parse("{1}{1}25.000\n{25}{50}x\n").unwrap();
|
||||
assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25));
|
||||
let d = parse("{0}{0}25.000\n{25}{50}x\n{50}{75}29.97\n").unwrap();
|
||||
assert_eq!(d.cues.len(), 2);
|
||||
assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25));
|
||||
assert_eq!(d.cues[1].start, FrameRate::FPS_25.tick_of(50));
|
||||
assert_eq!(d.cues[1].text, "29.97");
|
||||
let d = parse("{25}{50}x\n").unwrap();
|
||||
assert_eq!(d.cues[0].start, DEFAULT_RATE.tick_of(25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("hello\nworld\n").is_err());
|
||||
assert!(parse("").unwrap().cues.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! MPL2 (`.txt`, `.mpl`): times in tenths of a second.
|
||||
//!
|
||||
//! ```text
|
||||
//! [10][35]First line|/second line in italics
|
||||
//! ```
|
||||
//!
|
||||
//! A line is `[start][end]text` with times in deciseconds. `|` starts a new line; a `/` at the
|
||||
//! start of a line makes it italic. Writing marks a line italic only when `<i>` wraps all of it,
|
||||
//! drops other tags, rounds times to a tenth of a second, writes `|` in text as `|`, and writes
|
||||
//! a leading `/` in non-italic text as `/`.
|
||||
|
||||
use crate::text::{escape_markup, ms_to_tick, number, plain_text, tick_to_ms, whole_line_style, wrap_style};
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
/// `[a][b]text` as its parts.
|
||||
pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> {
|
||||
let rest = line.strip_prefix('[')?;
|
||||
let (a, rest) = rest.split_once(']')?;
|
||||
let rest = rest.strip_prefix('[')?;
|
||||
let (b, text) = rest.split_once(']')?;
|
||||
Some((number(a.trim())?, number(b.trim())?, text))
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let mut doc = Document::default();
|
||||
let mut found = false;
|
||||
for (n, line) in text.lines().enumerate() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some((a, b, raw)) = split_cue(line) else {
|
||||
doc.warnings.push(format!("line {}: not an MPL2 cue, skipped", n + 1));
|
||||
continue;
|
||||
};
|
||||
found = true;
|
||||
let mut lines = Vec::new();
|
||||
for l in raw.split('|') {
|
||||
let (italic, l) = match l.trim().strip_prefix('/') {
|
||||
Some(r) => (true, r.trim().to_string()),
|
||||
None => {
|
||||
let t = l.trim();
|
||||
if let Some(rest) = t.strip_prefix('\u{ff0f}') { (false, format!("/{rest}")) } else { (false, t.to_string()) }
|
||||
}
|
||||
};
|
||||
if !l.is_empty() {
|
||||
lines.push(wrap_style(crate::text::LineStyle { italic, ..Default::default() }, None, &escape_markup(&l)));
|
||||
}
|
||||
}
|
||||
let (start, end) = (ms_to_tick(a.saturating_mul(100)), ms_to_tick(b.saturating_mul(100)));
|
||||
if end <= start || lines.is_empty() {
|
||||
doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1));
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() });
|
||||
}
|
||||
if !found && !text.trim().is_empty() {
|
||||
return Err(Error::NotFormat("MPL2"));
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document) -> String {
|
||||
let mut out = String::new();
|
||||
let ds = |t| (tick_to_ms(t) + 50) / 100;
|
||||
for c in &doc.cues {
|
||||
let start = ds(c.start);
|
||||
let end = ds(c.end).max(start + 1);
|
||||
let mut lines = Vec::new();
|
||||
for line in c.text.lines() {
|
||||
let (style, inner) = whole_line_style(line);
|
||||
let mut text = plain_text(inner).trim().replace('|', "\u{ff5c}");
|
||||
if !style.italic && text.starts_with('/') {
|
||||
text.replace_range(..1, "\u{ff0f}");
|
||||
}
|
||||
if !text.is_empty() {
|
||||
lines.push(if style.italic { format!("/{text}") } else { text });
|
||||
}
|
||||
}
|
||||
if !lines.is_empty() {
|
||||
out.push_str(&format!("[{start}][{end}]{}\n", lines.join("|")));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn italics_and_lines() {
|
||||
let d = parse("[10][35]Hello|/italic\n").unwrap();
|
||||
assert_eq!(d.cues[0].text, "Hello\n<i>italic</i>");
|
||||
assert_eq!(d.cues[0].end, ms_to_tick(3500));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_italic_leading_slash_roundtrip() {
|
||||
let doc = Document {
|
||||
cues: vec![Cue { start: ms_to_tick(1000), end: ms_to_tick(2000), text: "/not italic\n<i>/italic</i>".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert_eq!(written, "[10][20]/not italic|//italic\n");
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues[0].text, "/not italic\n<i>/italic</i>");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! SAMI (`.smi`, `.sami`): Microsoft's HTML-like captions.
|
||||
//!
|
||||
//! ```text
|
||||
//! <SAMI><BODY>
|
||||
//! <SYNC Start=1000><P Class=ENCC>First line<br>second line
|
||||
//! <SYNC Start=3500><P Class=ENCC>
|
||||
//! </BODY></SAMI>
|
||||
//! ```
|
||||
//!
|
||||
//! A `<SYNC Start=ms>` block shows its text from that millisecond until the next block; a block
|
||||
//! holding only ` ` clears the screen. The last caption lasts four seconds if nothing clears
|
||||
//! it. `<br>` starts a new line; `<i>`, `<b>`, `<u>` and `<font color>` are kept, other tags
|
||||
//! dropped; `&`, `<`, `>`, ` ` and numeric references are read. A file can hold
|
||||
//! several language classes (`<P Class=ENCC>`, `<P Class=KRCC>`): the first one named is read and
|
||||
//! the others skipped with a warning. Writing makes one `ENCC` class, an ` ` block where a
|
||||
//! caption ends before the next starts, and rounds to milliseconds.
|
||||
|
||||
use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, sequential, tick_to_ms};
|
||||
use crate::time::Tick;
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
/// The value of attribute `name` in the tag text `tag` (quotes optional).
|
||||
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
|
||||
let lower = tag.to_ascii_lowercase();
|
||||
let mut from = 0;
|
||||
while let Some(i) = lower.get(from..).and_then(|r| r.find(name)) {
|
||||
let at = from + i;
|
||||
from = at + name.len();
|
||||
let before_ok = at == 0 || lower.as_bytes().get(at - 1).is_some_and(|b| !b.is_ascii_alphanumeric());
|
||||
let rest = tag.get(from..).unwrap_or("").trim_start();
|
||||
let Some(rest) = rest.strip_prefix('=').filter(|_| before_ok) else { continue };
|
||||
let rest = rest.trim_start();
|
||||
return Some(match rest.chars().next() {
|
||||
Some(q @ ('"' | '\'')) => {
|
||||
let inner = rest.get(1..).unwrap_or("");
|
||||
inner.split(q).next().unwrap_or("")
|
||||
}
|
||||
_ => rest.split(|c: char| c.is_whitespace() || c == '>').next().unwrap_or(""),
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A numeric character reference body (`#65`, `#x41`) as its character.
|
||||
fn numeric_reference(body: &str) -> Option<char> {
|
||||
let digits = body.strip_prefix('#')?;
|
||||
let code = match digits.strip_prefix(['x', 'X']) {
|
||||
Some(hex) => u32::from_str_radix(hex, 16).ok()?,
|
||||
None => digits.parse().ok()?,
|
||||
};
|
||||
char::from_u32(code).filter(|c| !c.is_control() || *c == '\n')
|
||||
}
|
||||
|
||||
/// HTML text as cue text: entities the cue model keeps stay, numeric ones are decoded, a stray
|
||||
/// `&` is escaped, whitespace runs collapse.
|
||||
fn text_run(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = s;
|
||||
let mut space = false;
|
||||
while let Some(c) = rest.chars().next() {
|
||||
let mut advance = c.len_utf8();
|
||||
if c.is_whitespace() && c != '\u{a0}' {
|
||||
space = true;
|
||||
rest = rest.get(advance..).unwrap_or("");
|
||||
continue;
|
||||
}
|
||||
if space {
|
||||
out.push(' ');
|
||||
}
|
||||
space = false;
|
||||
if c == '&' {
|
||||
if let Some((_, len)) = crate::entity_at(rest) {
|
||||
out.push_str(rest.get(..len).unwrap_or(""));
|
||||
advance = len;
|
||||
} else if let Some(body) = rest.get(1..).and_then(|r| {
|
||||
// Numeric entities have at most eight body bytes. Never scan the
|
||||
// unbounded remainder again for each malformed ampersand.
|
||||
let end = r.bytes().take(9).position(|b| b == b';')?;
|
||||
r.get(..end)
|
||||
}) && let Some(ch) = numeric_reference(body)
|
||||
{
|
||||
out.push_str(&escape_markup(&ch.to_string()));
|
||||
advance = body.len() + 2;
|
||||
} else {
|
||||
out.push_str("&");
|
||||
}
|
||||
} else {
|
||||
out.push_str(&escape_markup(&c.to_string()));
|
||||
}
|
||||
rest = rest.get(advance..).unwrap_or("");
|
||||
}
|
||||
if space {
|
||||
out.push(' ');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One `<SYNC>` block's body as (class, cue text) segments, one per `<P>`.
|
||||
fn segments(body: &str) -> Vec<(String, String)> {
|
||||
let mut segs: Vec<(String, String)> = vec![(String::new(), String::new())];
|
||||
let mut open_fonts = 0usize;
|
||||
let mut rest = body;
|
||||
while !rest.is_empty() {
|
||||
let Some(lt) = rest.find('<') else {
|
||||
if let Some(last) = segs.last_mut() {
|
||||
last.1.push_str(&text_run(rest));
|
||||
}
|
||||
break;
|
||||
};
|
||||
if let Some(last) = segs.last_mut() {
|
||||
last.1.push_str(&text_run(rest.get(..lt).unwrap_or("")));
|
||||
}
|
||||
let after = rest.get(lt + 1..).unwrap_or("");
|
||||
let Some(gt) = after.find('>') else {
|
||||
if let Some(last) = segs.last_mut() {
|
||||
last.1.push_str("<");
|
||||
last.1.push_str(&text_run(after));
|
||||
}
|
||||
break;
|
||||
};
|
||||
let tag = after.get(..gt).unwrap_or("");
|
||||
rest = after.get(gt + 1..).unwrap_or("");
|
||||
let closing = tag.starts_with('/');
|
||||
let name: String = tag.trim_start_matches('/').chars().take_while(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase();
|
||||
let Some(last) = segs.last_mut() else { continue };
|
||||
match (name.as_str(), closing) {
|
||||
("br", _) => last.1.push('\n'),
|
||||
("p", false) => segs.push((attribute(tag, "class").unwrap_or("").to_string(), String::new())),
|
||||
("i" | "b" | "u", false) => last.1.push_str(&format!("<{name}>")),
|
||||
("i" | "b" | "u", true) => last.1.push_str(&format!("</{name}>")),
|
||||
("font", false) => {
|
||||
if let Some(c) = attribute(tag, "color").filter(|c| c.len() <= 20 && c.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#')) {
|
||||
open_fonts += 1;
|
||||
last.1.push_str(&format!("<font color=\"{c}\">"));
|
||||
}
|
||||
}
|
||||
("font", true) if open_fonts > 0 => {
|
||||
open_fonts -= 1;
|
||||
last.1.push_str("</font>");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
/// A caption text without the whitespace and non-breaking spaces round its lines.
|
||||
fn tidy(text: &str) -> String {
|
||||
let lines: Vec<String> = text
|
||||
.split('\n')
|
||||
.map(|l| l.replace(" ", " ").trim().to_string())
|
||||
.filter(|l| !l.is_empty() && !crate::plain_text(l).trim().is_empty())
|
||||
.collect();
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let lower = text.to_ascii_lowercase();
|
||||
let mut starts: Vec<usize> = Vec::new();
|
||||
let mut from = 0;
|
||||
while let Some(i) = lower.get(from..).and_then(|r| r.find("<sync")) {
|
||||
starts.push(from + i);
|
||||
from += i + 5;
|
||||
}
|
||||
if starts.is_empty() {
|
||||
return if text.trim().is_empty() || lower.contains("<sami") { Ok(Document::default()) } else { Err(Error::NotFormat("SAMI")) };
|
||||
}
|
||||
let mut doc = Document::default();
|
||||
let mut class: Option<String> = None;
|
||||
let mut skipped_class = false;
|
||||
let mut syncs: Vec<(Tick, String)> = Vec::new();
|
||||
for (k, &at) in starts.iter().enumerate() {
|
||||
let stop = starts.get(k + 1).copied().unwrap_or(text.len());
|
||||
let chunk = text.get(at..stop).unwrap_or("");
|
||||
let chunk = match chunk.to_ascii_lowercase().find("</body") {
|
||||
Some(i) => chunk.get(..i).unwrap_or(chunk),
|
||||
None => chunk,
|
||||
};
|
||||
let Some((tag, body)) = chunk.get(1..).and_then(|c| c.split_once('>')) else { continue };
|
||||
let Some(start) = attribute(tag, "start").and_then(|v| number(v.trim())) else {
|
||||
doc.warnings.push("a <SYNC> without a Start time was skipped".to_string());
|
||||
continue;
|
||||
};
|
||||
let mut shown = String::new();
|
||||
for (cls, seg) in segments(body) {
|
||||
if class.is_none() && !cls.is_empty() {
|
||||
class = Some(cls.to_ascii_lowercase());
|
||||
}
|
||||
if class.as_deref().is_none_or(|c| c == cls.to_ascii_lowercase() || cls.is_empty()) {
|
||||
shown.push_str(&seg);
|
||||
} else {
|
||||
skipped_class = true;
|
||||
}
|
||||
}
|
||||
syncs.push((ms_to_tick(start), tidy(&shown)));
|
||||
}
|
||||
if skipped_class {
|
||||
doc.warnings.push("the file has other language classes; only the first was read".to_string());
|
||||
}
|
||||
syncs.sort_by_key(|(t, _)| *t);
|
||||
for (i, (start, text)) in syncs.iter().enumerate() {
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let end = syncs.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next);
|
||||
if end <= *start {
|
||||
doc.warnings.push("two captions start at the same time; the first was skipped".to_string());
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() });
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document) -> String {
|
||||
let cues = sequential(doc);
|
||||
let mut out = String::from(
|
||||
"<SAMI>\n<HEAD>\n<TITLE></TITLE>\n<STYLE TYPE=\"text/css\">\n<!--\nP { margin-left: 8pt; margin-right: 8pt; text-align: center; font-size: 20pt; color: white; }\n.ENCC { Name: English; lang: en-US; SAMIType: CC; }\n-->\n</STYLE>\n</HEAD>\n<BODY>\n",
|
||||
);
|
||||
let active_cues: Vec<(&Cue, Vec<&str>)> = cues
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let lines: Vec<&str> = c.text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
|
||||
if lines.is_empty() { None } else { Some((c, lines)) }
|
||||
})
|
||||
.collect();
|
||||
let mut resolved_cues: Vec<(i64, i64, &Vec<&str>)> = Vec::with_capacity(active_cues.len());
|
||||
let mut prev_end = 0i64;
|
||||
for (c, lines) in &active_cues {
|
||||
let start_ms = tick_to_ms(c.start).max(prev_end);
|
||||
let end_ms = tick_to_ms(c.end).max(start_ms + 1);
|
||||
prev_end = end_ms;
|
||||
resolved_cues.push((start_ms, end_ms, lines));
|
||||
}
|
||||
for (i, &(start_ms, end_ms, lines)) in resolved_cues.iter().enumerate() {
|
||||
out.push_str(&format!("<SYNC Start={start_ms}><P Class=ENCC>{}\n", lines.join("<br>")));
|
||||
let next_start = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s);
|
||||
if next_start != Some(end_ms) {
|
||||
out.push_str(&format!("<SYNC Start={end_ms}><P Class=ENCC> \n"));
|
||||
}
|
||||
}
|
||||
out.push_str("</BODY>\n</SAMI>\n");
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn blocks_clear_and_style() {
|
||||
let d = parse("<SAMI><BODY>\n<SYNC Start=1000><P Class=ENCC>Hello<br>world & <i>you</i>\n<SYNC Start=3500><P Class=ENCC> \n<SYNC Start=4000><P Class=ENCC>x A y\n</BODY></SAMI>").unwrap();
|
||||
assert_eq!(d.cues.len(), 2);
|
||||
assert_eq!(d.cues[0].text, "Hello\nworld & <i>you</i>");
|
||||
assert_eq!(d.cues[0].end, ms_to_tick(3500));
|
||||
assert_eq!(d.cues[1].text, "x A y");
|
||||
assert_eq!(d.cues[1].end, last_cue_end(ms_to_tick(4000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_entities_inside_valid_cues_are_bounded() {
|
||||
let raw = "&".repeat(32_768);
|
||||
let doc = parse(&format!("<SAMI><SYNC Start=0><P>{raw}<SYNC Start=1000><P> ")).unwrap();
|
||||
assert_eq!(doc.cues.len(), 1);
|
||||
assert_eq!(doc.cues[0].text, "&".repeat(32_768));
|
||||
assert_eq!(text_run("A A A &é;"), "A &#00000065; A &é;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_first_class_is_read() {
|
||||
let d = parse("<SAMI><BODY><SYNC Start=1000><P Class=ENCC>en<P Class=KRCC>kr<SYNC Start=2000><P Class=ENCC> </BODY></SAMI>").unwrap();
|
||||
assert_eq!(d.cues.len(), 1);
|
||||
assert_eq!(d.cues[0].text, "en");
|
||||
assert_eq!(d.warnings.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("hello").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_duration_and_empty_cues() {
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue { start: ms_to_tick(100), end: Tick(ms_to_tick(100).0 + 1), text: "Brief".into(), ..Default::default() },
|
||||
Cue { start: ms_to_tick(101), end: ms_to_tick(200), text: " ".into(), ..Default::default() },
|
||||
Cue { start: ms_to_tick(500), end: ms_to_tick(600), text: "After gap".into(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert!(written.contains("<SYNC Start=100><P Class=ENCC>Brief\n<SYNC Start=101><P Class=ENCC> \n"));
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 2);
|
||||
assert_eq!(parsed.cues[0].start, ms_to_tick(100));
|
||||
assert_eq!(parsed.cues[0].end, ms_to_tick(101));
|
||||
assert_eq!(parsed.cues[1].start, ms_to_tick(500));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_short_cues_do_not_collide_after_rounding() {
|
||||
let t100 = ms_to_tick(100);
|
||||
let t100_1 = Tick(t100.0 + crate::TICKS_PER_MS / 10);
|
||||
let t200 = ms_to_tick(200);
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue { start: t100, end: t100_1, text: "First".into(), ..Default::default() },
|
||||
Cue { start: t100_1, end: t200, text: "Second".into(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let encoded = write(&doc);
|
||||
let back = parse(&encoded).unwrap();
|
||||
assert_eq!(back.cues.len(), 2);
|
||||
assert_eq!(back.cues[0].text, "First");
|
||||
assert_eq!(tick_to_ms(back.cues[0].start), 100);
|
||||
assert_eq!(tick_to_ms(back.cues[0].end), 101);
|
||||
assert_eq!(back.cues[1].text, "Second");
|
||||
assert_eq!(tick_to_ms(back.cues[1].start), 101);
|
||||
assert_eq!(tick_to_ms(back.cues[1].end), 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! SubViewer 2 (`.sub`): hundredths of a second, with an information header.
|
||||
//!
|
||||
//! ```text
|
||||
//! [INFORMATION]
|
||||
//! [TITLE]…
|
||||
//! [END INFORMATION]
|
||||
//! [SUBTITLE]
|
||||
//! 00:00:01.00,00:00:03.50
|
||||
//! First line[br]second line
|
||||
//!
|
||||
//! ```
|
||||
//!
|
||||
//! Reading skips the bracketed header lines and takes every `start,end` time line as a cue whose
|
||||
//! text runs to the next blank line; `[br]` starts a new line. Fractions of one to three digits
|
||||
//! are accepted. Writing adds a minimal header, rounds times to a hundredth of a second, drops
|
||||
//! tags, writes `[br]` inside text as `[br]`, and writes `,` in lines that match the timing
|
||||
//! syntax as `,`.
|
||||
|
||||
use crate::text::{escape_markup, plain_lines};
|
||||
use crate::time::{TICKS_PER_SECOND, Tick};
|
||||
use crate::{Cue, Document, Error, Result, parse_clock};
|
||||
|
||||
const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100;
|
||||
|
||||
/// Returns true if `head` begins with a genuine SubViewer header structure.
|
||||
pub(crate) fn is_header(head: &str) -> bool {
|
||||
let mut lines = head.lines().map(str::trim).filter(|l| !l.is_empty());
|
||||
match lines.next() {
|
||||
Some("[INFORMATION]") => lines.any(|l| {
|
||||
l == "[SUBTITLE]"
|
||||
|| l == "[END INFORMATION]"
|
||||
|| l.starts_with("[TITLE")
|
||||
|| l.starts_with("[AUTHOR")
|
||||
|| l.starts_with("[SOURCE")
|
||||
|| l.starts_with("[FILEPATH")
|
||||
|| l.starts_with("[DELAY")
|
||||
|| l.starts_with("[CD TRACK")
|
||||
|| l.starts_with("[COMMENT")
|
||||
|| (l.starts_with('[') && l.contains(']'))
|
||||
}),
|
||||
Some("[SUBTITLE]") => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `h:mm:ss.cc,h:mm:ss.cc` as its two times.
|
||||
pub(crate) fn parse_timing(line: &str) -> Option<(Tick, Tick)> {
|
||||
let (a, b) = line.trim().split_once(',')?;
|
||||
let ok = |s: &str| s.contains(':') && s.contains('.');
|
||||
if !ok(a) || !ok(b) {
|
||||
return None;
|
||||
}
|
||||
Some((parse_clock(a)?, parse_clock(b)?))
|
||||
}
|
||||
|
||||
/// Split `s` at each `[br]`, whatever its case.
|
||||
fn split_br(s: &str) -> Vec<&str> {
|
||||
let lower = s.to_ascii_lowercase();
|
||||
let mut parts = Vec::new();
|
||||
let mut from = 0;
|
||||
while let Some(i) = lower.get(from..).and_then(|r| r.find("[br]")) {
|
||||
parts.push(s.get(from..from + i).unwrap_or(""));
|
||||
from += i + 4;
|
||||
}
|
||||
parts.push(s.get(from..).unwrap_or(""));
|
||||
parts
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut doc = Document::default();
|
||||
let mut found = false;
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let Some((start, end)) = lines.get(i).and_then(|l| parse_timing(l)) else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
found = true;
|
||||
i += 1;
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
while let Some(l) = lines.get(i).filter(|l| !l.trim().is_empty()) {
|
||||
if parse_timing(l).is_some() {
|
||||
break;
|
||||
}
|
||||
out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(escape_markup));
|
||||
i += 1;
|
||||
}
|
||||
if end <= start || out.is_empty() {
|
||||
doc.warnings.push(format!("the cue at line {i} is empty or ends before it starts; skipped"));
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start, end, text: out.join("\n"), ..Default::default() });
|
||||
}
|
||||
let has_header = text.contains("[INFORMATION]") || text.contains("[SUBTITLE]");
|
||||
if !found && !has_header && !text.trim().is_empty() {
|
||||
return Err(Error::NotFormat("SubViewer"));
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
fn cs(t: Tick) -> u64 {
|
||||
((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as u64
|
||||
}
|
||||
|
||||
fn clock(cs: u64) -> String {
|
||||
format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100)
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document) -> String {
|
||||
let mut out = String::from(
|
||||
"[INFORMATION]\n[TITLE]\n[AUTHOR]\n[SOURCE]\n[PRG]\n[FILEPATH]\n[DELAY]0\n[CD TRACK]0\n[COMMENT]\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]no,[SIZE]18,[FONT]Arial\n",
|
||||
);
|
||||
for c in &doc.cues {
|
||||
let lines = plain_lines(&c.text);
|
||||
if lines.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let start_cs = cs(c.start);
|
||||
let end_cs = cs(c.end).max(start_cs + 1);
|
||||
out.push_str(&format!("{},{}\n", clock(start_cs), clock(end_cs)));
|
||||
let lines: Vec<String> = lines
|
||||
.into_iter()
|
||||
.map(|mut l| {
|
||||
if parse_timing(&l).is_some() {
|
||||
l = l.replacen(',', "\u{ff0c}", 1);
|
||||
}
|
||||
l.replace("[br]", "\u{ff3b}br\u{ff3d}")
|
||||
.replace("[BR]", "\u{ff3b}BR\u{ff3d}")
|
||||
.replace("[Br]", "\u{ff3b}Br\u{ff3d}")
|
||||
.replace("[bR]", "\u{ff3b}bR\u{ff3d}")
|
||||
})
|
||||
.collect();
|
||||
out.push_str(&lines.join("[br]"));
|
||||
out.push_str("\n\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn header_and_breaks() {
|
||||
let d = parse("[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:03.50\nHello[BR]world\n\n").unwrap();
|
||||
assert_eq!(d.cues[0].text, "Hello\nworld");
|
||||
assert_eq!(d.cues[0].end, crate::text::ms_to_tick(3500));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_escapes_every_case_of_literal_break_tokens() {
|
||||
let doc = Document {
|
||||
cues: vec![Cue { start: Tick(0), end: crate::text::ms_to_tick(1000), text: "a[br]b[BR]c[Br]d[bR]é".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
let decoded = parse(&write(&doc)).unwrap();
|
||||
assert_eq!(decoded.cues[0].text, "a[br]b[BR]c[Br]d[bR]é");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn centisecond_rounding_without_double_rounding_error() {
|
||||
// 1.0046s is 255_184_473_600 ticks (at 254_016_000_000 ticks/sec).
|
||||
// Direct rounding to hundredths gives 100cs (00:00:01.00).
|
||||
// Double-rounding through ms gives 1005ms -> 101cs (00:00:01.01).
|
||||
let t = Tick(255_184_473_600);
|
||||
assert_eq!(clock(cs(t)), "00:00:01.00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timing_shaped_text_escaped_and_roundtripped() {
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue { start: Tick(TICKS_PER_SECOND), end: Tick(3 * TICKS_PER_SECOND), text: "00:00:01.00,00:00:02.00".into(), ..Default::default() },
|
||||
Cue { start: Tick(4 * TICKS_PER_SECOND), end: Tick(5 * TICKS_PER_SECOND), text: "Second cue".into(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert!(written.contains("00:00:01.00,00:00:02.00"));
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 2);
|
||||
assert_eq!(parsed.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00");
|
||||
assert_eq!(parsed.cues[1].text, "Second cue");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_fullwidth_comma_preserved_on_read() {
|
||||
let raw = "[INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:02.00\n00:00:01.00\u{ff0c}00:00:02.00\n\n";
|
||||
let doc = parse(raw).unwrap();
|
||||
assert_eq!(doc.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00");
|
||||
}
|
||||
}
|
||||
@@ -85,8 +85,8 @@ pub fn plain_text(s: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
use crate::TICKS_PER_MS;
|
||||
use crate::time::{TICKS_PER_SECOND, Tick};
|
||||
use crate::{Cue, Document, TICKS_PER_MS};
|
||||
|
||||
/// How long the last cue of a format that gives only start times lasts: such a file says when a
|
||||
/// caption appears, and the next one ends it.
|
||||
@@ -131,6 +131,62 @@ pub(crate) fn plain_lines(text: &str) -> Vec<String> {
|
||||
text.lines().map(plain_text).map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// The style a whole line of cue text carries: `<i>`, `<b>` and `<u>` around all of it.
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct LineStyle {
|
||||
pub italic: bool,
|
||||
pub bold: bool,
|
||||
pub underline: bool,
|
||||
}
|
||||
|
||||
/// The style that wraps the whole of `line`, and the line without it. `<i>a</i> b <i>c</i>` is not
|
||||
/// italic as a whole.
|
||||
pub(crate) fn whole_line_style(line: &str) -> (LineStyle, &str) {
|
||||
let mut style = LineStyle::default();
|
||||
let mut rest = line.trim();
|
||||
loop {
|
||||
let mut changed = false;
|
||||
for (open, close, flag) in [("<i>", "</i>", 0), ("<b>", "</b>", 1), ("<u>", "</u>", 2)] {
|
||||
if let Some(inner) = rest.strip_prefix(open).and_then(|r| r.strip_suffix(close))
|
||||
&& !inner.contains(open)
|
||||
&& !inner.contains(close)
|
||||
{
|
||||
match flag {
|
||||
0 => style.italic = true,
|
||||
1 => style.bold = true,
|
||||
_ => style.underline = true,
|
||||
}
|
||||
rest = inner.trim();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return (style, rest);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cue text from a line's style and its (already escaped) text.
|
||||
pub(crate) fn wrap_style(style: LineStyle, color: Option<&str>, text: &str) -> String {
|
||||
let mut out = text.to_string();
|
||||
for (on, tag) in [(style.underline, "u"), (style.bold, "b"), (style.italic, "i")] {
|
||||
if on {
|
||||
out = format!("<{tag}>{out}</{tag}>");
|
||||
}
|
||||
}
|
||||
match color {
|
||||
Some(c) => format!("<font color=\"{c}\">{out}</font>"),
|
||||
None => out,
|
||||
}
|
||||
}
|
||||
|
||||
/// The cues of `doc` in time order with no overlaps, for a format that holds one caption at a time.
|
||||
pub(crate) fn sequential(doc: &Document) -> Vec<Cue> {
|
||||
let mut copy = Document { cues: doc.cues.clone(), ..Default::default() };
|
||||
copy.normalize();
|
||||
copy.cues
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! VPlayer (`.txt`, `.vpl`): one start time per caption.
|
||||
//!
|
||||
//! ```text
|
||||
//! 00:00:01.00=First line|second line
|
||||
//! 00:00:04.00=
|
||||
//! ```
|
||||
//!
|
||||
//! A line is `HH:MM:SS`, an optional `.cc` fraction, one of `:`, `=` or a space, and the text; `|`
|
||||
//! starts a new line. The file gives only when each caption appears: it stays until the next
|
||||
//! line, whose empty text clears it. The last caption lasts four seconds if no line ends it.
|
||||
//! Writing puts a clearing line where a caption ends before the next one starts, drops tags,
|
||||
//! rounds to a hundredth of a second and writes `|` in text as `|`.
|
||||
|
||||
use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, plain_lines, sequential};
|
||||
use crate::time::{TICKS_PER_SECOND, Tick};
|
||||
use crate::{Cue, Document, Error, Result};
|
||||
|
||||
const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100;
|
||||
|
||||
/// `HH:MM:SS[.cc]` then a separator and text: the time and the text.
|
||||
pub(crate) fn split_line(line: &str) -> Option<(Tick, &str)> {
|
||||
let mut parts = line.splitn(3, ':');
|
||||
let h = number(parts.next()?)?;
|
||||
let m = number(parts.next()?)?;
|
||||
let tail = parts.next()?;
|
||||
let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
|
||||
let s = number(tail.get(..digits)?)?;
|
||||
let mut rest = tail.get(digits..)?;
|
||||
let mut ms = 0;
|
||||
if let Some(frac) = rest.strip_prefix('.') {
|
||||
let n = frac.bytes().take_while(u8::is_ascii_digit).count().min(3);
|
||||
let f = frac.get(..n).filter(|f| !f.is_empty())?;
|
||||
ms = number(f)? * 10_i64.pow(3 - n as u32);
|
||||
rest = frac.get(n..)?;
|
||||
// further digits of a long fraction are below a millisecond
|
||||
rest = rest.trim_start_matches(|c: char| c.is_ascii_digit());
|
||||
}
|
||||
if m >= 60 || s >= 60 || h > 9999 {
|
||||
return None;
|
||||
}
|
||||
let text = rest.strip_prefix([':', '=', ' '])?;
|
||||
Some((ms_to_tick(((h * 60 + m) * 60 + s) * 1000 + ms), text))
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Document> {
|
||||
let mut doc = Document::default();
|
||||
let mut starts: Vec<(Tick, String)> = Vec::new();
|
||||
for (n, line) in text.lines().enumerate() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
match split_line(line.trim()) {
|
||||
Some((t, raw)) => {
|
||||
let lines: Vec<String> = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect();
|
||||
starts.push((t, lines.join("\n")));
|
||||
}
|
||||
None => doc.warnings.push(format!("line {}: not a VPlayer line, skipped", n + 1)),
|
||||
}
|
||||
}
|
||||
if starts.is_empty() && !text.trim().is_empty() {
|
||||
return Err(Error::NotFormat("VPlayer"));
|
||||
}
|
||||
for (i, (start, text)) in starts.iter().enumerate() {
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let end = starts.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next);
|
||||
if end <= *start {
|
||||
doc.warnings.push("a caption is followed by a line at the same time; skipped".to_string());
|
||||
continue;
|
||||
}
|
||||
doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() });
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
fn cs(t: Tick) -> i64 {
|
||||
((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as i64
|
||||
}
|
||||
|
||||
fn clock(cs: i64) -> String {
|
||||
format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100)
|
||||
}
|
||||
|
||||
pub fn write(doc: &Document) -> String {
|
||||
let cues = sequential(doc);
|
||||
let mut out = String::new();
|
||||
let active_cues: Vec<(&Cue, Vec<String>)> = cues
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let lines = plain_lines(&c.text);
|
||||
if lines.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let lines = lines.into_iter().map(|l| l.replace('|', "\u{ff5c}")).collect();
|
||||
Some((c, lines))
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut resolved_cues: Vec<(i64, i64, &Vec<String>)> = Vec::with_capacity(active_cues.len());
|
||||
let mut prev_end = 0i64;
|
||||
for (c, lines) in &active_cues {
|
||||
let start_cs = cs(c.start).max(prev_end);
|
||||
let end_cs = cs(c.end).max(start_cs + 1);
|
||||
prev_end = end_cs;
|
||||
resolved_cues.push((start_cs, end_cs, lines));
|
||||
}
|
||||
|
||||
for (i, &(start_cs, end_cs, lines)) in resolved_cues.iter().enumerate() {
|
||||
out.push_str(&format!("{}={}\n", clock(start_cs), lines.join("|")));
|
||||
let next_start_cs = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s);
|
||||
if next_start_cs != Some(end_cs) {
|
||||
out.push_str(&format!("{}=\n", clock(end_cs)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn short_duration_cue_preserves_positive_duration_on_write_and_read() {
|
||||
let mut doc = Document::default();
|
||||
// A cue from 0 to 1 ms collapses to 00:00:00.00 under centisecond rounding.
|
||||
doc.cues.push(Cue { start: ms_to_tick(0), end: ms_to_tick(1), text: "Short".to_string(), ..Default::default() });
|
||||
let written = write(&doc);
|
||||
assert_eq!(written, "00:00:00.00=Short\n00:00:00.01=\n");
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 1);
|
||||
assert_eq!(parsed.cues[0].text, "Short");
|
||||
assert_eq!(parsed.cues[0].start, ms_to_tick(0));
|
||||
assert_eq!(parsed.cues[0].end, ms_to_tick(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_short_cues_do_not_collide_after_rounding() {
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue { start: ms_to_tick(1000), end: ms_to_tick(1001), text: "First".to_string(), ..Default::default() },
|
||||
Cue { start: ms_to_tick(1001), end: ms_to_tick(1020), text: "Second".to_string(), ..Default::default() },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert_eq!(written, "00:00:01.00=First\n00:00:01.01=Second\n00:00:01.02=\n");
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 2);
|
||||
assert_eq!(parsed.cues[0].text, "First");
|
||||
assert_eq!(parsed.cues[0].start, ms_to_tick(1000));
|
||||
assert_eq!(parsed.cues[0].end, ms_to_tick(1010));
|
||||
assert_eq!(parsed.cues[1].text, "Second");
|
||||
assert_eq!(parsed.cues[1].start, ms_to_tick(1010));
|
||||
assert_eq!(parsed.cues[1].end, ms_to_tick(1020));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separators_and_ends() {
|
||||
let d = parse("00:00:01:Hello|world\n00:00:04.50=\n00:00:05 later\n").unwrap();
|
||||
assert_eq!(d.cues.len(), 2);
|
||||
assert_eq!(d.cues[0].text, "Hello\nworld");
|
||||
assert_eq!(d.cues[0].end, ms_to_tick(4500));
|
||||
assert_eq!(d.cues[1].end, ms_to_tick(9000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_text() {
|
||||
assert!(parse("hello\n").is_err());
|
||||
assert!(parse("00:00:01,000 --> 00:00:02,000\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_cue_skipped_and_numerical_timestamp_order() {
|
||||
let doc = Document {
|
||||
cues: vec![
|
||||
Cue {
|
||||
start: Tick(99 * 3600 * TICKS_PER_SECOND),
|
||||
end: Tick(99 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND),
|
||||
text: "At 99h".into(),
|
||||
..Default::default()
|
||||
},
|
||||
Cue {
|
||||
start: Tick(99 * 3600 * TICKS_PER_SECOND + 3 * TICKS_PER_SECOND),
|
||||
end: Tick(99 * 3600 * TICKS_PER_SECOND + 4 * TICKS_PER_SECOND),
|
||||
text: " ".into(),
|
||||
..Default::default()
|
||||
},
|
||||
Cue {
|
||||
start: Tick(100 * 3600 * TICKS_PER_SECOND),
|
||||
end: Tick(100 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND),
|
||||
text: "At 100h".into(),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let written = write(&doc);
|
||||
assert_eq!(written, "99:00:00.00=At 99h\n99:00:02.00=\n100:00:00.00=At 100h\n100:00:02.00=\n");
|
||||
let parsed = parse(&written).unwrap();
|
||||
assert_eq!(parsed.cues.len(), 2);
|
||||
assert_eq!(parsed.cues[0].text, "At 99h");
|
||||
assert_eq!(parsed.cues[1].text, "At 100h");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
//! The legacy text formats (MicroDVD, MPL2, SubViewer 2, VPlayer, SAMI): reading, writing, and
|
||||
//! ffmpeg as the reference (oracle; skipped when ffmpeg is absent, a failure with
|
||||
//! `CRAFT_MEDIA_REQUIRE_ORACLES=1`).
|
||||
|
||||
use craft_captions::time::FrameRate;
|
||||
use craft_captions::{Cue, Document, Format, TICKS_PER_SECOND, Tick, WriteOptions, detect, parse, plain_text, write};
|
||||
use std::process::Command;
|
||||
|
||||
const T: i64 = TICKS_PER_SECOND;
|
||||
const MS: i64 = T / 1000;
|
||||
|
||||
fn ms(v: i64) -> Tick {
|
||||
Tick(v * MS)
|
||||
}
|
||||
|
||||
/// The five formats, with the ffmpeg format name each is read and written through.
|
||||
const FORMATS: [(Format, &str, &str); 5] = [
|
||||
(Format::MicroDvd, "microdvd", "sub"),
|
||||
(Format::Mpl2, "mpl2", "txt"),
|
||||
(Format::SubViewer, "subviewer", "sbv"),
|
||||
(Format::VPlayer, "vplayer", "txt"),
|
||||
(Format::Sami, "sami", "smi"),
|
||||
];
|
||||
|
||||
const MICRODVD: &str = "{1}{1}23.976\n{24}{72}Hello|{y:i}second bold\n{100}{150}{c:$0000ff}red\n{200}{250}a & b < c\n";
|
||||
const MPL2: &str = "[10][35]Hello|/italic\n[40][60]plain\n[70][90]/a|/b\n";
|
||||
const SUBVIEWER: &str = "[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]bd,[SIZE]18,[FONT]Arial\n00:00:01.00,00:00:03.50\nHello[br]world\n\n00:00:04.00,00:00:05.00\nplain\n";
|
||||
const VPLAYER: &str = "00:00:01.00=Hello|world\n00:00:04.00=\n00:00:05:plain\n00:00:09 later\n";
|
||||
const SAMI: &str = "<SAMI>\n<HEAD><TITLE>x</TITLE></HEAD>\n<BODY>\n<SYNC Start=1000><P Class=ENCC>Hello<br>world\n<SYNC Start=3500><P Class=ENCC> \n<SYNC Start=4000><P Class=ENCC><i>plain</i> & more\n<SYNC Start=5000><P Class=ENCC> \n</BODY>\n</SAMI>\n";
|
||||
|
||||
fn samples() -> [(Format, &'static str); 5] {
|
||||
[(Format::MicroDvd, MICRODVD), (Format::Mpl2, MPL2), (Format::SubViewer, SUBVIEWER), (Format::VPlayer, VPLAYER), (Format::Sami, SAMI)]
|
||||
}
|
||||
|
||||
fn run(ff: &std::path::Path, args: &[&str]) {
|
||||
let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg");
|
||||
assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
/// What ffmpeg reads from `bytes` as `ffmpeg_format`, as cues.
|
||||
fn ffmpeg_reads(ff: &std::path::Path, name: &str, ffmpeg_format: &str, ext: &str, bytes: &[u8]) -> Document {
|
||||
let dir = craft_media_testkit::fixture_subdir("captions_legacy");
|
||||
let (input, out) = (dir.join(format!("{name}.{ext}")), dir.join(format!("{name}.srt")));
|
||||
std::fs::write(&input, bytes).expect("write");
|
||||
run(ff, &["-f", ffmpeg_format, "-i", input.to_str().expect("path"), out.to_str().expect("path")]);
|
||||
parse(&std::fs::read(&out).expect("read"), Format::Srt).expect("parse ffmpeg's srt")
|
||||
}
|
||||
|
||||
/// The lines of a cue's text as plain text, tags and entities gone.
|
||||
fn plain(c: &Cue) -> String {
|
||||
c.text.lines().map(|l| plain_text(l).trim().to_string()).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn we_read_what_ffmpeg_reads() {
|
||||
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
|
||||
for (format, text) in samples() {
|
||||
let (_, name, ext) = FORMATS.iter().copied().find(|f| f.0 == format).expect("format");
|
||||
let ours = parse(text.as_bytes(), format).expect("parse");
|
||||
let theirs = ffmpeg_reads(&ff, &format!("read_{name}"), name, ext, text.as_bytes());
|
||||
assert_eq!(ours.cues.len(), theirs.cues.len(), "{format:?}: {:?} against {:?}", ours.cues, theirs.cues);
|
||||
for (i, (o, t)) in ours.cues.iter().zip(&theirs.cues).enumerate() {
|
||||
// ffmpeg gives a last caption of a start-only format no end (an enormous one).
|
||||
let last = i + 1 == ours.cues.len();
|
||||
let open_ended = matches!(format, Format::VPlayer | Format::Sami) && last;
|
||||
assert!((o.start.0 - t.start.0).abs() <= MS, "{format:?} start of {:?}: {:?} against {:?}", o.text, o.start, t.start);
|
||||
if !open_ended {
|
||||
assert!((o.end.0 - t.end.0).abs() <= MS, "{format:?} end of {:?}: {:?} against {:?}", o.text, o.end, t.end);
|
||||
}
|
||||
assert_eq!(plain(o), plain(t), "{format:?} text of the cue at {:?}", o.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_document() -> Document {
|
||||
let cue = |a: i64, b: i64, text: &str| Cue { start: ms(a), end: ms(b), text: text.into(), ..Default::default() };
|
||||
Document {
|
||||
cues: vec![
|
||||
cue(1000, 3500, "Hello\n<i>second line</i>"),
|
||||
cue(3500, 5000, "straight after, with & and <"),
|
||||
cue(7000, 9000, "after a gap [br] { } |"),
|
||||
cue(3_600_000, 3_601_500, "an hour in"),
|
||||
],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_reads_what_we_write() {
|
||||
let Some(ff) = craft_media_testkit::ffmpeg() else { return };
|
||||
// ffmpeg's own readers mangle the look-alike characters a writer uses for what a format cannot hold,
|
||||
// so the cue that has those is left out here (write_then_read covers it).
|
||||
let mut doc = sample_document();
|
||||
doc.cues[2].text = "after a gap".into();
|
||||
for (format, name, ext) in FORMATS {
|
||||
let bytes = write(&doc, format, WriteOptions::default());
|
||||
let theirs = ffmpeg_reads(&ff, &format!("write_{name}"), name, ext, &bytes);
|
||||
assert_eq!(theirs.cues.len(), doc.cues.len(), "{format:?}: {:?}", String::from_utf8_lossy(&bytes));
|
||||
for (t, d) in theirs.cues.iter().zip(&doc.cues) {
|
||||
let tolerance = if format == Format::MicroDvd { 45 * MS } else { 10 * MS };
|
||||
assert!((t.start.0 - d.start.0).abs() <= tolerance, "{format:?} start of {:?}: {:?}", d.text, t.start);
|
||||
// the characters a format cannot hold are written as look-alikes: compare without them
|
||||
let bare = |c: &Cue| {
|
||||
plain(c)
|
||||
.replace('\u{ff3b}', "[")
|
||||
.replace('\u{ff3d}', "]")
|
||||
.replace("[br]", "")
|
||||
.replace(['{', '}', '|', '\u{ff5b}', '\u{ff5d}', '\u{ff5c}'], "")
|
||||
.replace(" ", " ")
|
||||
};
|
||||
assert_eq!(bare(t), bare(d), "{format:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_then_read_keeps_times_and_text() {
|
||||
let doc = sample_document();
|
||||
for (format, _, _) in FORMATS {
|
||||
let bytes = write(&doc, format, WriteOptions::default());
|
||||
let back = parse(&bytes, format).unwrap_or_else(|e| panic!("{format:?}: {e}"));
|
||||
assert_eq!(back.cues.len(), doc.cues.len(), "{format:?}");
|
||||
let tolerance = match format {
|
||||
Format::MicroDvd => 25 * MS,
|
||||
Format::Mpl2 => 50 * MS,
|
||||
_ => 5 * MS,
|
||||
};
|
||||
for (b, d) in back.cues.iter().zip(&doc.cues) {
|
||||
assert!((b.start.0 - d.start.0).abs() <= tolerance, "{format:?} start {:?} against {:?}", b.start, d.start);
|
||||
assert!((b.end.0 - d.end.0).abs() <= tolerance, "{format:?} end {:?} against {:?}", b.end, d.end);
|
||||
}
|
||||
assert_eq!(back.cues[0].text.lines().count(), 2, "{format:?} keeps the line break");
|
||||
assert_eq!(plain(&back.cues[1]), "straight after, with & and <", "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_survive_where_the_format_has_them() {
|
||||
let doc = Document {
|
||||
cues: vec![Cue { start: ms(0), end: ms(2000), text: "plain\n<i>slanted</i>".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
for format in [Format::MicroDvd, Format::Mpl2] {
|
||||
let back = parse(&write(&doc, format, WriteOptions::default()), format).expect("parse");
|
||||
assert_eq!(back.cues[0].text, "plain\n<i>slanted</i>", "{format:?}");
|
||||
}
|
||||
// SAMI keeps inline tags too.
|
||||
let doc = Document {
|
||||
cues: vec![Cue { start: ms(0), end: ms(2000), text: "a <b>bold</b> <i>and</i> <u>more</u>".into(), ..Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(parse(&write(&doc, Format::Sami, WriteOptions::default()), Format::Sami).expect("parse").cues[0].text, doc.cues[0].text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn microdvd_counts_frames_at_the_given_rate() {
|
||||
let doc = Document { cues: vec![Cue { start: Tick(2 * T), end: Tick(4 * T), text: "x".into(), ..Default::default() }], ..Default::default() };
|
||||
let bytes = write(&doc, Format::MicroDvd, WriteOptions { rate: Some(FrameRate::FPS_25), ..Default::default() });
|
||||
assert_eq!(String::from_utf8(bytes.clone()).expect("utf8"), "{1}{1}25.000\n{50}{100}x\n");
|
||||
let back = parse(&bytes, Format::MicroDvd).expect("parse");
|
||||
assert_eq!((back.cues[0].start, back.cues[0].end), (Tick(2 * T), Tick(4 * T)));
|
||||
|
||||
for header in ["{1}{1}25.000", "{0}{0}25.000"] {
|
||||
let fixture = format!("{header}\n{{50}}{{100}}First cue\n{{100}}{{150}}23.976\n");
|
||||
let parsed = parse(fixture.as_bytes(), Format::MicroDvd).expect("parse rate header fixture");
|
||||
assert_eq!(parsed.cues.len(), 2, "{header}");
|
||||
assert_eq!((parsed.cues[0].start, parsed.cues[0].end), (Tick(2 * T), Tick(4 * T)), "{header}");
|
||||
assert_eq!((parsed.cues[1].start, parsed.cues[1].end), (Tick(4 * T), Tick(6 * T)), "{header}");
|
||||
assert_eq!(parsed.cues[1].text, "23.976", "{header}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection_finds_each_format() {
|
||||
for (format, text) in samples() {
|
||||
assert_eq!(detect(text.as_bytes(), None), Some(format), "{format:?}");
|
||||
let ext = FORMATS.iter().find(|f| f.0 == format).map(|f| f.2);
|
||||
assert_eq!(detect(text.as_bytes(), ext), Some(format), "{format:?} with its extension");
|
||||
}
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nx\n", None), Some(Format::Srt));
|
||||
// Cue text containing literal SubViewer markers must not hijack SRT detection
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nHere is a [SUBTITLE] tag\n", None), Some(Format::Srt));
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n[INFORMATION] about movie\n", None), Some(Format::Srt));
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", None), Some(Format::Srt));
|
||||
assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", Some("srt")), Some(Format::Srt));
|
||||
// TTML with namespaced sami element is not SAMI
|
||||
assert_ne!(detect(b"<sami:tt xmlns:sami=\"http://www.w3.org/ns/ttml\"><head></head><body></body></sami:tt>", None), Some(Format::Sami));
|
||||
// Genuine SubViewer with only [SUBTITLE] header
|
||||
assert_eq!(detect(b"[SUBTITLE]\n00:00:01.00,00:00:02.00\nText\n", None), Some(Format::SubViewer));
|
||||
// Genuine SubViewer with long/truncated [TITLE] line
|
||||
let truncated_sv = format!("[INFORMATION]\n[TITLE]{}", "A".repeat(5000));
|
||||
assert_eq!(detect(truncated_sv.as_bytes(), None), Some(Format::SubViewer));
|
||||
assert_eq!(detect(b"just some prose\n", Some("txt")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_text_is_not_one_of_these_formats() {
|
||||
for (format, _, _) in FORMATS {
|
||||
assert!(parse(b"hello there\nthis is not a subtitle file\n", format).is_err(), "{format:?}");
|
||||
assert!(parse(b"", format).expect("empty").cues.is_empty(), "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_is_an_error_or_a_warning_never_a_panic() {
|
||||
let mut inputs: Vec<Vec<u8>> = vec![
|
||||
"{".repeat(10_000).into_bytes(),
|
||||
"{1}{1}".repeat(2000).into_bytes(),
|
||||
"{999999999}{999999999}x\n{1}{99999999999999999999}y\n{5}{3}z\n".into(),
|
||||
"[999999999][999999999]x\n[1][2".into(),
|
||||
"99999:99:99.99,99999:99:99.99\nx\n\n00:00:01.00,00:00:00.00\ny\n".into(),
|
||||
"99999999:00:00=x\n00:60:00=y\n00:00:00.=z\n".into(),
|
||||
"<sync start=".repeat(5000).into_bytes(),
|
||||
"<SAMI><SYNC Start=999999999999999999999><P>x<SYNC Start=-5>y<SYNC Start=1><<<<&&&&�&#x;".into(),
|
||||
format!("<SYNC Start=1>{}", "<font color=\"#fff\">".repeat(10_000)).into_bytes(),
|
||||
format!("<SYNC Start=1>{}", "<".repeat(10_000)).into_bytes(),
|
||||
vec![0xff, 0xfe, 0x00, 0xd8, 0x00],
|
||||
vec![0u8; 1000],
|
||||
];
|
||||
// deterministic noise
|
||||
let mut x = 0x9e37_79b9u32;
|
||||
for len in [10usize, 100, 1000] {
|
||||
let alphabet = b"{}[]<>:=,. \n|&#;0123456789abSYNC";
|
||||
let noise: Vec<u8> = (0..len)
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
alphabet[x as usize % alphabet.len()]
|
||||
})
|
||||
.collect();
|
||||
inputs.push(noise);
|
||||
}
|
||||
for (format, _, _) in FORMATS {
|
||||
for input in &inputs {
|
||||
if let Ok(doc) = parse(input, format) {
|
||||
// what was read writes and reads again
|
||||
let again = write(&doc, format, WriteOptions::default());
|
||||
parse(&again, format).expect("a written file reads back");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cue_limit_applies() {
|
||||
let mut text = String::new();
|
||||
for i in 0..200 {
|
||||
text.push_str(&format!("[{}][{}]x\n", i * 10, i * 10 + 5));
|
||||
}
|
||||
assert_eq!(parse(text.as_bytes(), Format::Mpl2).expect("parse").cues.len(), 200);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
mod ass;
|
||||
mod legacy_text;
|
||||
mod limits;
|
||||
mod literal_roundtrips;
|
||||
mod mcc_708_timing;
|
||||
|
||||
+54
-14
@@ -319,23 +319,33 @@ fn solve_cmy_by<F: Forward + ?Sized>(model: &F, k: f64, limit: f64, seeds: &[[f6
|
||||
|
||||
const SEEDS: [[f64; 3]; 5] = [[0.3, 0.3, 0.3], [0.05, 0.05, 0.05], [0.8, 0.8, 0.8], [0.9, 0.2, 0.2], [0.2, 0.9, 0.9]];
|
||||
|
||||
/// Black for a gray component `g` (the smallest of C, M, Y without black).
|
||||
/// Black for a gray component `g` (the smallest of C, M, Y without black), at most the total ink
|
||||
/// limit: the CMY solve gets `tac - k`, so black above `tac` would break the limit on its own.
|
||||
fn gcr(p: &CmykParams, g: f64) -> f64 {
|
||||
let Some(first) = p.gcr_curve.first() else {
|
||||
let k = match p.gcr_curve.first() {
|
||||
// The Photocraft profile's curve.
|
||||
return if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) };
|
||||
};
|
||||
let mut k = first[1];
|
||||
for w in p.gcr_curve.windows(2) {
|
||||
let ([g0, k0], [g1, k1]) = (w[0], w[1]);
|
||||
if g >= g1 {
|
||||
k = k1;
|
||||
} else if g > g0 {
|
||||
k = k0 + (k1 - k0) * (g - g0) / (g1 - g0);
|
||||
break;
|
||||
None => {
|
||||
if g <= p.gcr_start {
|
||||
0.0
|
||||
} else {
|
||||
p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma)
|
||||
}
|
||||
}
|
||||
}
|
||||
k.clamp(0.0, 1.0)
|
||||
Some(first) => {
|
||||
let mut k = first[1];
|
||||
for w in p.gcr_curve.windows(2) {
|
||||
let ([g0, k0], [g1, k1]) = (w[0], w[1]);
|
||||
if g >= g1 {
|
||||
k = k1;
|
||||
} else if g > g0 {
|
||||
k = k0 + (k1 - k0) * (g - g0) / (g1 - g0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
k
|
||||
}
|
||||
};
|
||||
k.clamp(0.0, 1.0).min(p.tac.max(0.0))
|
||||
}
|
||||
|
||||
/// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve.
|
||||
@@ -712,6 +722,9 @@ fn check_grids(p: &CmykParams) -> Result<(), CmsError> {
|
||||
if p.white_on_node && p.grid_b2a.is_multiple_of(2) {
|
||||
return Err(invalid_arg(format!("white on a node needs an odd BToA grid, not {}", p.grid_b2a)));
|
||||
}
|
||||
if !(p.tac.is_finite() && p.tac >= 0.0) {
|
||||
return Err(invalid_arg(format!("total ink limit {} must be finite and not negative", p.tac)));
|
||||
}
|
||||
let valid = |v: &[f64; 2]| v.iter().all(|x| (0.0..=1.0).contains(x));
|
||||
if !p.gcr_curve.iter().all(valid) || p.gcr_curve.windows(2).any(|w| w[1][0] <= w[0][0]) {
|
||||
return Err(invalid_arg(format!("black generation curve {:?} needs points in [0, 1] with increasing gray components", p.gcr_curve)));
|
||||
@@ -847,6 +860,33 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn total_ink_limit_must_be_finite_and_not_negative() {
|
||||
for tac in [-0.5, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
let p = CmykParams { grid_a2b: 2, grid_b2a: 2, tac, ..CmykParams::default() };
|
||||
assert!(cmyk_profile(&p).is_err(), "tac {tac}");
|
||||
}
|
||||
// `separate` is public and does not validate: black is still never negative.
|
||||
let p = CmykParams { tac: -0.5, gcr_curve: vec![[0.0, 0.75]], ..CmykParams::default() };
|
||||
assert_eq!(gcr(&p, 0.5), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curve_black_stays_within_the_ink_limit() {
|
||||
// Black from either the profile curve or the default empty-curve fallback never exceeds the ink limit.
|
||||
let m = CmykModel::coated(CmykParams::default().tvi);
|
||||
for gcr_curve in [vec![[0.0, 0.75]], vec![]] {
|
||||
for tac in [0.5, 0.0] {
|
||||
let p = CmykParams { tac, gcr_curve: gcr_curve.clone(), ..CmykParams::default() };
|
||||
assert!(gcr(&p, 1.0) <= p.tac, "tac {tac} curve {gcr_curve:?}");
|
||||
for target in [[50.0, 0.0, 0.0], [90.0, 0.0, 0.0], [30.0, 20.0, -10.0]] {
|
||||
let (cmyk, _) = separate(&m, &p, target, None);
|
||||
assert!(cmyk.iter().sum::<f64>() <= p.tac + 1e-6, "{target:?} -> {cmyk:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oklab_round_trips() {
|
||||
let m = CmykModel::coated(CmykParams::default().tvi);
|
||||
|
||||
@@ -430,6 +430,8 @@ fn separates_like_the_reference_application() {
|
||||
for (rgb, want) in REFERENCE_SEPARATIONS {
|
||||
for ((intent, bpc), want) in SEPARATION_INTENTS.into_iter().zip(want) {
|
||||
let got = separation(intent, bpc, rgb);
|
||||
// `f32::max` drops a NaN, so a NaN ink would otherwise count as no difference.
|
||||
assert!(got.iter().all(|v| v.is_finite()), "{rgb:?} {intent:?} bpc {bpc}: {got:?}");
|
||||
let diff = (0..4).map(|i| (got[i] - want[i]).abs()).fold(0.0f32, f32::max);
|
||||
eprintln!("{rgb:?} {intent:?} bpc {bpc}: {got:.1?} reference {want:?} (max {diff:.1})");
|
||||
worst = worst.max(diff);
|
||||
|
||||
@@ -38,6 +38,10 @@ log = { workspace = true, optional = true }
|
||||
proptest = { workspace = true }
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
# Reserve an unused control port without opening a listener, including between assertions.
|
||||
socket2 = "0.6.5"
|
||||
|
||||
[[test]]
|
||||
name = "agents"
|
||||
required-features = ["agents"]
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::*;
|
||||
use crate::ControlRequest;
|
||||
use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits};
|
||||
use socket2::{Domain, Socket, Type};
|
||||
use std::ffi::OsString;
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
@@ -78,9 +79,14 @@ fn addr(port: u16) -> String {
|
||||
format!("127.0.0.1:{port}")
|
||||
}
|
||||
|
||||
/// A port nothing listens on.
|
||||
fn free_port() -> u16 {
|
||||
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
/// Keep this port bound without listening, so another normal test listener cannot take it.
|
||||
fn reserve_non_listening_port() -> (Socket, u16) {
|
||||
let reserved = Socket::new(Domain::IPV4, Type::STREAM, Some(socket2::Protocol::TCP)).unwrap();
|
||||
let address = std::net::SocketAddr::from(([127, 0, 0, 1], 0));
|
||||
reserved.bind(&address.into()).unwrap();
|
||||
let port = reserved.local_addr().unwrap().as_socket().unwrap().port();
|
||||
assert_ne!(port, 0);
|
||||
(reserved, port)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -115,13 +121,22 @@ fn a_wrong_token_or_none_is_refused() {
|
||||
|
||||
#[test]
|
||||
fn an_app_not_running_says_how_to_start_it() {
|
||||
let port = free_port();
|
||||
let (reserved, port) = reserve_non_listening_port();
|
||||
let mut c = Connection::new(APP, &addr(port), Some(TOKEN));
|
||||
let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err();
|
||||
let CallError::NotRunning(m) = &e else { panic!("{e:?}") };
|
||||
assert!(m.starts_with(&format!("no Probe app is listening at 127.0.0.1:{port}")), "{m}");
|
||||
assert!(m.contains(&format!("`probe --control {port}`")), "{m}");
|
||||
assert_eq!(c.try_connect().unwrap_err().kind(), std::io::ErrorKind::NotConnected);
|
||||
drop(reserved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_not_running_fixture_keeps_its_port_from_another_listener() {
|
||||
let (reserved, port) = reserve_non_listening_port();
|
||||
let rival = TcpListener::bind(("127.0.0.1", port));
|
||||
assert!(rival.is_err(), "another listener acquired the reserved port");
|
||||
drop(reserved);
|
||||
}
|
||||
|
||||
/// An app that goes away during a call is lost, not "not running"; the next call says it is not
|
||||
|
||||
@@ -353,6 +353,7 @@ audio-qoa = ["audio", "craft-audio/qoa"]
|
||||
audio-qoa-decode = ["audio", "craft-audio/qoa-decode"]
|
||||
audio-qoa-encode = ["audio", "craft-audio/qoa-encode"]
|
||||
audio-rayon = ["audio", "craft-audio/rayon"]
|
||||
audio-s302m = ["audio", "craft-audio/s302m"]
|
||||
audio-sbc = ["audio", "craft-audio/sbc"]
|
||||
audio-serde = ["audio", "craft-audio/serde"]
|
||||
audio-symphonia = ["audio", "craft-audio/symphonia"]
|
||||
@@ -636,6 +637,7 @@ mcp-server = ["dep:craft-mcp-server"]
|
||||
|
||||
media = ["dep:craft-media"]
|
||||
media-avi = ["media", "craft-media/avi"]
|
||||
media-bink = ["media", "craft-media/bink"]
|
||||
media-bitstream = ["media", "craft-media/bitstream"]
|
||||
media-isobmff = ["media", "craft-media/isobmff"]
|
||||
media-matroska = ["media", "craft-media/matroska"]
|
||||
@@ -974,6 +976,8 @@ video-av1 = ["video", "craft-video/av1"]
|
||||
video-av1-decode = ["video", "craft-video/av1-decode"]
|
||||
video-av1-encode = ["video", "craft-video/av1-encode"]
|
||||
video-av1-large-encode = ["video", "craft-video/av1-large-encode"]
|
||||
video-bink = ["video", "craft-video/bink"]
|
||||
video-bink-decode = ["video", "craft-video/bink-decode"]
|
||||
video-dnx = ["video", "craft-video/dnx"]
|
||||
video-ffv1 = ["video", "craft-video/ffv1"]
|
||||
video-h264 = ["video", "craft-video/h264"]
|
||||
@@ -990,7 +994,11 @@ video-mpeg2-encode = ["video", "craft-video/mpeg2-encode"]
|
||||
video-mpeg4 = ["video", "craft-video/mpeg4"]
|
||||
video-mpeg4-encode = ["video", "craft-video/mpeg4-encode"]
|
||||
video-prores = ["video", "craft-video/prores"]
|
||||
video-rawvideo = ["video", "craft-video/rawvideo"]
|
||||
video-screen-video = ["video", "craft-video/screen-video"]
|
||||
video-theora = ["video", "craft-video/theora"]
|
||||
video-theora-decode = ["video", "craft-video/theora-decode"]
|
||||
video-theora-encode = ["video", "craft-video/theora-encode"]
|
||||
video-threads = ["video", "craft-video/threads"]
|
||||
video-vmd = ["video", "craft-video/vmd"]
|
||||
video-vmd-decode = ["video", "craft-video/vmd-decode"]
|
||||
|
||||
@@ -11,7 +11,8 @@ mapping a SYLK sheet onto a document are the caller's work.
|
||||
| Function | What it does |
|
||||
|---|---|
|
||||
| `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 |
|
||||
| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
|
||||
| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters (empty or whitespace-only quoted records are blank); when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
|
||||
| `sniff_csv_delimiter(text, quote)` | same scan as `sniff_delimiter`, but for `.csv`-named text prefers comma when comma coherently separates every sampled record with text; when no candidate coherently separates every sampled record, falls back to a coherent candidate whose header and at least one later record share a positive delimiter count with strictly more than half of the sampled records having 1 to that many delimiters (preferring comma, then tab over semicolon), or else comma if comma coherently separates the first sampled record with text |
|
||||
| `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text |
|
||||
| `records(text, delim, quote, max_records, max_fields)` | the same, collected |
|
||||
| `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing |
|
||||
|
||||
+162
-6
@@ -4,7 +4,8 @@
|
||||
//! - [`decode_text`] turns a file's bytes into a string: byte order marks, UTF-8, else
|
||||
//! Windows-1256 when the bytes read as Arabic and Windows-1252 otherwise.
|
||||
//! - [`decode_utf8`] requires valid UTF-8 and strips a leading UTF-8 byte order mark.
|
||||
//! - [`sniff_delimiter`] picks comma, semicolon or tab.
|
||||
//! - [`sniff_delimiter`] picks comma, semicolon or tab; [`sniff_csv_delimiter`] applies the same
|
||||
//! scan while preferring comma when it coherently separates `.csv` records.
|
||||
//! - [`parse_records`] splits text into records of fields (RFC 4180 with the usual leniency),
|
||||
//! handing each record to a callback, with a cap on the fields kept per record. [`records`]
|
||||
//! collects them.
|
||||
@@ -45,14 +46,35 @@ pub use decode::{decode_text, decode_utf8};
|
||||
/// with one. When one of those candidates ends the sample inside a quoted field, each of them
|
||||
/// counts only up to that field's opening quote.
|
||||
pub fn sniff_delimiter(text: &str, quote: char) -> u8 {
|
||||
sniff_delimiter_inner(text, quote, false)
|
||||
}
|
||||
|
||||
/// Picks comma, semicolon or tab for `.csv`-named text, preferring comma when it coherently
|
||||
/// separates the sampled records.
|
||||
///
|
||||
/// Uses the same bounded character sample, quote-boundary coherence rules and fallback ranking
|
||||
/// as [`sniff_delimiter`], with two `.csv`-specific rules:
|
||||
/// - When comma has coherent quoted fields and separates every sampled record with text, comma
|
||||
/// wins even if tab or semicolon also separates them.
|
||||
/// - When no candidate coherently separates every sampled record with text, a coherent candidate
|
||||
/// whose first record and at least one later record share the same positive delimiter count
|
||||
/// (and where strictly more than half of the sampled records with text contain between one and
|
||||
/// that many delimiters) is chosen — preferring comma, then the most matching records, higher
|
||||
/// header count and total, then tab over semicolon. If none matches, comma still wins when it
|
||||
/// has coherent quoted fields and separates the first sampled record with text.
|
||||
pub fn sniff_csv_delimiter(text: &str, quote: char) -> u8 {
|
||||
sniff_delimiter_inner(text, quote, true)
|
||||
}
|
||||
|
||||
fn sniff_delimiter_inner(text: &str, quote: char, prefer_comma: bool) -> u8 {
|
||||
const SAMPLE_CHARS: usize = 64 * 1024;
|
||||
let sample_end = text.char_indices().nth(SAMPLE_CHARS).map_or(text.len(), |(at, _)| at);
|
||||
let sample = &text[..sample_end];
|
||||
let truncated = sample_end < text.len();
|
||||
let mut scans = b"\t,;".map(|delimiter| scan_delimiter(sample, delimiter, quote));
|
||||
if truncated {
|
||||
if scans.iter().any(|scan| scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0)) {
|
||||
return pick_delimiter(scans);
|
||||
if scans.iter().any(separates_coherently) {
|
||||
return pick_delimiter(scans, prefer_comma);
|
||||
}
|
||||
// Every quote in the scans is at a char boundary, so the cut is one too.
|
||||
let cut = scans.iter().filter(|scan| scan.counts.is_empty()).filter_map(|scan| scan.open_quote).min().unwrap_or(sample_end);
|
||||
@@ -93,10 +115,60 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 {
|
||||
}
|
||||
}
|
||||
}
|
||||
pick_delimiter(scans)
|
||||
pick_delimiter(scans, prefer_comma)
|
||||
}
|
||||
|
||||
fn pick_delimiter(scans: [DelimiterScan; 3]) -> u8 {
|
||||
fn separates_coherently(scan: &DelimiterScan) -> bool {
|
||||
scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0)
|
||||
}
|
||||
|
||||
/// Scores a coherent candidate whose first record and at least one later record share the same
|
||||
/// positive delimiter count, and where strictly more than half of the sampled records with text
|
||||
/// contain between one and that many delimiters (allowing occasional short rows).
|
||||
fn header_short_row_score(scan: &DelimiterScan) -> Option<(usize, usize, usize)> {
|
||||
if !scan.coherent {
|
||||
return None;
|
||||
}
|
||||
let &header = scan.counts.first()?;
|
||||
if header == 0 {
|
||||
return None;
|
||||
}
|
||||
let exact_matches = scan.counts.iter().filter(|&&count| count == header).count();
|
||||
let in_range = scan.counts.iter().filter(|&&count| (1..=header).contains(&count)).count();
|
||||
if exact_matches < 2 || in_range * 2 <= scan.counts.len() {
|
||||
return None;
|
||||
}
|
||||
Some((exact_matches, header, scan.counts.iter().sum()))
|
||||
}
|
||||
|
||||
fn pick_csv_delimiter(scans: &[DelimiterScan; 3]) -> Option<u8> {
|
||||
let [tab, comma, semi] = scans;
|
||||
if separates_coherently(comma) {
|
||||
return Some(b',');
|
||||
}
|
||||
if separates_coherently(tab) || separates_coherently(semi) {
|
||||
return None;
|
||||
}
|
||||
if header_short_row_score(comma).is_some() {
|
||||
return Some(b',');
|
||||
}
|
||||
if let Some((delimiter, _)) = [tab, semi]
|
||||
.into_iter()
|
||||
.filter_map(|scan| header_short_row_score(scan).map(|score| (scan.delimiter, score)))
|
||||
.reduce(|best, candidate| if candidate.1 > best.1 { candidate } else { best })
|
||||
{
|
||||
return Some(delimiter);
|
||||
}
|
||||
if comma.coherent && comma.counts.first().is_some_and(|&first| first > 0) {
|
||||
return Some(b',');
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn pick_delimiter(scans: [DelimiterScan; 3], prefer_comma: bool) -> u8 {
|
||||
if prefer_comma && let Some(delimiter) = pick_csv_delimiter(&scans) {
|
||||
return delimiter;
|
||||
}
|
||||
let with_text = scans.each_ref().map(|scan| (scan.delimiter, scan.counts.as_slice(), scan.coherent));
|
||||
// Records of delimiters alone have no quotes, so they are coherent.
|
||||
let delimiters_only =
|
||||
@@ -205,7 +277,6 @@ fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan {
|
||||
if ch == quote && field_start {
|
||||
scan.open_quote = Some(at);
|
||||
field_start = false;
|
||||
scan.record_has_content = true;
|
||||
} else if ch == char::from(delimiter) {
|
||||
scan.count += 1;
|
||||
field_start = true;
|
||||
@@ -505,6 +576,91 @@ mod tests {
|
||||
assert_eq!(sniff_delimiter(&format!("{}x;y\n", ",,,\n".repeat(20_000)), '"'), b',');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delimiter_sniffing_ignores_empty_quoted_records() {
|
||||
assert_eq!(sniff_delimiter("\"\"\nName\tCity\nAda\tLondon\n", '"'), b'\t');
|
||||
assert_eq!(sniff_delimiter("\"\"\nName;City\nAda;London\n", '"'), b';');
|
||||
assert_eq!(sniff_delimiter("\" \"\nName\tCity\nAda\tLondon\n", '"'), b'\t');
|
||||
// Quoted empty cells separated by a delimiter still act as delimiter-only rows.
|
||||
assert_eq!(sniff_delimiter("\"\";\"\"\n\"\";\"\"\n", '"'), b';');
|
||||
// A doubled quote inside a quoted field is content, not a blank line.
|
||||
assert_eq!(sniff_delimiter("\"\"\"\"\nName\tCity\nAda\tLondon\n", '"'), b',');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_delimiter_sniffing_prefers_coherent_comma_and_detects_tab_and_semicolon() {
|
||||
// Coherent comma separation wins even when semicolons or tabs appear in fields.
|
||||
for text in [
|
||||
"id,notes; comments\n1,a; b; c\n2,d; e; f\n",
|
||||
"Ort,\"Name;Vorname\"\nBerlin,\"a;b;c\"\n",
|
||||
"\"Name\",\"Last; First\"\n\"Ada\",\"Lovelace; Countess\"\n",
|
||||
"Name,Note\tx\nAda,hi\tthere\n",
|
||||
"\"Name\tLabel\",City\nAda,London\n",
|
||||
"\"\"\nName;Team;Role,Email\nAda;Core;Eng,ada@example.com\n",
|
||||
// A short comma row does not fall back to an incoherent semicolon parse.
|
||||
"\"Name\",\"Note;Tag\"\nAda;Team\nGrace,Hello;2\n",
|
||||
// Single-column exports with stray separators fall back to comma.
|
||||
"alpha;beta\r\ngamma\r\n",
|
||||
"alpha\tbeta\r\ngamma\r\n",
|
||||
] {
|
||||
assert_eq!(sniff_csv_delimiter(text, '"'), b',', "{text:?}");
|
||||
}
|
||||
|
||||
// Tab- and semicolon-delimited CSVs (including headers containing commas) sniff cleanly.
|
||||
for (text, expected) in [
|
||||
("Name\tPosition\tOrt\nAda\tLead\tBerlin\n", b'\t'),
|
||||
("Name;City\nAda;London\n", b';'),
|
||||
("\"Name, First\"\tOrt\nAda\tBerlin\n", b'\t'),
|
||||
("\"Name\";\"Last, First\"\n\"Ada\";\"Lovelace, Countess\"\n", b';'),
|
||||
("\"Name\"\t\"Last, First\"\n\"Ada\"\t\"Lovelace, Countess\"\n", b'\t'),
|
||||
("Last, First\tEmail\tCity\nAda Lovelace\tada@example.com\tLondon\n", b'\t'),
|
||||
("Last, First;Email;City\nAda Lovelace;ada@example.com;London\n", b';'),
|
||||
("\"\"\nName\tCity\nAda\tLondon\n", b'\t'),
|
||||
("\"\"\nName;City\nAda;London\n", b';'),
|
||||
] {
|
||||
assert_eq!(sniff_csv_delimiter(text, '"'), expected, "{text:?}");
|
||||
}
|
||||
|
||||
let blank_tab_rows = format!("{}a;b\nc;d\n", "\t \t\n".repeat(25));
|
||||
assert_eq!(sniff_csv_delimiter(&blank_tab_rows, '"'), b';');
|
||||
assert_eq!(sniff_csv_delimiter(&format!("{};7\n", ";\n".repeat(40_000)), '"'), b';');
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_delimiter_sniffing_handles_short_rows_conservatively() {
|
||||
// Tab- and semicolon-delimited CSVs with a short row recover when the header and a later
|
||||
// full row agree across a majority of sampled records.
|
||||
for (text, expected) in [
|
||||
("Name\tCity\nAda\nGrace\tParis\n", b'\t'),
|
||||
("Name;City\nAda\nGrace;Paris\n", b';'),
|
||||
("Name\tCity\tRole\nAda\nGrace\tParis\tLead\n", b'\t'),
|
||||
("Name;City;Role\nAda\nGrace;Paris;Lead\n", b';'),
|
||||
("Name\tCity\nAda\tLondon\nGrace\n", b'\t'),
|
||||
("Name;City\nAda;London\nGrace\n", b';'),
|
||||
("Last, First\tCity\nAda\nGrace\tParis\n", b'\t'),
|
||||
("Last, First;City\nAda\nGrace;Paris\n", b';'),
|
||||
("\"\"\nName\tCity\nAda\nGrace\tParis\n", b'\t'),
|
||||
("\"Name\"\t\"City;Region\"\nAda;X\nGrace\tParis;Y\n", b'\t'),
|
||||
] {
|
||||
assert_eq!(sniff_csv_delimiter(text, '"'), expected, "{text:?}");
|
||||
}
|
||||
|
||||
// Comma preference and conservative single-column fallbacks stay comma.
|
||||
for text in [
|
||||
"Name,Note;Tag\nAda\nGrace,Hello;2\n",
|
||||
"Name,Note\tTag\nAda\nGrace,Hello\t2\n",
|
||||
"\"Name\",\"Note;Tag\"\nAda;Team\n",
|
||||
"alpha;beta\r\ngamma\r\n",
|
||||
"alpha\tbeta\r\ngamma\r\n",
|
||||
"alpha;beta\r\ngamma\r\ndelta\r\n",
|
||||
"Notes\r\nalpha;beta\r\ngamma;delta\r\n",
|
||||
"a;b\nc\nd\ne;f\n",
|
||||
"Title: a;b\nline\nx;y;z\nline\nc;d\n",
|
||||
] {
|
||||
assert_eq!(sniff_csv_delimiter(text, '"'), b',', "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_stops_collecting_fields_at_the_cap() {
|
||||
let (max, extra) = (16_384usize, 50);
|
||||
|
||||
@@ -186,7 +186,7 @@ application's renderer and is ignored: the photo keeps LightCraft's own process,
|
||||
| `DefringePurple/GreenAmount/HueLo/HueHi` | `optics.defringe_*` | |
|
||||
| `ShadowTint`, `RedHue/Saturation`, `GreenHue/Saturation`, `BlueHue/Saturation` | `calibration.shadows_tint`, `calibration.red_hue/red_sat`, … | Calibration panel, 1:1 |
|
||||
| `PerspectiveVertical/Horizontal/Rotate/Scale/Aspect/X/Y` | `geometry.vertical/horizontal/rotate/scale/aspect/offset_x/offset_y` | |
|
||||
| `PerspectiveUpright` | `geometry.upright` | 0 off, 1 auto, 2 level, 3 vertical, 4 full, 5 guided; saved `UprightTransform_*` matrices are not imported, so photo import reports that Lightroom geometry was not preserved and the selected mode will be recalculated |
|
||||
| `PerspectiveUpright` | `geometry.upright` | 0 off, 1 auto, 2 full, 3 level, 4 vertical, 5 guided; saved `UprightTransform_*` matrices are not imported, so photo import reports that Lightroom geometry was not preserved and the selected mode will be recalculated |
|
||||
| `HasCrop`, `CropLeft/Top/Right/Bottom`, `CropAngle` | `crop.geometry` | normalized edges → rect; angle in degrees; `HasCrop="False"` → no crop |
|
||||
|
||||
Values pass through our control specs, so anything outside our slider ranges gets clamped.
|
||||
|
||||
@@ -414,11 +414,13 @@ pub fn to_partial(props: &Props, target: Target) -> Value {
|
||||
n(o, "PerspectiveX", "geometry.offset_x");
|
||||
n(o, "PerspectiveY", "geometry.offset_y");
|
||||
if let Some(u) = num(props, "crs:PerspectiveUpright") {
|
||||
// 0 Off, 1 Auto, 2 Full, 3 Level, 4 Vertical, 5 Guided: Lightroom saves one Upright matrix per
|
||||
// value, and each has that mode's shape (lightcraft#205)
|
||||
let mode = match u as i64 {
|
||||
1 => "auto",
|
||||
2 => "level",
|
||||
3 => "vertical",
|
||||
4 => "full",
|
||||
2 => "full",
|
||||
3 => "level",
|
||||
4 => "vertical",
|
||||
5 => "guided",
|
||||
_ => "off",
|
||||
};
|
||||
|
||||
@@ -79,7 +79,7 @@ fn assert_common_detail_fields(s: &DevelopSettings) {
|
||||
}
|
||||
|
||||
fn assert_common_geometry_fields(s: &DevelopSettings) {
|
||||
assert_eq!(s.geometry.upright, Upright::Level);
|
||||
assert_eq!(s.geometry.upright, Upright::Full);
|
||||
assert_eq!(s.geometry.vertical, -10.0);
|
||||
assert!(s.optics.remove_ca);
|
||||
assert_eq!(s.treatment, crate::Treatment::Color);
|
||||
@@ -92,6 +92,19 @@ fn assert_common_geometry_fields(s: &DevelopSettings) {
|
||||
assert_eq!((c.rect.x0, c.rect.y0, c.rect.x1, c.rect.y1, c.angle), (0.05, 0.1, 0.8, 0.9, 1.5));
|
||||
}
|
||||
|
||||
/// `crs:PerspectiveUpright` 2, 3 and 4 name Full, Level and Vertical, in that order.
|
||||
#[test]
|
||||
fn upright_mode_numbers_name_full_level_and_vertical() {
|
||||
for (value, mode) in [(2, Upright::Full), (3, Upright::Level), (4, Upright::Vertical)] {
|
||||
let xmp = format!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:PerspectiveUpright="{value}"/></rdf:RDF></x:xmpmeta>"#
|
||||
);
|
||||
let partial = to_partial(&props(&xmp), Target::Any);
|
||||
let s = apply_partial(&DevelopSettings::default(), &partial, 1.0);
|
||||
assert_eq!(s.geometry.upright, mode, "crs:PerspectiveUpright={value}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A sidecar curve with a `NaN` or `inf` point (Rust's `parse` reads both) is not a curve:
|
||||
/// it is left out, rather than stored with a point the curve editor can't place.
|
||||
#[test]
|
||||
|
||||
@@ -32,6 +32,9 @@ pub(crate) struct StandardFonts {
|
||||
pub(crate) bidi: Option<u16>,
|
||||
}
|
||||
|
||||
/// `sti` of no style ([MS-DOC] `StdfBase`): read when the record is too short for one.
|
||||
const STI_NIL: u16 = 0x0FFF;
|
||||
|
||||
/// `StshiLsd.cbLSD`: the size of a latent style's `LSD` ([MS-DOC] `StshiLsd`).
|
||||
const LSD_SIZE: u16 = 4;
|
||||
|
||||
@@ -55,6 +58,287 @@ pub(crate) fn standard_fonts(table: &[u8], fc: u32, lcb: u32) -> StandardFonts {
|
||||
StandardFonts { ascii: at(12), east_asian: at(14), other: at(16), bidi }
|
||||
}
|
||||
|
||||
/// The names of Word's built-in styles by `sti`: the "Index within built-in styles" of the
|
||||
/// reserved style names in [MS-OE376] (Part 4 §2.7.3.9, 0–266), which [MS-DOC]'s `StdfBase` says
|
||||
/// `sti` is. Spelled as that table spells them.
|
||||
const BUILT_IN_NAMES: [&str; 267] = [
|
||||
"Normal",
|
||||
"heading 1",
|
||||
"heading 2",
|
||||
"heading 3",
|
||||
"heading 4",
|
||||
"heading 5",
|
||||
"heading 6",
|
||||
"heading 7",
|
||||
"heading 8",
|
||||
"heading 9",
|
||||
"index 1",
|
||||
"index 2",
|
||||
"index 3",
|
||||
"index 4",
|
||||
"index 5",
|
||||
"index 6",
|
||||
"index 7",
|
||||
"index 8",
|
||||
"index 9",
|
||||
"toc 1",
|
||||
"toc 2",
|
||||
"toc 3",
|
||||
"toc 4",
|
||||
"toc 5",
|
||||
"toc 6",
|
||||
"toc 7",
|
||||
"toc 8",
|
||||
"toc 9",
|
||||
"Normal Indent",
|
||||
"footnote text",
|
||||
"annotation text",
|
||||
"header",
|
||||
"footer",
|
||||
"index heading",
|
||||
"caption",
|
||||
"table of figures",
|
||||
"envelope address",
|
||||
"envelope return",
|
||||
"footnote reference",
|
||||
"annotation reference",
|
||||
"line number",
|
||||
"page number",
|
||||
"endnote reference",
|
||||
"endnote text",
|
||||
"table of authorities",
|
||||
"macro",
|
||||
"toa heading",
|
||||
"List",
|
||||
"List Bullet",
|
||||
"List Number",
|
||||
"List 2",
|
||||
"List 3",
|
||||
"List 4",
|
||||
"List 5",
|
||||
"List Bullet 2",
|
||||
"List Bullet 3",
|
||||
"List Bullet 4",
|
||||
"List Bullet 5",
|
||||
"List Number 2",
|
||||
"List Number 3",
|
||||
"List Number 4",
|
||||
"List Number 5",
|
||||
"Title",
|
||||
"Closing",
|
||||
"Signature",
|
||||
"Default Paragraph Font",
|
||||
"Body Text",
|
||||
"Body Text Indent",
|
||||
"List Continue",
|
||||
"List Continue 2",
|
||||
"List Continue 3",
|
||||
"List Continue 4",
|
||||
"List Continue 5",
|
||||
"Message Header",
|
||||
"Subtitle",
|
||||
"Salutation",
|
||||
"Date",
|
||||
"Body Text First Indent",
|
||||
"Body Text First Indent 2",
|
||||
"Note Heading",
|
||||
"Body Text 2",
|
||||
"Body Text 3",
|
||||
"Body Text Indent 2",
|
||||
"Body Text Indent 3",
|
||||
"Block Text",
|
||||
"Hyperlink",
|
||||
"FollowedHyperlink",
|
||||
"Strong",
|
||||
"Emphasis",
|
||||
"Document Map",
|
||||
"Plain Text",
|
||||
"E-mail Signature",
|
||||
"HTML Top of Form",
|
||||
"HTML Bottom of Form",
|
||||
"Normal (Web)",
|
||||
"HTML Acronym",
|
||||
"HTML Address",
|
||||
"HTML Cite",
|
||||
"HTML Code",
|
||||
"HTML Definition",
|
||||
"HTML Keyboard",
|
||||
"HTML Preformatted",
|
||||
"HTML Sample",
|
||||
"HTML Typewriter",
|
||||
"HTML Variable",
|
||||
"Normal Table",
|
||||
"annotation subject",
|
||||
"No List",
|
||||
"Outline List 1",
|
||||
"Outline List 2",
|
||||
"Outline List 3",
|
||||
"Table Simple 1",
|
||||
"Table Simple 2",
|
||||
"Table Simple 3",
|
||||
"Table Classic 1",
|
||||
"Table Classic 2",
|
||||
"Table Classic 3",
|
||||
"Table Classic 4",
|
||||
"Table Colorful 1",
|
||||
"Table Colorful 2",
|
||||
"Table Colorful 3",
|
||||
"Table Columns 1",
|
||||
"Table Columns 2",
|
||||
"Table Columns 3",
|
||||
"Table Columns 4",
|
||||
"Table Columns 5",
|
||||
"Table Grid 1",
|
||||
"Table Grid 2",
|
||||
"Table Grid 3",
|
||||
"Table Grid 4",
|
||||
"Table Grid 5",
|
||||
"Table Grid 6",
|
||||
"Table Grid 7",
|
||||
"Table Grid 8",
|
||||
"Table List 1",
|
||||
"Table List 2",
|
||||
"Table List 3",
|
||||
"Table List 4",
|
||||
"Table List 5",
|
||||
"Table List 6",
|
||||
"Table List 7",
|
||||
"Table List 8",
|
||||
"Table 3D effects 1",
|
||||
"Table 3D effects 2",
|
||||
"Table 3D effects 3",
|
||||
"Table Contemporary",
|
||||
"Table Elegant",
|
||||
"Table Professional",
|
||||
"Table Subtle 1",
|
||||
"Table Subtle 2",
|
||||
"Table Web 1",
|
||||
"Table Web 2",
|
||||
"Table Web 3",
|
||||
"Balloon Text",
|
||||
"Table Grid",
|
||||
"Table Theme",
|
||||
"Placeholder Text",
|
||||
"No Spacing",
|
||||
"Light Shading",
|
||||
"Light List",
|
||||
"Light Grid",
|
||||
"Medium Shading 1",
|
||||
"Medium Shading 2",
|
||||
"Medium List 1",
|
||||
"Medium List 2",
|
||||
"Medium Grid 1",
|
||||
"Medium Grid 2",
|
||||
"Medium Grid 3",
|
||||
"Dark List",
|
||||
"Colorful Shading",
|
||||
"Colorful List",
|
||||
"Colorful Grid",
|
||||
"Light Shading Accent 1",
|
||||
"Light List Accent 1",
|
||||
"Light Grid Accent 1",
|
||||
"Medium Shading 1 Accent 1",
|
||||
"Medium Shading 2 Accent 1",
|
||||
"Medium List 1 Accent 1",
|
||||
"Revision",
|
||||
"List Paragraph",
|
||||
"Quote",
|
||||
"Intense Quote",
|
||||
"Medium List 2 Accent 1",
|
||||
"Medium Grid 1 Accent 1",
|
||||
"Medium Grid 2 Accent 1",
|
||||
"Medium Grid 3 Accent 1",
|
||||
"Dark List Accent 1",
|
||||
"Colorful Shading Accent 1",
|
||||
"Colorful List Accent 1",
|
||||
"Colorful Grid Accent 1",
|
||||
"Light Shading Accent 2",
|
||||
"Light List Accent 2",
|
||||
"Light Grid Accent 2",
|
||||
"Medium Shading 1 Accent 2",
|
||||
"Medium Shading 2 Accent 2",
|
||||
"Medium List 1 Accent 2",
|
||||
"Medium List 2 Accent 2",
|
||||
"Medium Grid 1 Accent 2",
|
||||
"Medium Grid 2 Accent 2",
|
||||
"Medium Grid 3 Accent 2",
|
||||
"Dark List Accent 2",
|
||||
"Colorful Shading Accent 2",
|
||||
"Colorful List Accent 2",
|
||||
"Colorful Grid Accent 2",
|
||||
"Light Shading Accent 3",
|
||||
"Light List Accent 3",
|
||||
"Light Grid Accent 3",
|
||||
"Medium Shading 1 Accent 3",
|
||||
"Medium Shading 2 Accent 3",
|
||||
"Medium List 1 Accent 3",
|
||||
"Medium List 2 Accent 3",
|
||||
"Medium Grid 1 Accent 3",
|
||||
"Medium Grid 2 Accent 3",
|
||||
"Medium Grid 3 Accent 3",
|
||||
"Dark List Accent 3",
|
||||
"Colorful Shading Accent 3",
|
||||
"Colorful List Accent 3",
|
||||
"Colorful Grid Accent 3",
|
||||
"Light Shading Accent 4",
|
||||
"Light List Accent 4",
|
||||
"Light Grid Accent 4",
|
||||
"Medium Shading 1 Accent 4",
|
||||
"Medium Shading 2 Accent 4",
|
||||
"Medium List 1 Accent 4",
|
||||
"Medium List 2 Accent 4",
|
||||
"Medium Grid 1 Accent 4",
|
||||
"Medium Grid 2 Accent 4",
|
||||
"Medium Grid 3 Accent 4",
|
||||
"Dark List Accent 4",
|
||||
"Colorful Shading Accent 4",
|
||||
"Colorful List Accent 4",
|
||||
"Colorful Grid Accent 4",
|
||||
"Light Shading Accent 5",
|
||||
"Light List Accent 5",
|
||||
"Light Grid Accent 5",
|
||||
"Medium Shading 1 Accent 5",
|
||||
"Medium Shading 2 Accent 5",
|
||||
"Medium List 1 Accent 5",
|
||||
"Medium List 2 Accent 5",
|
||||
"Medium Grid 1 Accent 5",
|
||||
"Medium Grid 2 Accent 5",
|
||||
"Medium Grid 3 Accent 5",
|
||||
"Dark List Accent 5",
|
||||
"Colorful Shading Accent 5",
|
||||
"Colorful List Accent 5",
|
||||
"Colorful Grid Accent 5",
|
||||
"Light Shading Accent 6",
|
||||
"Light List Accent 6",
|
||||
"Light Grid Accent 6",
|
||||
"Medium Shading 1 Accent 6",
|
||||
"Medium Shading 2 Accent 6",
|
||||
"Medium List 1 Accent 6",
|
||||
"Medium List 2 Accent 6",
|
||||
"Medium Grid 1 Accent 6",
|
||||
"Medium Grid 2 Accent 6",
|
||||
"Medium Grid 3 Accent 6",
|
||||
"Dark List Accent 6",
|
||||
"Colorful Shading Accent 6",
|
||||
"Colorful List Accent 6",
|
||||
"Colorful Grid Accent 6",
|
||||
"Subtle Emphasis",
|
||||
"Intense Emphasis",
|
||||
"Subtle Reference",
|
||||
"Intense Reference",
|
||||
"Book Title",
|
||||
"Bibliography",
|
||||
"TOC Heading",
|
||||
];
|
||||
|
||||
/// The built-in name of a style whose `sti` is `sti`. Word names a built-in style by its `sti`,
|
||||
/// whatever name the file stores (a non-English Word stores "Обычный" or "Kop 1"): `None` for a
|
||||
/// user-defined style (0x0FFE), the null 0x0FFF, and anything else past the table, which keep the
|
||||
/// stored name.
|
||||
pub(crate) fn built_in_name(sti: u16) -> Option<&'static str> {
|
||||
BUILT_IN_NAMES.get(usize::from(sti)).copied()
|
||||
}
|
||||
|
||||
/// Parse the `STSH` at `table[fc..fc+lcb]`.
|
||||
pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result<Vec<RawStyle>, DocbinError> {
|
||||
let fc = fc as usize;
|
||||
@@ -95,6 +379,7 @@ pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result<Vec<RawStyle>, Do
|
||||
// StdfBase ([MS-DOC] §2.9.260, 10 bytes): sti(12)+flags(4); stk(4)+istdBase(12);
|
||||
// cupx(4)+istdNext(12); bchUpe(16) (= cbStd); grfstd(16). istdBase is a zero-based
|
||||
// index into the stylesheet, 0x0FFF meaning "no parent".
|
||||
let sti = stdf.get(0..2).map_or(STI_NIL, |b| u16::from_le_bytes([b[0], b[1]]) & 0x0FFF);
|
||||
let stk = (stdf.get(2).copied().unwrap_or(1) & 0x0F).max(1);
|
||||
let w1 = stdf.get(2..4).map(|b| u16::from_le_bytes([b[0], b[1]])).unwrap_or(0xFFF1);
|
||||
let istd_base = w1 >> 4;
|
||||
@@ -135,6 +420,8 @@ pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result<Vec<RawStyle>, Do
|
||||
{
|
||||
chpx = u.clone();
|
||||
}
|
||||
// A built-in style goes by its built-in name ("Normal", "heading 1"), as in Word.
|
||||
let name = built_in_name(sti).map_or(name, str::to_owned);
|
||||
out.push(RawStyle { stk, istd_base, name, papx, chpx });
|
||||
}
|
||||
Ok(out)
|
||||
@@ -192,3 +479,84 @@ pub(crate) fn fonts(table: &[u8], fc: u32, lcb: u32) -> Vec<String> {
|
||||
|
||||
/// Bytes of an FFN before its primary name ([MS-DOC] §2.9.82).
|
||||
const FFN_HEADER: usize = 39;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// One Word 97 STD ([MS-DOC] §2.9.260, `cbSTDBaseInFile` 10) with this `sti`, `stk` and
|
||||
/// stored name, and empty UPXs.
|
||||
fn std_record(sti: u16, stk: u16, name: &str) -> Vec<u8> {
|
||||
let cupx: u16 = if stk == 1 { 2 } else { 1 };
|
||||
let mut v = Vec::new();
|
||||
v.extend_from_slice(&sti.to_le_bytes());
|
||||
v.extend_from_slice(&(stk | 0x0FFF << 4).to_le_bytes()); // stk, istdBase none
|
||||
v.extend_from_slice(&(cupx | 0x0FFF << 4).to_le_bytes()); // cupx, istdNext none
|
||||
v.extend_from_slice(&[0; 4]); // bchUpe, grfstd
|
||||
let units: Vec<u16> = name.encode_utf16().collect();
|
||||
v.extend_from_slice(&(units.len() as u16).to_le_bytes());
|
||||
v.extend(units.iter().flat_map(|u| u.to_le_bytes()));
|
||||
v.extend_from_slice(&[0, 0]);
|
||||
if stk == 1 {
|
||||
v.extend_from_slice(&[2, 0, 0, 0]); // UpxPapx: istd 0, no sprms
|
||||
}
|
||||
v.extend_from_slice(&[0, 0]); // UpxChpx: no sprms
|
||||
[(v.len() as u16).to_le_bytes().to_vec(), v].concat()
|
||||
}
|
||||
|
||||
/// An STSH holding these STDs.
|
||||
fn stsh(stds: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut v = vec![4, 0];
|
||||
v.extend_from_slice(&(stds.len() as u16).to_le_bytes());
|
||||
v.extend_from_slice(&10u16.to_le_bytes());
|
||||
v.extend(stds.iter().flatten());
|
||||
v
|
||||
}
|
||||
|
||||
fn names(stds: &[Vec<u8>]) -> Vec<String> {
|
||||
let t = stsh(stds);
|
||||
parse(&t, 0, t.len() as u32).expect("STSH").into_iter().map(|s| s.name).collect()
|
||||
}
|
||||
|
||||
/// #1805: a non-English Word stores its built-in styles under its own names; Word reads them
|
||||
/// by `sti`, under the built-in names.
|
||||
#[test]
|
||||
fn built_in_styles_take_their_built_in_names() {
|
||||
let read = names(&[
|
||||
std_record(0, 1, "Обычный"),
|
||||
std_record(1, 1, "Kop 1"),
|
||||
std_record(65, 2, "Fuente de párrafo predeter."),
|
||||
std_record(153, 1, "Sprechblasentext"),
|
||||
std_record(154, 3, "表 (格子)"),
|
||||
std_record(266, 1, "Inhaltsverzeichnisüberschrift"),
|
||||
]);
|
||||
assert_eq!(read, ["Normal", "heading 1", "Default Paragraph Font", "Balloon Text", "Table Grid", "TOC Heading"]);
|
||||
}
|
||||
|
||||
/// #1805: a user-defined style (0x0FFE), and an `sti` past the table, keep the stored name.
|
||||
#[test]
|
||||
fn other_styles_keep_their_stored_names() {
|
||||
assert_eq!(
|
||||
names(&[std_record(0x0FFE, 1, "Mijn stijl"), std_record(267, 2, "Later"), std_record(0x0FFF, 1, "Nil")]),
|
||||
["Mijn stijl", "Later", "Nil"]
|
||||
);
|
||||
}
|
||||
|
||||
/// #1805: the document's own Normal is the model's `Normal`, and a heading is a heading.
|
||||
#[test]
|
||||
fn a_localized_normal_is_the_models_normal() {
|
||||
let t = stsh(&[std_record(0, 1, "Standaard"), std_record(1, 1, "Kop 1")]);
|
||||
let sheet = crate::fmt::stylesheet(&parse(&t, 0, t.len() as u32).expect("STSH"), &[], StandardFonts::default());
|
||||
assert!(sheet.get("Normal").is_some());
|
||||
let h = sheet.styles.iter().find(|s| s.name == "Heading 1").expect("Heading 1");
|
||||
assert_eq!(h.para.outline_level, Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_has_every_sti_of_ms_oe376() {
|
||||
assert_eq!(BUILT_IN_NAMES.len(), 267);
|
||||
assert_eq!(built_in_name(106), Some("annotation subject"));
|
||||
assert_eq!(built_in_name(107), Some("No List"));
|
||||
assert_eq!(built_in_name(0x0FFE), None);
|
||||
}
|
||||
}
|
||||
@@ -389,119 +389,6 @@ fn stylesheet(word: &[u8], fc: u32, lcb: u32) -> (Vec<RawStyle>, Vec<StyleFacts>
|
||||
(styles, facts)
|
||||
}
|
||||
|
||||
/// The names of the built-in styles by sti: the "Index within built-in styles" of the reserved
|
||||
/// style names in [MS-OE376] (Part 4 §2.7.3.9), which [MS-DOC]'s StdfBase says sti is. 0x0FFE
|
||||
/// (user-defined) and anything past the table keep the name stored in the file.
|
||||
const BUILT_IN_NAMES: [&str; 107] = [
|
||||
"Normal",
|
||||
"heading 1",
|
||||
"heading 2",
|
||||
"heading 3",
|
||||
"heading 4",
|
||||
"heading 5",
|
||||
"heading 6",
|
||||
"heading 7",
|
||||
"heading 8",
|
||||
"heading 9",
|
||||
"index 1",
|
||||
"index 2",
|
||||
"index 3",
|
||||
"index 4",
|
||||
"index 5",
|
||||
"index 6",
|
||||
"index 7",
|
||||
"index 8",
|
||||
"index 9",
|
||||
"toc 1",
|
||||
"toc 2",
|
||||
"toc 3",
|
||||
"toc 4",
|
||||
"toc 5",
|
||||
"toc 6",
|
||||
"toc 7",
|
||||
"toc 8",
|
||||
"toc 9",
|
||||
"Normal Indent",
|
||||
"footnote text",
|
||||
"annotation text",
|
||||
"header",
|
||||
"footer",
|
||||
"index heading",
|
||||
"caption",
|
||||
"table of figures",
|
||||
"envelope address",
|
||||
"envelope return",
|
||||
"footnote reference",
|
||||
"annotation reference",
|
||||
"line number",
|
||||
"page number",
|
||||
"endnote reference",
|
||||
"endnote text",
|
||||
"table of authorities",
|
||||
"macro",
|
||||
"toa heading",
|
||||
"List",
|
||||
"List Bullet",
|
||||
"List Number",
|
||||
"List 2",
|
||||
"List 3",
|
||||
"List 4",
|
||||
"List 5",
|
||||
"List Bullet 2",
|
||||
"List Bullet 3",
|
||||
"List Bullet 4",
|
||||
"List Bullet 5",
|
||||
"List Number 2",
|
||||
"List Number 3",
|
||||
"List Number 4",
|
||||
"List Number 5",
|
||||
"Title",
|
||||
"Closing",
|
||||
"Signature",
|
||||
"Default Paragraph Font",
|
||||
"Body Text",
|
||||
"Body Text Indent",
|
||||
"List Continue",
|
||||
"List Continue 2",
|
||||
"List Continue 3",
|
||||
"List Continue 4",
|
||||
"List Continue 5",
|
||||
"Message Header",
|
||||
"Subtitle",
|
||||
"Salutation",
|
||||
"Date",
|
||||
"Body Text First Indent",
|
||||
"Body Text First Indent 2",
|
||||
"Note Heading",
|
||||
"Body Text 2",
|
||||
"Body Text 3",
|
||||
"Body Text Indent 2",
|
||||
"Body Text Indent 3",
|
||||
"Block Text",
|
||||
"Hyperlink",
|
||||
"FollowedHyperlink",
|
||||
"Strong",
|
||||
"Emphasis",
|
||||
"Document Map",
|
||||
"Plain Text",
|
||||
"E-mail Signature",
|
||||
"HTML Top of Form",
|
||||
"HTML Bottom of Form",
|
||||
"Normal (Web)",
|
||||
"HTML Acronym",
|
||||
"HTML Address",
|
||||
"HTML Cite",
|
||||
"HTML Code",
|
||||
"HTML Definition",
|
||||
"HTML Keyboard",
|
||||
"HTML Preformatted",
|
||||
"HTML Sample",
|
||||
"HTML Typewriter",
|
||||
"HTML Variable",
|
||||
"Normal Table",
|
||||
"annotation subject",
|
||||
];
|
||||
|
||||
/// One style entry (`None` for an empty slot or one too short for its fixed part and name).
|
||||
fn style(std: &[u8], cb_base: usize) -> Option<(RawStyle, StyleFacts)> {
|
||||
let u16_at = |at: usize| std.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]]));
|
||||
@@ -515,8 +402,8 @@ fn style(std: &[u8], cb_base: usize) -> Option<(RawStyle, StyleFacts)> {
|
||||
// ("Default" or "Обычный" for Normal). Other names are 8-bit, as Word shows them
|
||||
// (Windows-1252: names it couldn't store read back with '?').
|
||||
let stored = std.get(cb_base + 1..cb_base + 1 + len)?;
|
||||
let name: String = match BUILT_IN_NAMES.get(usize::from(sti)) {
|
||||
Some(built_in) => (*built_in).to_owned(),
|
||||
let name: String = match crate::stsh::built_in_name(sti) {
|
||||
Some(built_in) => built_in.to_owned(),
|
||||
None => stored.iter().map(|&b| craft_codepage::cp1252(b)).collect(),
|
||||
};
|
||||
let mut upxs: Vec<&[u8]> = Vec::new();
|
||||
|
||||
@@ -72,7 +72,7 @@ const BUILTIN: &[(&str, u16)] = &[
|
||||
("FollowedHyperlink", 86),
|
||||
("Strong", 87),
|
||||
("Emphasis", 88),
|
||||
("Plain Text", 91),
|
||||
("Plain Text", 90),
|
||||
("Normal (Web)", 94),
|
||||
("Normal Table", 105),
|
||||
("No List", 107),
|
||||
@@ -397,4 +397,30 @@ mod tests {
|
||||
let t = font_table(&names);
|
||||
assert_eq!(crate::stsh::fonts(&t, 0, t.len() as u32), names);
|
||||
}
|
||||
|
||||
/// #1805: the reader names a built-in style by its `sti`, so each one the writer gives must be
|
||||
/// the one [MS-OE376] lists for the name it writes (Plain Text is 90; 91 is E-mail Signature).
|
||||
#[test]
|
||||
fn every_built_in_sti_names_the_style_written() {
|
||||
for &(name, sti) in BUILTIN {
|
||||
assert_eq!(crate::stsh::built_in_name(sti), Some(name), "sti {sti}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #1805: a built-in style the writer gives an `sti` reads back under its own name.
|
||||
#[test]
|
||||
fn a_plain_text_style_reads_back_as_plain_text() {
|
||||
let mut d = craft_wordmodel::Document::new();
|
||||
std::sync::Arc::make_mut(&mut d.styles).styles.push(Style {
|
||||
id: "PlainText".into(),
|
||||
name: "Plain Text".into(),
|
||||
kind: StyleKind::Paragraph,
|
||||
based_on: Some("Normal".into()),
|
||||
..Default::default()
|
||||
});
|
||||
d.body = vec![craft_wordmodel::para_block(craft_wordmodel::para::Paragraph::with_text("x", CharProps::default()).styled("PlainText"))];
|
||||
let r = crate::read(&crate::write(&d).expect("write")).expect("read back");
|
||||
let style = r.body[0].as_para().and_then(|p| p.props.style.clone()).and_then(|id| r.styles.get(&id).map(|s| s.name.clone()));
|
||||
assert_eq!(style.as_deref(), Some("Plain Text"));
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub(crate) struct Reader<'p> {
|
||||
file_orders: craft_wordmodel::para::FileOrders,
|
||||
pub doc: Document,
|
||||
pub pc: PropCtx,
|
||||
revs: HashMap<(u8, String, String, Option<String>), u32>,
|
||||
revs: HashMap<(u8, String, String, Option<String>, Option<String>), u32>,
|
||||
/// Move ranges (`w:moveFromRangeStart` …) seen so far.
|
||||
pub moves: MoveCtx,
|
||||
media_by_path: HashMap<String, String>,
|
||||
|
||||
@@ -74,17 +74,22 @@ impl Reader<'_> {
|
||||
pub(super) fn revision_named(&mut self, kind: RevisionKind, e: &El, move_name: Option<String>) -> u32 {
|
||||
let author = e.attr("w:author").unwrap_or("").chars().take(256).collect::<String>();
|
||||
let date = e.attr("w:date").unwrap_or("").chars().take(64).collect::<String>();
|
||||
// Only the Word namespace's `dateUtc`: a bare one would be saved under that namespace
|
||||
// without having come from it.
|
||||
let date_utc = e.attr_exact("w16du:dateUtc").filter(|d| !d.is_empty()).map(|d| d.chars().take(64).collect::<String>());
|
||||
let k = match kind {
|
||||
RevisionKind::Insert => 0,
|
||||
RevisionKind::Delete => 1,
|
||||
RevisionKind::Format => 2,
|
||||
};
|
||||
let key = (k, author.clone(), date.clone(), move_name.clone());
|
||||
// Two changes with one local `w:date` (the hour the clocks go back over) are told apart
|
||||
// by their UTC time.
|
||||
let key = (k, author.clone(), date.clone(), move_name.clone(), date_utc.clone());
|
||||
if let Some(i) = self.revs.get(&key) {
|
||||
return *i;
|
||||
}
|
||||
let i = self.doc.revisions.len() as u32;
|
||||
self.doc.revisions.push(Revision { kind, author, date, move_name });
|
||||
self.doc.revisions.push(Revision { kind, author, date, move_name, date_utc });
|
||||
self.revs.insert(key, i);
|
||||
i
|
||||
}
|
||||
|
||||
@@ -144,7 +144,9 @@ impl Reader<'_> {
|
||||
// Brightness and contrast (Word's picture watermark "Washout" sets them, #1711).
|
||||
let frac = |k: &str| img.attr(k).and_then(crate::units::vml_number);
|
||||
let fx = craft_wordmodel::picfx::PicFx::from_vml(frac("gain").unwrap_or(1.0), frac("blacklevel").unwrap_or(0.0));
|
||||
return Some(InlineObject::Image { media, w, h, alt, float, crop: [0.0; 4], fx, ole: None });
|
||||
let crop =
|
||||
["cropleft", "croptop", "cropright", "cropbottom"].map(|key| img.attr(key).and_then(vml_fraction).unwrap_or(0.0).clamp(0.0, 1.0));
|
||||
return Some(InlineObject::Image { media, w, h, alt, float, crop, fx, ole: None });
|
||||
}
|
||||
// The shapetype the shape is drawn from (its `type`, ECMA-376 Part 4 VML), when written in
|
||||
// the same picture: what the shape leaves out, it takes from there.
|
||||
|
||||
@@ -225,6 +225,12 @@ pub fn open_change(w: &mut W, tag: &str, a: &ChangeAttrs) {
|
||||
w.open(tag, &refs);
|
||||
}
|
||||
|
||||
/// [`open_change`] for an empty element.
|
||||
pub fn empty_change(w: &mut W, tag: &str, a: &ChangeAttrs) {
|
||||
let refs: Vec<(&str, &str)> = a.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||
w.empty(tag, &refs);
|
||||
}
|
||||
|
||||
/// A tracked change element holding the properties before the change: `<tag attrs><inner>…</inner></tag>`.
|
||||
fn change_el(w: &mut W, tag: &str, inner: &str, a: &ChangeAttrs, body: impl FnOnce(&mut W)) {
|
||||
open_change(w, tag, a);
|
||||
|
||||
@@ -8,7 +8,7 @@ use craft_wordmodel::section::{LineNumberRestart, NoteProps, SectionProps, Secti
|
||||
use craft_wordmodel::table::Table;
|
||||
use craft_wordmodel::{Block, Blocks, InlineObject, Paragraph, RevisionKind};
|
||||
|
||||
use super::props::{ChangeAttrs, borders, open_change, ppr_inner, rpr, rpr_inner, tblpr, tcpr, trpr};
|
||||
use super::props::{ChangeAttrs, borders, empty_change, open_change, ppr_inner, rpr, rpr_inner, tblpr, tcpr, trpr};
|
||||
use super::{PartRels, Writer};
|
||||
use crate::package::rt;
|
||||
use crate::units::{emu, n, twips};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::toc::written_toc_span;
|
||||
use super::{Block, Blocks, CharProps, MAX_DEPTH, PartRels, Table, W, Writer, tblpr, tcpr, trpr, twips};
|
||||
use super::{Block, Blocks, CharProps, MAX_DEPTH, PartRels, Table, W, Writer, empty_change, tblpr, tcpr, trpr, twips};
|
||||
|
||||
impl Writer<'_> {
|
||||
fn write_trailing_para(&mut self, w: &mut W, depth: usize) {
|
||||
@@ -77,13 +77,11 @@ impl Writer<'_> {
|
||||
continue;
|
||||
}
|
||||
let name = self.doc.move_name(Some(rev)).unwrap_or("").to_string();
|
||||
let (id, author, date) = self.rev_attrs(rev);
|
||||
let mut a = self.change_attrs(rev);
|
||||
let id = a.first().map(|(_, id)| id.clone()).unwrap_or_default();
|
||||
a.insert(1, ("w:name", name));
|
||||
let tag = if to { "w:moveToRangeStart" } else { "w:moveFromRangeStart" };
|
||||
if date.is_empty() {
|
||||
w.empty(tag, &[("w:id", &id), ("w:name", &name), ("w:author", &author)]);
|
||||
} else {
|
||||
w.empty(tag, &[("w:id", &id), ("w:name", &name), ("w:author", &author), ("w:date", &date)]);
|
||||
}
|
||||
empty_change(w, tag, &a);
|
||||
self.open_moves.push((rev, id, to));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::{
|
||||
ChangeAttrs, CharProps, InlineObject, Paragraph, PartRels, Piece, PropChange, RevisionKind, W, Writer, open_change, ppr_inner, rpr, rpr_inner, rt,
|
||||
ChangeAttrs, CharProps, InlineObject, Paragraph, PartRels, Piece, PropChange, RevisionKind, W, Writer, empty_change, open_change, ppr_inner, rpr,
|
||||
rpr_inner, rt,
|
||||
};
|
||||
|
||||
impl Writer<'_> {
|
||||
@@ -37,12 +38,8 @@ impl Writer<'_> {
|
||||
fn write_mark_rpr(&mut self, w: &mut W, mark: &CharProps, mark_revs: &[(u32, &str)]) {
|
||||
w.open("w:rPr", &[]);
|
||||
for (idx, tag) in mark_revs {
|
||||
let (id, author, date) = self.rev_attrs(*idx);
|
||||
if date.is_empty() {
|
||||
w.empty(tag, &[("w:id", &id), ("w:author", &author)]);
|
||||
} else {
|
||||
w.empty(tag, &[("w:id", &id), ("w:author", &author), ("w:date", &date)]);
|
||||
}
|
||||
let a = self.change_attrs(*idx);
|
||||
empty_change(w, tag, &a);
|
||||
}
|
||||
rpr_inner(w, mark);
|
||||
if let Some(ch) = mark.fmt_change.as_deref() {
|
||||
@@ -300,21 +297,20 @@ impl Writer<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn rev_attrs(&mut self, idx: u32) -> (String, String, String) {
|
||||
/// `w:id`, `w:author`, `w:date` and `w16du:dateUtc` of a tracked change by revision `idx`.
|
||||
pub(crate) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs {
|
||||
self.next_rev_id += 1;
|
||||
let r = self.doc.revisions.get(idx as usize);
|
||||
let author = crate::write::annotation_author(self.doc, r.map_or("", |r| r.author.as_str())).to_string();
|
||||
// Remove date and time (§17.15.1.69): tracked changes are saved without `w:date`.
|
||||
let date = if self.doc.settings.remove_date_time { String::new() } else { r.map(|r| r.date.clone()).unwrap_or_default() };
|
||||
(self.next_rev_id.to_string(), author, date)
|
||||
}
|
||||
|
||||
/// `w:id`, `w:author` and `w:date` of a tracked change by revision `idx`.
|
||||
pub(crate) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs {
|
||||
let (id, author, date) = self.rev_attrs(idx);
|
||||
let mut a = vec![("w:id", id), ("w:author", author)];
|
||||
if !date.is_empty() {
|
||||
a.push(("w:date", date));
|
||||
let mut a = vec![("w:id", self.next_rev_id.to_string()), ("w:author", author)];
|
||||
// Remove date and time (§17.15.1.69): tracked changes are saved without their dates.
|
||||
if let Some(r) = r.filter(|_| !self.doc.settings.remove_date_time) {
|
||||
if !r.date.is_empty() {
|
||||
a.push(("w:date", r.date.clone()));
|
||||
}
|
||||
if let Some(utc) = r.date_utc.as_ref().filter(|d| !d.is_empty()) {
|
||||
a.push(("w16du:dateUtc", utc.clone()));
|
||||
}
|
||||
}
|
||||
a
|
||||
}
|
||||
@@ -344,12 +340,8 @@ impl Writer<'_> {
|
||||
continue;
|
||||
}
|
||||
let tag = self.rev_tag(idx, tag);
|
||||
let (id, author, date) = self.rev_attrs(idx);
|
||||
if date.is_empty() {
|
||||
w.open(tag, &[("w:id", &id), ("w:author", &author)]);
|
||||
} else {
|
||||
w.open(tag, &[("w:id", &id), ("w:author", &author), ("w:date", &date)]);
|
||||
}
|
||||
let a = self.change_attrs(idx);
|
||||
open_change(w, tag, &a);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-3
@@ -49,6 +49,8 @@ pub const NAMESPACES: &[(&str, &str)] = &[
|
||||
("cx6", "http://schemas.microsoft.com/office/drawing/2016/5/12/chartex"),
|
||||
("cx7", "http://schemas.microsoft.com/office/drawing/2016/5/13/chartex"),
|
||||
("cx8", "http://schemas.microsoft.com/office/drawing/2016/5/14/chartex"),
|
||||
// A tracked change's UTC time (`w16du:dateUtc`).
|
||||
("w16du", "http://schemas.microsoft.com/office/word/2023/wordml/word16du"),
|
||||
];
|
||||
|
||||
/// The `a:ext` URI under which a drawing is marked decorative ([MS-ODRAWXML]), and the
|
||||
@@ -201,15 +203,20 @@ impl El {
|
||||
/// Attribute by canonical name (`w:val`); falls back to an unqualified attribute with the
|
||||
/// same local name (some producers omit the prefix).
|
||||
pub fn attr(&self, name: &str) -> Option<&str> {
|
||||
if let Some((_, v)) = self.attrs.iter().find(|(k, _)| k == name) {
|
||||
if let Some(v) = self.attr_exact(name) {
|
||||
return Some(v);
|
||||
}
|
||||
let local = name.rsplit(':').next().unwrap_or(name);
|
||||
if local != name {
|
||||
return self.attrs.iter().find(|(k, _)| k == local).map(|(_, v)| v.as_str());
|
||||
return self.attr_exact(local);
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Attribute by canonical name only, for one whose namespace carries meaning an unqualified
|
||||
/// attribute can't claim.
|
||||
pub fn attr_exact(&self, name: &str) -> Option<&str> {
|
||||
self.attrs.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
|
||||
}
|
||||
/// Child elements.
|
||||
pub fn els(&self) -> impl Iterator<Item = &El> {
|
||||
self.kids.iter().filter_map(|n| match n {
|
||||
@@ -531,7 +538,7 @@ impl W {
|
||||
/// `xmlns:` declarations for the body-part namespaces, plus `mc:Ignorable`.
|
||||
pub fn body_ns() -> Vec<(String, String)> {
|
||||
let mut v: Vec<(String, String)> = NAMESPACES.iter().map(|(p, u)| (format!("xmlns:{p}"), (*u).to_string())).collect();
|
||||
v.push(("mc:Ignorable".into(), "w14 w15 wp14".into()));
|
||||
v.push(("mc:Ignorable".into(), "w14 w15 wp14 w16du".into()));
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -2706,6 +2706,42 @@ fn move_revisions_round_trip() {
|
||||
check(&craft_docx::read(&out).unwrap());
|
||||
}
|
||||
|
||||
/// Two insertions by one author with one local `w:date`, told apart (or not) by `dateUtc`.
|
||||
fn two_insertions_at_one_local_time(utc: [&str; 2]) -> String {
|
||||
let ins = |id: u32, utc: &str, text: &str| {
|
||||
format!(r#"<w:ins w:id="{id}" w:author="Ada" w:date="2026-11-01T01:30:00Z" {utc}><w:r><w:t xml:space="preserve">{text}</w:t></w:r></w:ins>"#)
|
||||
};
|
||||
format!("<w:p>{}{}</w:p>", ins(1, utc[0], " One"), ins(2, utc[1], " Two"))
|
||||
}
|
||||
|
||||
/// Issue #3206: a tracked change's `dateUtc` is read under any prefix bound to Word's namespace
|
||||
/// for it, and saved under that namespace.
|
||||
#[test]
|
||||
fn a_tracked_change_utc_time_is_read_under_any_prefix_for_its_namespace() {
|
||||
let du = r#"xmlns:du="http://schemas.microsoft.com/office/word/2023/wordml/word16du""#;
|
||||
let body = two_insertions_at_one_local_time([
|
||||
&format!(r#"{du} du:dateUtc="2026-11-01T05:30:00Z""#),
|
||||
&format!(r#"{du} du:dateUtc="2026-11-01T06:30:00Z""#),
|
||||
]);
|
||||
let d = read_body(&body);
|
||||
let utc: Vec<_> = d.revisions.iter().map(|r| r.date_utc.as_deref()).collect();
|
||||
assert_eq!(utc, [Some("2026-11-01T05:30:00Z"), Some("2026-11-01T06:30:00Z")]);
|
||||
let xml = text(&unzip(&craft_docx::write(&d).unwrap()), "word/document.xml");
|
||||
assert_eq!(attr_values(&xml, "w:ins", "w16du:dateUtc"), ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"]);
|
||||
}
|
||||
|
||||
/// Issue #3206: an unqualified `dateUtc` doesn't say it's Word's UTC time, so it neither tells
|
||||
/// changes apart nor is saved under Word's namespace.
|
||||
#[test]
|
||||
fn an_unqualified_date_utc_is_not_a_tracked_change_utc_time() {
|
||||
let body = two_insertions_at_one_local_time([r#"dateUtc="2026-11-01T05:30:00Z""#, r#"dateUtc="2026-11-01T06:30:00Z""#]);
|
||||
let d = read_body(&body);
|
||||
assert_eq!(d.revisions.len(), 1, "one author, kind and local date is one change");
|
||||
assert_eq!(d.revisions[0].date_utc, None);
|
||||
let xml = text(&unzip(&craft_docx::write(&d).unwrap()), "word/document.xml");
|
||||
assert!(!xml.contains("dateUtc="), "{xml}");
|
||||
}
|
||||
|
||||
/// A document's own footnote separators and continuation notice are kept (ECMA-376 §17.11), and
|
||||
/// written back as Word numbers them: -1, 0 and 1, the notes after them.
|
||||
#[test]
|
||||
|
||||
@@ -125,3 +125,91 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() {
|
||||
let edited = out.finish().unwrap().into_inner();
|
||||
assert_eq!(picture_links(&craft_docx::read(&edited).unwrap())[0], Some("https://example.com/saved".to_string()));
|
||||
}
|
||||
|
||||
// Original synthetic VML package for #2912, reported by denstu473; no reference-app asset.
|
||||
#[test]
|
||||
fn a_vml_picture_keeps_its_crop_when_saved() {
|
||||
fn image_crop(doc: &Document, original_png: &[u8]) -> [f32; 4] {
|
||||
let paragraph = doc.body[0].as_para().expect("the synthetic picture's paragraph");
|
||||
assert_eq!(paragraph.objects.len(), 1, "the VML picture must be decoded before testing crop");
|
||||
let InlineObject::Image { media, w, h, alt, crop, fx, .. } = ¶graph.objects[0] else {
|
||||
panic!("the synthetic object must be an image");
|
||||
};
|
||||
assert!((*w - 24.0).abs() < 0.001 && (*h - 12.0).abs() < 0.001, "picture size changed: {w} x {h}");
|
||||
assert_eq!(alt, "cropped square");
|
||||
assert_eq!(doc.media.get(media).expect("the picture's embedded media").as_slice(), original_png);
|
||||
assert_eq!(*fx, craft_wordmodel::picfx::PicFx::new(40_000, 0, 0));
|
||||
*crop
|
||||
}
|
||||
fn crops_near(actual: [f32; 4], expected: [f32; 4], tolerance: f32) -> bool {
|
||||
actual.into_iter().zip(expected).all(|(a, b)| (a - b).abs() <= tolerance)
|
||||
}
|
||||
|
||||
let original_png = png();
|
||||
let mut lost = Vec::new();
|
||||
// Crop slots are left, top, right, bottom. These distinct fractions are exactly binary.
|
||||
let positive = [0.125, 0.0625, 0.25, 0.5];
|
||||
for (label, attributes, expected, saved_rect) in [
|
||||
("default", "", [0.0; 4], None),
|
||||
(
|
||||
"report fixed fractions",
|
||||
r#"cropleft="8192f" croptop="3277f" cropright="16384f" cropbottom="6554f""#,
|
||||
[8192.0f32 / 65_536.0, 3277.0 / 65_536.0, 16384.0 / 65_536.0, 6554.0 / 65_536.0],
|
||||
Some(r#"<a:srcRect l="12500" t="5000" r="25000" b="10001"/>"#),
|
||||
),
|
||||
(
|
||||
"fixed fractions",
|
||||
r#"cropleft="8192f" croptop="4096f" cropright="16384f" cropbottom="32768f""#,
|
||||
positive,
|
||||
Some(r#"<a:srcRect l="12500" t="6250" r="25000" b="50000"/>"#),
|
||||
),
|
||||
(
|
||||
"decimal fractions",
|
||||
r#"cropleft="0.125" croptop="0.0625" cropright="0.25" cropbottom="0.5""#,
|
||||
positive,
|
||||
Some(r#"<a:srcRect l="12500" t="6250" r="25000" b="50000"/>"#),
|
||||
),
|
||||
(
|
||||
"percentage fractions",
|
||||
r#"cropleft="12.5%" croptop="6.25%" cropright="25%" cropbottom="50%""#,
|
||||
positive,
|
||||
Some(r#"<a:srcRect l="12500" t="6250" r="25000" b="50000"/>"#),
|
||||
),
|
||||
(
|
||||
"bounded fractions",
|
||||
r#"cropleft="-25%" croptop="125%" cropright="not-a-fraction" cropbottom="NaN""#,
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
Some(r#"<a:srcRect l="0" t="100000" r="0" b="0"/>"#),
|
||||
),
|
||||
] {
|
||||
// The local namespace keeps the existing package helper and every old fixture intact.
|
||||
let body = format!(
|
||||
r#"<w:p><w:r><w:pict xmlns:v="urn:schemas-microsoft-com:vml"><v:shape style="width:24pt;height:12pt" alt="cropped square"><v:imagedata r:id="rIdPic" gain="1" blacklevel="0.2" {attributes}/></v:shape></w:pict></w:r></w:p>"#
|
||||
);
|
||||
let doc = craft_docx::read(&package(&body)).unwrap();
|
||||
let read_crop = image_crop(&doc, &original_png);
|
||||
let saved = craft_docx::write(&doc).unwrap();
|
||||
let xml = part(&saved, "word/document.xml");
|
||||
let reopened = craft_docx::read(&saved).unwrap();
|
||||
let reopened_crop = image_crop(&reopened, &original_png);
|
||||
|
||||
if let Some(saved_rect) = saved_rect {
|
||||
if !crops_near(read_crop, expected, 0.000_001) {
|
||||
lost.push(format!("{label}: read crop {read_crop:?}"));
|
||||
}
|
||||
if !xml.contains(saved_rect) {
|
||||
lost.push(format!("{label}: saved srcRect"));
|
||||
}
|
||||
// DrawingML uses 100000 units per fraction; allow its rounding on a real re-read.
|
||||
if !crops_near(reopened_crop, expected, 0.000_01) {
|
||||
lost.push(format!("{label}: reopened crop {reopened_crop:?}"));
|
||||
}
|
||||
} else {
|
||||
// The zero/default control must work before any positive-crop regression is reported.
|
||||
assert_eq!(read_crop, [0.0; 4]);
|
||||
assert!(!xml.contains("<a:srcRect"), "{xml}");
|
||||
assert_eq!(reopened_crop, [0.0; 4]);
|
||||
}
|
||||
}
|
||||
assert!(lost.is_empty(), "VML picture crops were lost: {lost:?}");
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use std::collections::BTreeMap;
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#;
|
||||
const W16DU_NS: &str = r#"xmlns:w16du="http://schemas.microsoft.com/office/word/2023/wordml/word16du""#;
|
||||
const RT: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
|
||||
|
||||
fn zip(entries: &[(&str, String)]) -> Vec<u8> {
|
||||
@@ -29,11 +30,11 @@ fn unzip(bytes: &[u8]) -> BTreeMap<String, String> {
|
||||
parts
|
||||
}
|
||||
|
||||
/// A package with two named commenters, a tracked insertion and deletion, the document
|
||||
/// properties' creator and last-modified-by, and `settings` inside `w:settings`.
|
||||
/// A package with two named commenters, a tracked insertion (with its UTC time) and deletion, the
|
||||
/// document properties' creator and last-modified-by, and `settings` inside `w:settings`.
|
||||
fn fixture(settings: &str) -> Vec<u8> {
|
||||
let body = r#"<w:p><w:commentRangeStart w:id="1"/><w:r><w:t>Clause one.</w:t></w:r><w:commentRangeEnd w:id="1"/><w:r><w:commentReference w:id="1"/></w:r></w:p>
|
||||
<w:p><w:commentRangeStart w:id="2"/><w:ins w:id="10" w:author="Quill Ramsey" w:date="2026-03-04T05:06:07Z"><w:r><w:t>Added</w:t></w:r></w:ins><w:del w:id="11" w:author="Ona Vettel" w:date="2026-03-05T05:06:07Z"><w:r><w:delText>Removed</w:delText></w:r></w:del><w:commentRangeEnd w:id="2"/><w:r><w:commentReference w:id="2"/></w:r></w:p>"#;
|
||||
<w:p><w:commentRangeStart w:id="2"/><w:ins w:id="10" w:author="Quill Ramsey" w:date="2026-03-04T05:06:07Z" w16du:dateUtc="2026-03-04T13:06:07Z"><w:r><w:t>Added</w:t></w:r></w:ins><w:del w:id="11" w:author="Ona Vettel" w:date="2026-03-05T05:06:07Z"><w:r><w:delText>Removed</w:delText></w:r></w:del><w:commentRangeEnd w:id="2"/><w:r><w:commentReference w:id="2"/></w:r></w:p>"#;
|
||||
let comments = format!(
|
||||
r#"<w:comments {W_NS}><w:comment w:id="1" w:author="Quill Ramsey" w:initials="QR" w:date="2026-03-01T10:00:00Z"><w:p><w:r><w:t>Check this.</w:t></w:r></w:p></w:comment><w:comment w:id="2" w:author="Ona Vettel" w:initials="OV" w:date="2026-03-02T10:00:00Z"><w:p><w:r><w:t>Agreed.</w:t></w:r></w:p></w:comment></w:comments>"#
|
||||
);
|
||||
@@ -46,7 +47,7 @@ fn fixture(settings: &str) -> Vec<u8> {
|
||||
);
|
||||
zip(&[
|
||||
("_rels/.rels", root_rels),
|
||||
("word/document.xml", format!(r#"<w:document {W_NS}><w:body>{body}</w:body></w:document>"#)),
|
||||
("word/document.xml", format!(r#"<w:document {W_NS} {W16DU_NS}><w:body>{body}</w:body></w:document>"#)),
|
||||
("word/_rels/document.xml.rels", doc_rels),
|
||||
("word/comments.xml", comments),
|
||||
("word/settings.xml", format!(r#"<w:settings {W_NS}>{settings}</w:settings>"#)),
|
||||
@@ -77,7 +78,7 @@ fn remove_personal_information_and_dates_on_save() {
|
||||
for name in NAMES {
|
||||
assert!(!all.contains(name), "{name} saved");
|
||||
}
|
||||
assert!(!all.contains("w:date="), "annotation date saved");
|
||||
assert!(!all.contains("w:date=") && !all.contains("dateUtc="), "annotation date saved");
|
||||
assert!(!all.contains("2026-03-0"), "annotation date saved");
|
||||
let comments = &parts["word/comments.xml"];
|
||||
assert_eq!(comments.matches(r#"w:author="Author""#).count(), 2, "{comments}");
|
||||
@@ -103,7 +104,7 @@ fn each_privacy_setting_works_alone() {
|
||||
// Dates only: names stay.
|
||||
let doc = craft_docx::read(&fixture("<w:removeDateAndTime/>")).unwrap();
|
||||
let (parts, all) = saved(&doc);
|
||||
assert!(!all.contains("w:date="));
|
||||
assert!(!all.contains("w:date=") && !all.contains("dateUtc="));
|
||||
assert!(all.contains("Quill Ramsey") && all.contains("Ona Vettel"));
|
||||
assert!(parts["docProps/core.xml"].contains("<dc:creator>Quill Ramsey</dc:creator>"));
|
||||
assert!(!parts["word/settings.xml"].contains("removePersonalInformation"));
|
||||
@@ -121,6 +122,7 @@ fn each_privacy_setting_works_alone() {
|
||||
let (parts, all) = saved(&doc);
|
||||
assert!(all.contains("Quill Ramsey") && all.contains(r#"w:initials="OV""#));
|
||||
assert_eq!(all.matches("w:date=").count(), 4);
|
||||
assert!(all.contains(r#"w16du:dateUtc="2026-03-04T13:06:07Z""#), "the insertion keeps its UTC time");
|
||||
assert!(parts["docProps/core.xml"].contains("<cp:lastModifiedBy>Ona Vettel</cp:lastModifiedBy>"));
|
||||
assert!(!parts["word/settings.xml"].contains("removeDateAndTime"));
|
||||
}
|
||||
|
||||
@@ -229,6 +229,8 @@ fn every_para_prop_round_trips() {
|
||||
fmt_change: None,
|
||||
snap_to_grid: Some(false),
|
||||
text_alignment: Some(TextAlignment::Top),
|
||||
// A list item's further paragraph: WordprocessingML has no such paragraph.
|
||||
list_item: None,
|
||||
};
|
||||
let variants = [
|
||||
ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() },
|
||||
@@ -976,8 +978,20 @@ fn toc_field_skips_nested_stories() {
|
||||
#[test]
|
||||
fn tracked_changes_round_trip() {
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.settings.track_changes = true;
|
||||
let ins = CharProps { ins: Some(0), ..Default::default() };
|
||||
let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() };
|
||||
@@ -1001,12 +1015,51 @@ fn tracked_changes_round_trip() {
|
||||
assert!(r.settings.track_changes);
|
||||
}
|
||||
|
||||
/// Two changes by one author with one local `w:date` (the hour the clocks go back over) stay two
|
||||
/// changes across a save, told apart by their UTC time (`w16du:dateUtc`).
|
||||
#[test]
|
||||
fn tracked_changes_with_one_local_date_stay_apart_by_their_utc_time() {
|
||||
let mut d = Document::new();
|
||||
for utc in ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"] {
|
||||
let mut r = Revision::new(RevisionKind::Insert, "Ada", "2026-11-01T01:30:00Z");
|
||||
r.date_utc = Some(utc.into());
|
||||
d.revisions.push(r);
|
||||
}
|
||||
d.settings.track_changes = true;
|
||||
let p = para_runs(&[
|
||||
("Draft.", CharProps::default()),
|
||||
(" One", CharProps { ins: Some(0), ..Default::default() }),
|
||||
(" Two", CharProps { ins: Some(1), ..Default::default() }),
|
||||
]);
|
||||
d.body = vec![para_block(p.clone())];
|
||||
let r = rt(&d);
|
||||
assert_eq!(r.revisions, d.revisions);
|
||||
assert_eq!(paras(&r)[0].runs, p.runs);
|
||||
// Without their UTC times, the file can't tell them apart.
|
||||
for r in &mut d.revisions {
|
||||
r.date_utc = None;
|
||||
}
|
||||
assert_eq!(rt(&d).revisions.len(), 1, "one author, kind and date is one change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_equations_round_trip() {
|
||||
// Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.settings.track_changes = true;
|
||||
let ins = CharProps { ins: Some(0), ..Default::default() };
|
||||
let del = CharProps { del: Some(1), ..Default::default() };
|
||||
@@ -1061,8 +1114,20 @@ fn tracked_equations_round_trip() {
|
||||
fn nested_omath_para_revisions_read() {
|
||||
// Defensive reader check: w:ins and w:del nested inside m:oMathPara.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Ada".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Charles".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let doc_xml = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><w:body><w:p><m:oMathPara><w:ins w:id="1" w:author="Ada" w:date="2026-05-01T10:00:00Z"><m:oMath><m:r><m:t>x+1</m:t></m:r></m:oMath></w:ins><w:del w:id="2" w:author="Charles" w:date="2026-05-02T10:00:00Z"><m:oMath><m:r><m:t>y-1</m:t></m:r></m:oMath></w:del></m:oMathPara></w:p></w:body></w:document>"#;
|
||||
let base = craft_docx::write(&d).unwrap();
|
||||
let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes());
|
||||
@@ -1080,8 +1145,20 @@ fn tracked_paragraph_marks_round_trip() {
|
||||
// Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's
|
||||
// `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting.
|
||||
let mut d = Document::new();
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None });
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Insert,
|
||||
author: "Alice".into(),
|
||||
date: "2026-05-01T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
d.revisions.push(Revision {
|
||||
kind: RevisionKind::Delete,
|
||||
author: "Bob".into(),
|
||||
date: "2026-05-02T10:00:00Z".into(),
|
||||
move_name: None,
|
||||
date_utc: None,
|
||||
});
|
||||
let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default());
|
||||
split.mark.ins = Some(0);
|
||||
let mut joined = Paragraph::with_text("Owned BETA", CharProps::default());
|
||||
@@ -1821,7 +1898,7 @@ fn kitchen_sink() -> Document {
|
||||
let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]);
|
||||
let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]);
|
||||
d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.last_section.headers.default = Some(h);
|
||||
let mut blocks: Blocks = Vec::new();
|
||||
let mut p = para_runs(&[
|
||||
|
||||
@@ -41,7 +41,7 @@ fn section_metadata_survives_native_json_and_two_docx_save_reopen_cycles() {
|
||||
assert!(xml.contains(r#"<w15:footnoteColumns w:val="3"/>"#), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains(r#"w:chapStyle="1" w:chapSep="hyphen""#), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains(r#"w:chapStyle="10" w:chapSep="colon""#), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14\""), "cycle {cycle}: {xml}");
|
||||
assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14 w16du\""), "cycle {cycle}: {xml}");
|
||||
document = craft_docx::read(&bytes).unwrap();
|
||||
let json = serde_json::to_vec(&document).unwrap();
|
||||
document = serde_json::from_slice(&json).unwrap();
|
||||
|
||||
@@ -37,7 +37,7 @@ fn sample() -> Document {
|
||||
let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]);
|
||||
let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]);
|
||||
d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
|
||||
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None });
|
||||
d.last_section.headers.default = Some(head);
|
||||
|
||||
let mut p = Paragraph::new();
|
||||
|
||||
+292
-21
@@ -35,6 +35,10 @@ pub enum DxfError {
|
||||
/// The memory for `tags` group codes couldn't be had: an error, not the process ending.
|
||||
#[error("not enough memory to read this drawing's {tags} DXF group codes")]
|
||||
OutOfMemory { tags: usize },
|
||||
/// An invalid integer value ([`Value::Invalid`]) cannot be encoded in binary DXF
|
||||
/// because binary integer fields have no non-finite sentinel.
|
||||
#[error("cannot encode invalid integer tag (group {code}) as binary DXF: `{text}`")]
|
||||
InvalidInteger { code: i32, text: String },
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, DxfError>;
|
||||
@@ -48,12 +52,21 @@ pub enum Value {
|
||||
Bool(bool),
|
||||
/// Binary chunk (310–319, 1004) as hex text.
|
||||
Hex(String),
|
||||
/// Non-finite or malformed numeric group value preserved as raw text.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
const I64_MIN_F64: f64 = -9_223_372_036_854_775_808.0;
|
||||
const I64_MAX_EXCLUSIVE_F64: f64 = 9_223_372_036_854_775_808.0;
|
||||
|
||||
fn f64_to_i64_checked(r: f64) -> Option<i64> {
|
||||
if r.is_finite() && (I64_MIN_F64..I64_MAX_EXCLUSIVE_F64).contains(&r) { Some(r as i64) } else { None }
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub fn as_str(&self) -> String {
|
||||
match self {
|
||||
Value::Str(s) | Value::Hex(s) => s.clone(),
|
||||
Value::Str(s) | Value::Hex(s) | Value::Invalid(s) => s.clone(),
|
||||
Value::Real(r) => format_real(*r),
|
||||
Value::Int(i) => i.to_string(),
|
||||
Value::Bool(b) => i64::from(*b).to_string(),
|
||||
@@ -84,6 +97,41 @@ impl Value {
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
/// Return the finite float value, or `None` if this value is non-finite or represents an invalid numeric group.
|
||||
pub fn checked_f64(&self) -> Option<f64> {
|
||||
match self {
|
||||
Value::Real(r) if r.is_finite() => Some(*r),
|
||||
Value::Int(i) => Some(*i as f64),
|
||||
Value::Str(s) => s.trim().parse::<f64>().ok().filter(|v| v.is_finite()),
|
||||
Value::Bool(b) => Some(f64::from(u8::from(*b))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Return the integer value, or `None` if this value represents an invalid numeric group or cannot be converted to `i64`.
|
||||
pub fn checked_i64(&self) -> Option<i64> {
|
||||
match self {
|
||||
Value::Int(i) => Some(*i),
|
||||
Value::Real(r) => f64_to_i64_checked(*r),
|
||||
Value::Str(s) => match s.trim().parse::<i64>() {
|
||||
Ok(i) => Some(i),
|
||||
Err(err) if matches!(err.kind(), std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow) => None,
|
||||
Err(_) => s.trim().parse::<f64>().ok().and_then(f64_to_i64_checked),
|
||||
},
|
||||
Value::Bool(b) => Some(i64::from(*b)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Whether this value represents a malformed or non-finite numeric group.
|
||||
pub fn is_invalid(&self) -> bool {
|
||||
matches!(self, Value::Invalid(_))
|
||||
}
|
||||
/// The raw text of the invalid value, if this is [`Value::Invalid`].
|
||||
pub fn invalid_str(&self) -> Option<&str> {
|
||||
match self {
|
||||
Value::Invalid(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -100,11 +148,14 @@ impl Tag {
|
||||
Tag { code, value: Value::Str(v.into()) }
|
||||
}
|
||||
pub fn f(code: i32, v: f64) -> Self {
|
||||
Tag { code, value: Value::Real(if v.is_finite() { v } else { 0.0 }) }
|
||||
Tag { code, value: if v.is_finite() { Value::Real(v) } else { Value::Invalid(v.to_string()) } }
|
||||
}
|
||||
pub fn i(code: i32, v: i64) -> Self {
|
||||
Tag { code, value: Value::Int(v) }
|
||||
}
|
||||
pub fn invalid(code: i32, v: impl Into<String>) -> Self {
|
||||
Tag { code, value: Value::Invalid(v.into()) }
|
||||
}
|
||||
pub fn str(&self) -> String {
|
||||
self.value.as_str()
|
||||
}
|
||||
@@ -121,6 +172,20 @@ impl Tag {
|
||||
pub fn i64(&self) -> i64 {
|
||||
self.value.as_i64()
|
||||
}
|
||||
/// Return the finite float value, or `None` if this tag's value is non-finite or invalid.
|
||||
pub fn checked_f64(&self) -> Option<f64> {
|
||||
self.value.checked_f64()
|
||||
}
|
||||
/// Return the integer value, or `None` if this tag's value is invalid or cannot be converted to `i64`.
|
||||
pub fn checked_i64(&self) -> Option<i64> {
|
||||
self.value.checked_i64()
|
||||
}
|
||||
pub fn is_invalid(&self) -> bool {
|
||||
self.value.is_invalid()
|
||||
}
|
||||
pub fn invalid_str(&self) -> Option<&str> {
|
||||
self.value.invalid_str()
|
||||
}
|
||||
}
|
||||
|
||||
/// The value type for a group code (DXF Reference, "Group Code Value Types").
|
||||
@@ -151,18 +216,26 @@ pub fn kind_of(code: i32) -> Kind {
|
||||
fn typed(code: i32, text: &str) -> Value {
|
||||
let t = text.trim();
|
||||
match kind_of(code) {
|
||||
Kind::Real => t.parse::<f64>().ok().filter(|v| v.is_finite()).map_or(Value::Real(0.0), Value::Real),
|
||||
Kind::Real => match t.parse::<f64>() {
|
||||
Ok(v) if v.is_finite() => Value::Real(v),
|
||||
_ => Value::Invalid(t.to_string()),
|
||||
},
|
||||
Kind::Int16 | Kind::Int32 | Kind::Int64 => {
|
||||
// A float spelling ("1e3", "12.0") is accepted when finite, clamped to what the
|
||||
// group's width holds, signed or unsigned (files write 16-bit flags up to 65535, as
|
||||
// the integer spelling reads them); NaN, inf and text become 0.
|
||||
// the integer spelling reads them); NaN, inf and non-numeric text become Value::Invalid.
|
||||
let (lo, hi) = match kind_of(code) {
|
||||
Kind::Int16 => (i64::from(i16::MIN), i64::from(u16::MAX)),
|
||||
Kind::Int32 => (i64::from(i32::MIN), i64::from(u32::MAX)),
|
||||
_ => (i64::MIN, i64::MAX),
|
||||
};
|
||||
t.parse::<i64>()
|
||||
.map_or_else(|_| Value::Int(t.parse::<f64>().ok().filter(|f| f.is_finite()).map_or(0, |f| (f as i64).clamp(lo, hi))), Value::Int)
|
||||
match t.parse::<i64>() {
|
||||
Ok(i) => Value::Int(i),
|
||||
Err(_) => match t.parse::<f64>() {
|
||||
Ok(f) if f.is_finite() => Value::Int((f as i64).clamp(lo, hi)),
|
||||
_ => Value::Invalid(t.to_string()),
|
||||
},
|
||||
}
|
||||
}
|
||||
Kind::Bool => Value::Bool(t.parse::<i64>().unwrap_or(0) != 0),
|
||||
Kind::Hex => Value::Hex(normalize_hex(t)),
|
||||
@@ -201,8 +274,9 @@ pub use codepage::decode_code_page;
|
||||
///
|
||||
/// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair,
|
||||
/// truncated binary data, or more group codes than the limit returned by [`max_tags()`], which is
|
||||
/// [`MAX_TAGS`] by default. For ASCII input, invalid numeric text becomes `0.0` for real values or
|
||||
/// `0` for integer values, and an EOF tag is not required.
|
||||
/// [`MAX_TAGS`] by default. For ASCII input, invalid numeric text is preserved as [`Value::Invalid`],
|
||||
/// and an EOF tag is not required. Numeric accessors ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or
|
||||
/// `0` for backward compatibility.
|
||||
pub fn parse(bytes: &[u8]) -> Result<Vec<Tag>> {
|
||||
parse_with_limit(bytes, max_tags())
|
||||
}
|
||||
@@ -255,7 +329,8 @@ fn count_ascii_pairs(bytes: &[u8]) -> usize {
|
||||
///
|
||||
/// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair,
|
||||
/// truncated binary data, or more than `max_tags` group codes. For ASCII input, invalid numeric
|
||||
/// text becomes `0.0` for real values or `0` for integer values, and an EOF tag is not required.
|
||||
/// text is preserved as [`Value::Invalid`], and an EOF tag is not required. Numeric accessors
|
||||
/// ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or `0` for backward compatibility.
|
||||
pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
|
||||
if let Some(body) = bytes.strip_prefix(BINARY_SENTINEL) {
|
||||
return parse_binary_with_limit(body, max_tags);
|
||||
@@ -404,7 +479,8 @@ fn byte_lines(mut rest: &[u8]) -> impl Iterator<Item = &[u8]> {
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair,
|
||||
/// or too many tags. Invalid numeric text becomes `0.0` for real values or `0` for integer values.
|
||||
/// or too many tags. Invalid numeric text is preserved as [`Value::Invalid`]. Numeric accessors
|
||||
/// ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or `0` for backward compatibility.
|
||||
/// A complete tag stream does not require an EOF tag.
|
||||
pub fn parse_ascii(text: &str) -> Result<Vec<Tag>> {
|
||||
parse_ascii_counted(text, max_tags(), 0)
|
||||
@@ -418,6 +494,21 @@ fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result<V
|
||||
ascii_tags(text, max_tags, expected, false).map(|(tags, _)| tags)
|
||||
}
|
||||
|
||||
fn unescape_invalid(code: i32, s: String) -> String {
|
||||
let unescaped = unescape_owned(s.clone());
|
||||
if unescaped == s {
|
||||
return s;
|
||||
}
|
||||
let becomes_valid_numeric = match kind_of(code) {
|
||||
Kind::Real => unescaped.trim().parse::<f64>().ok().filter(|v| v.is_finite()).is_some(),
|
||||
Kind::Int16 | Kind::Int32 | Kind::Int64 => {
|
||||
unescaped.trim().parse::<i64>().is_ok() || unescaped.trim().parse::<f64>().ok().filter(|f| f.is_finite()).is_some()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if becomes_valid_numeric { s } else { unescaped }
|
||||
}
|
||||
|
||||
/// The tags of ASCII DXF text. With `recover`, a line that is no group code, or a group code
|
||||
/// with no value after it, ends the reading instead of failing it: the tags before it are
|
||||
/// returned with the 1-based number of that line.
|
||||
@@ -450,6 +541,7 @@ fn ascii_tags(text: &str, max_tags: usize, expected: usize, recover: bool) -> Re
|
||||
let v = match typed(code, val) {
|
||||
// Only text with a backslash can hold an escape; the rest moves in as it is.
|
||||
Value::Str(s) => Value::Str(unescape_owned(s)),
|
||||
Value::Invalid(s) => Value::Invalid(unescape_invalid(code, s)),
|
||||
o => o,
|
||||
};
|
||||
let eof = code == 0 && matches!(&v, Value::Str(s) if s.trim_end() == "EOF");
|
||||
@@ -570,7 +662,10 @@ fn parse_binary_pass(b: &[u8], max_tags: usize, text: &mut codepage::BinaryText)
|
||||
};
|
||||
let v = match kind_of(code) {
|
||||
Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))),
|
||||
Kind::Real => Value::Real(Some(c.f64()?).filter(|v| v.is_finite()).unwrap_or(0.0)),
|
||||
Kind::Real => {
|
||||
let r = c.f64()?;
|
||||
if r.is_finite() { Value::Real(r) } else { Value::Invalid(r.to_string()) }
|
||||
}
|
||||
Kind::Int16 => Value::Int(i64::from(c.i16()?)),
|
||||
Kind::Int32 => Value::Int(i64::from(c.i32()?)),
|
||||
Kind::Int64 => Value::Int(c.i64()?),
|
||||
@@ -766,6 +861,7 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec<u8> {
|
||||
out.extend_from_slice(chunk.as_bytes());
|
||||
}
|
||||
}
|
||||
Value::Invalid(s) => push_string(s, strings, &mut out),
|
||||
}
|
||||
out.extend_from_slice(b"\r\n");
|
||||
}
|
||||
@@ -779,17 +875,36 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec<u8> {
|
||||
/// several groups of the same code). Strings are UTF-8 when `utf8` (R2007+), otherwise escaped as
|
||||
/// in [`write_ascii`]. A tag's value is converted to its code's kind, so a number written as text
|
||||
/// is stored as a number; a code outside the 16-bit range is skipped.
|
||||
pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec<u8> {
|
||||
binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) })
|
||||
///
|
||||
/// Invalid real values ([`Value::Invalid`]) are preserved across binary serialization using
|
||||
/// `f64::NAN`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`DxfError::InvalidInteger`] if any integer tag holds an invalid value ([`Value::Invalid`]),
|
||||
/// because binary DXF integer representations have no IEEE-754 non-finite sentinel. Callers who
|
||||
/// want invalid integers normalized to `0` can use [`write_binary_lossy`].
|
||||
pub fn write_binary(tags: &[Tag], utf8: bool) -> Result<Vec<u8>> {
|
||||
binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }, false)
|
||||
}
|
||||
|
||||
/// Write tags as pre-R2007 binary DXF with text in the code page `code_page` names, as
|
||||
/// [`write_ascii_in`] does.
|
||||
pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Vec<u8> {
|
||||
binary(tags, Strings::Escaped(codepage::encoder(code_page)))
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`DxfError::InvalidInteger`] if any integer tag holds an invalid value ([`Value::Invalid`]).
|
||||
pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Result<Vec<u8>> {
|
||||
binary(tags, Strings::Escaped(codepage::encoder(code_page)), false)
|
||||
}
|
||||
|
||||
fn binary(tags: &[Tag], strings: Strings) -> Vec<u8> {
|
||||
/// Write tags as binary DXF, normalizing invalid integer tags ([`Value::Invalid`]) to `0`
|
||||
/// instead of returning an error.
|
||||
pub fn write_binary_lossy(tags: &[Tag], utf8: bool) -> Vec<u8> {
|
||||
binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }, true).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn binary(tags: &[Tag], strings: Strings, normalize_invalid_integers: bool) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(BINARY_SENTINEL.len() + tags.len() * 12);
|
||||
out.extend_from_slice(BINARY_SENTINEL);
|
||||
for t in tags {
|
||||
@@ -809,19 +924,44 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec<u8> {
|
||||
}
|
||||
Kind::Real => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
out.extend_from_slice(&t.value.as_f64().to_le_bytes());
|
||||
let r = match &t.value {
|
||||
Value::Invalid(s) => s.parse::<f64>().unwrap_or(f64::NAN),
|
||||
_ => t.value.checked_f64().unwrap_or(0.0),
|
||||
};
|
||||
out.extend_from_slice(&r.to_le_bytes());
|
||||
}
|
||||
Kind::Int16 => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
out.extend_from_slice(&wrap_i16(t.value.as_i64()));
|
||||
let i = match t.value.checked_i64() {
|
||||
Some(i) => i,
|
||||
None if normalize_invalid_integers => 0,
|
||||
None => {
|
||||
return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() });
|
||||
}
|
||||
};
|
||||
out.extend_from_slice(&wrap_i16(i));
|
||||
}
|
||||
Kind::Int32 => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
out.extend_from_slice(&wrap_i32(t.value.as_i64()));
|
||||
let i = match t.value.checked_i64() {
|
||||
Some(i) => i,
|
||||
None if normalize_invalid_integers => 0,
|
||||
None => {
|
||||
return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() });
|
||||
}
|
||||
};
|
||||
out.extend_from_slice(&wrap_i32(i));
|
||||
}
|
||||
Kind::Int64 => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
out.extend_from_slice(&t.value.as_i64().to_le_bytes());
|
||||
let i = match t.value.checked_i64() {
|
||||
Some(i) => i,
|
||||
None if normalize_invalid_integers => 0,
|
||||
None => {
|
||||
return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() });
|
||||
}
|
||||
};
|
||||
out.extend_from_slice(&i.to_le_bytes());
|
||||
}
|
||||
Kind::Bool => {
|
||||
out.extend_from_slice(&code_bytes);
|
||||
@@ -842,7 +982,7 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec<u8> {
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Hex text cleaned up: only the hex digits are kept, and an odd trailing digit is padded with
|
||||
@@ -1219,6 +1359,137 @@ mod tests {
|
||||
assert_eq!(t[0].str(), expect, "{s:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_numeric_values_produce_value_invalid_and_preserve_compatibility() {
|
||||
let val = Value::Invalid("not_a_number".into());
|
||||
assert!(val.is_invalid());
|
||||
assert_eq!(val.invalid_str(), Some("not_a_number"));
|
||||
assert_eq!(val.as_str(), "not_a_number");
|
||||
assert_eq!(val.as_f64(), 0.0);
|
||||
assert_eq!(val.as_i64(), 0);
|
||||
|
||||
let tag = Tag::invalid(10, "NaN");
|
||||
assert!(tag.is_invalid());
|
||||
assert_eq!(tag.invalid_str(), Some("NaN"));
|
||||
assert_eq!(tag.str(), "NaN");
|
||||
assert_eq!(tag.str_ref(), None);
|
||||
assert_eq!(tag.f64(), 0.0);
|
||||
assert_eq!(tag.i64(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ascii_invalid_and_non_finite_reals() {
|
||||
let text = "10\nNaN\n20\ninf\n30\n-inf\n40\ngarbage\n50\n 12.34.56 \n0\nEOF\n";
|
||||
let tags = parse(text.as_bytes()).unwrap();
|
||||
assert_eq!(tags.len(), 6);
|
||||
|
||||
assert_eq!(tags[0], Tag::invalid(10, "NaN"));
|
||||
assert!(tags[0].is_invalid());
|
||||
assert_eq!(tags[0].f64(), 0.0);
|
||||
|
||||
assert_eq!(tags[1], Tag::invalid(20, "inf"));
|
||||
assert!(tags[1].is_invalid());
|
||||
assert_eq!(tags[1].f64(), 0.0);
|
||||
|
||||
assert_eq!(tags[2], Tag::invalid(30, "-inf"));
|
||||
assert!(tags[2].is_invalid());
|
||||
assert_eq!(tags[2].f64(), 0.0);
|
||||
|
||||
assert_eq!(tags[3], Tag::invalid(40, "garbage"));
|
||||
assert!(tags[3].is_invalid());
|
||||
assert_eq!(tags[3].f64(), 0.0);
|
||||
|
||||
assert_eq!(tags[4], Tag::invalid(50, "12.34.56"));
|
||||
assert!(tags[4].is_invalid());
|
||||
assert_eq!(tags[4].f64(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_reals_roundtrip_in_ascii_and_binary() {
|
||||
let tags = vec![Tag::invalid(10, "NaN"), Tag::invalid(20, "inf"), Tag::invalid(30, "malformed"), Tag::s(0, "EOF")];
|
||||
let ascii_out = write_ascii(&tags);
|
||||
let back_ascii = parse(ascii_out.as_bytes()).unwrap();
|
||||
assert_eq!(back_ascii[0], Tag::invalid(10, "NaN"));
|
||||
assert_eq!(back_ascii[1], Tag::invalid(20, "inf"));
|
||||
assert_eq!(back_ascii[2], Tag::invalid(30, "malformed"));
|
||||
|
||||
let bin_out = write_binary(&tags, true).unwrap();
|
||||
let back_bin = parse(&bin_out).unwrap();
|
||||
assert_eq!(back_bin[0], Tag::invalid(10, "NaN"));
|
||||
assert_eq!(back_bin[1], Tag::invalid(20, "inf"));
|
||||
// Invalid text that cannot be parsed as a float is preserved in binary DXF as NaN,
|
||||
// so it remains invalid rather than silently converting to genuine zero.
|
||||
assert_eq!(back_bin[2], Tag::invalid(30, "NaN"));
|
||||
assert_eq!(back_bin[2].f64(), 0.0);
|
||||
assert!(back_bin[2].is_invalid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_i64_bounds_enforced_including_exclusive_upper_bound() {
|
||||
// Inclusive lower bound: -2^63 fits
|
||||
assert_eq!(Value::Real(-9_223_372_036_854_775_808.0).checked_i64(), Some(i64::MIN));
|
||||
assert_eq!(Value::Str("-9223372036854775808".into()).checked_i64(), Some(i64::MIN));
|
||||
|
||||
// Adjacent decimal below lower bound: must not round to i64::MIN via float fallback
|
||||
assert_eq!(Value::Str("-9223372036854775809".into()).checked_i64(), None);
|
||||
|
||||
// Far below lower bound: does not fit
|
||||
assert_eq!(Value::Real(-1e30).checked_i64(), None);
|
||||
assert_eq!(Value::Str("-1e30".into()).checked_i64(), None);
|
||||
|
||||
// Inclusive upper bound: 2^63 - 1 fits
|
||||
assert_eq!(Value::Str("9223372036854775807".into()).checked_i64(), Some(i64::MAX));
|
||||
|
||||
// Exclusive upper bound / adjacent decimal above upper bound: does not fit
|
||||
assert_eq!(Value::Real(9_223_372_036_854_775_808.0).checked_i64(), None);
|
||||
assert_eq!(Value::Str("9223372036854775808".into()).checked_i64(), None);
|
||||
|
||||
// Just below exclusive upper bound: 2^63 - 2048 (largest representable f64 < 2^63)
|
||||
assert_eq!(Value::Real(9_223_372_036_854_774_784.0).checked_i64(), Some(9_223_372_036_854_774_784));
|
||||
|
||||
// Float syntax fallback still converts finite real strings within integer range
|
||||
assert_eq!(Value::Str("12.0".into()).checked_i64(), Some(12));
|
||||
assert_eq!(Value::Str("-12.0".into()).checked_i64(), Some(-12));
|
||||
assert_eq!(Value::Str("1e3".into()).checked_i64(), Some(1000));
|
||||
|
||||
// Normal values
|
||||
assert_eq!(Value::Real(42.0).checked_i64(), Some(42));
|
||||
assert_eq!(Value::Int(42).checked_i64(), Some(42));
|
||||
assert_eq!(Value::Invalid("foo".into()).checked_i64(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_numeric_escape_does_not_decode_into_valid_numeric_spelling() {
|
||||
let text = "10\n\\U+0030\n0\nEOF\n";
|
||||
let tags = parse(text.as_bytes()).unwrap();
|
||||
assert_eq!(tags[0], Tag::invalid(10, "\\U+0030"));
|
||||
assert!(tags[0].is_invalid());
|
||||
|
||||
// Roundtrip in ASCII preserves raw invalid escape and signal
|
||||
let ascii_out = write_ascii(&tags);
|
||||
let back_ascii = parse(ascii_out.as_bytes()).unwrap();
|
||||
assert_eq!(back_ascii[0], Tag::invalid(10, "\\U+0030"));
|
||||
assert!(back_ascii[0].is_invalid());
|
||||
|
||||
// Roundtrip in binary preserves invalid signal via NaN sentinel
|
||||
let bin_out = write_binary(&tags, true).unwrap();
|
||||
let back_bin = parse(&bin_out).unwrap();
|
||||
assert_eq!(back_bin[0], Tag::invalid(10, "NaN"));
|
||||
assert!(back_bin[0].is_invalid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_integer_writer_reports_error_unless_lossy_normalized() {
|
||||
let tags = vec![Tag::invalid(70, "corrupted"), Tag::s(0, "EOF")];
|
||||
// Checked write_binary returns error for invalid integer tag
|
||||
assert!(matches!(write_binary(&tags, true), Err(DxfError::InvalidInteger { code: 70, .. })));
|
||||
|
||||
// Explicit write_binary_lossy normalizes invalid integer to 0
|
||||
let lossy_bin = write_binary_lossy(&tags, true);
|
||||
let back = parse(&lossy_bin).unwrap();
|
||||
assert_eq!(back[0], Tag::i(70, 0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -9,7 +9,7 @@ fn group_code_255_is_an_ordinary_code_in_binary_dxf() {
|
||||
// Code 255 used to be read as an R12 escape (`FF 00 <code>`), so a file with that code could
|
||||
// not be read back.
|
||||
let tags = vec![Tag::s(255, "x"), Tag::s(0, "EOF")];
|
||||
let back = parse(&write_binary(&tags, true)).unwrap();
|
||||
let back = parse(&write_binary(&tags, true).unwrap()).unwrap();
|
||||
assert_eq!(back.len(), 2);
|
||||
assert_eq!((back[0].code, back[0].str()), (255, "x".to_string()));
|
||||
}
|
||||
@@ -117,7 +117,7 @@ fn escapes_next_to_other_text_and_backslashes() {
|
||||
assert_eq!(parse(&file).unwrap()[0].str(), "éA\\ ü");
|
||||
// And the writer keeps the literal text literal.
|
||||
let tags = [Tag::s(1, "é\\U+0041\\ ü"), Tag::s(0, "EOF")];
|
||||
assert_eq!(parse(&write_binary(&tags, true)).unwrap()[0].str(), "é\\U+0041\\ ü");
|
||||
assert_eq!(parse(&write_binary(&tags, true).unwrap()).unwrap()[0].str(), "é\\U+0041\\ ü");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -27,7 +27,7 @@ fn binary_converts_values_to_their_codes_kind() {
|
||||
// A number held as text at a numeric code, an out-of-range 16-bit value, a long chunk.
|
||||
let long = "AB".repeat(300);
|
||||
let tags = vec![Tag::s(70, "12"), Tag::i(62, 1 << 20), Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")];
|
||||
let back = parse(&write_binary(&tags, true)).unwrap();
|
||||
let back = parse(&write_binary(&tags, true).unwrap()).unwrap();
|
||||
assert_eq!(back[0], Tag::i(70, 12));
|
||||
assert_eq!(back[1], Tag::i(62, i64::from(i16::MAX)));
|
||||
let sizes: Vec<usize> = back.iter().filter(|t| t.code == 310).map(|t| t.str().len()).collect();
|
||||
@@ -36,7 +36,7 @@ fn binary_converts_values_to_their_codes_kind() {
|
||||
|
||||
#[test]
|
||||
fn hostile_binary_input_never_panics() {
|
||||
let good = write_binary(&sample(), true);
|
||||
let good = write_binary(&sample(), true).unwrap();
|
||||
// Every truncation, and every single-byte corruption of the body.
|
||||
for n in 0..good.len() {
|
||||
let _ = parse(good.get(..n).unwrap());
|
||||
|
||||
@@ -43,7 +43,7 @@ fn text_is_written_in_the_code_page() {
|
||||
];
|
||||
for (cp, text, raw) in cases {
|
||||
let tags = file(cp, text);
|
||||
for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] {
|
||||
for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] {
|
||||
assert!(contains(&bytes, raw), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes));
|
||||
assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}");
|
||||
}
|
||||
@@ -60,7 +60,7 @@ fn unknown_ascii_and_utf8_code_pages_are_pure_ascii() {
|
||||
assert!(bytes.is_ascii(), "{cp}");
|
||||
assert_eq!(bytes, write_ascii(&tags).into_bytes(), "{cp}");
|
||||
assert!(contains(&bytes, b"A\\U+00E7\\U+00E3o fim"), "{cp}");
|
||||
assert!(write_binary_in(&tags, cp).iter().all(u8::is_ascii), "{cp} binary");
|
||||
assert!(write_binary_in(&tags, cp).unwrap().iter().all(u8::is_ascii), "{cp} binary");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ fn code_page_bytes_that_are_valid_utf8_are_escaped_in_ascii() {
|
||||
assert!(ascii.is_ascii(), "{:?}", String::from_utf8_lossy(&ascii));
|
||||
assert!(contains(&ascii, b"\\U+0421\\U+0406"));
|
||||
assert_eq!(parse(&ascii).unwrap()[10].str(), "СІ");
|
||||
let binary = write_binary_in(&tags, "ANSI_1251");
|
||||
let binary = write_binary_in(&tags, "ANSI_1251").unwrap();
|
||||
assert!(contains(&binary, b"\xD1\xB2"));
|
||||
assert_eq!(parse(&binary).unwrap()[10].str(), "СІ");
|
||||
// Bytes that are not valid UTF-8 stay as they are.
|
||||
@@ -111,7 +111,7 @@ fn literal_escapes_survive_code_page_text() {
|
||||
[("ANSI_1252", "Ação \\U+00E9 \\M+183A4F"), ("ANSI_1251", "Слой \\U+0041"), ("ANSI_1251", "СІ \\U+0041"), ("ANSI_932", "表 \\M+1")]
|
||||
{
|
||||
let tags = file(cp, text);
|
||||
for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] {
|
||||
for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] {
|
||||
assert!(contains(&bytes, b"\\U+005C"), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes));
|
||||
assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}");
|
||||
}
|
||||
@@ -132,7 +132,7 @@ fn a_trail_byte_backslash_never_starts_an_escape() {
|
||||
];
|
||||
for (cp, text, written, never) in cases {
|
||||
let tags = file(cp, text);
|
||||
for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] {
|
||||
for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] {
|
||||
assert!(contains(&bytes, written), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes));
|
||||
assert!(!contains(&bytes, never), "{cp} {what}: a trail byte starts an escape");
|
||||
assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}");
|
||||
|
||||
@@ -42,7 +42,7 @@ fn writes_independently_specified_ascii_and_binary_bytes() {
|
||||
for utf8 in [false, true] {
|
||||
let tags = std::slice::from_ref(&tag);
|
||||
assert_eq!(write_ascii_as(tags, utf8).as_bytes(), ascii, "ASCII code {}", tag.code);
|
||||
assert_eq!(write_binary(tags, utf8), [SENTINEL, binary].concat(), "binary code {}", tag.code);
|
||||
assert_eq!(write_binary(tags, utf8).unwrap(), [SENTINEL, binary].concat(), "binary code {}", tag.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ fn integer_code_ranges_have_independent_binary_widths() {
|
||||
let expected = [SENTINEL, &code_bytes, &value_bytes[..width]].concat();
|
||||
let tags = [Tag::i(code, value)];
|
||||
for utf8 in [false, true] {
|
||||
assert_eq!(write_binary(&tags, utf8), expected, "code={code} value={value} utf8={utf8}");
|
||||
assert_eq!(write_binary(&tags, utf8).unwrap(), expected, "code={code} value={value} utf8={utf8}");
|
||||
}
|
||||
assert_eq!(parse(&expected).unwrap(), tags, "code={code} value={value}");
|
||||
}
|
||||
@@ -83,7 +83,7 @@ fn text_encoding_has_independent_wire_expectations() {
|
||||
let ascii = [b" 1\r\n".as_slice(), text, b"\r\n"].concat();
|
||||
let binary = [SENTINEL, b"\x01\0", text, b"\0"].concat();
|
||||
assert_eq!(write_ascii_as(&tags, unicode).as_bytes(), ascii, "utf8={unicode}");
|
||||
assert_eq!(write_binary(&tags, unicode), binary, "utf8={unicode}");
|
||||
assert_eq!(write_binary(&tags, unicode).unwrap(), binary, "utf8={unicode}");
|
||||
assert_eq!(parse(&ascii).unwrap(), tags);
|
||||
assert_eq!(parse(&binary).unwrap(), tags);
|
||||
}
|
||||
|
||||
@@ -13,17 +13,36 @@ fn bin_with(f: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_reals_that_are_not_finite_become_zero() {
|
||||
fn binary_reals_that_are_not_finite_become_invalid() {
|
||||
for bits in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
let b = bin_with(|b| {
|
||||
b.extend_from_slice(&10i16.to_le_bytes());
|
||||
b.extend_from_slice(&bits.to_le_bytes());
|
||||
});
|
||||
let tags = parse(&b).unwrap();
|
||||
assert_eq!(tags[0], Tag::f(10, 0.0), "{bits}");
|
||||
assert_eq!(tags[0], Tag::invalid(10, bits.to_string()), "{bits}");
|
||||
assert_eq!(tags[0].f64(), 0.0, "backward compatibility for f64: {bits}");
|
||||
assert_eq!(tags[0].i64(), 0, "backward compatibility for i64: {bits}");
|
||||
assert!(tags[0].is_invalid());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_path_coordinates_are_invalid_and_do_not_silently_snap_to_origin() {
|
||||
// Malformed line entity coordinates (groups 10, 20, 11, 21)
|
||||
let dxf = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n10\n100.0\n20\nNaN\n11\ncorrupted\n21\n200.0\n0\nENDSEC\n0\nEOF\n";
|
||||
let tags = parse(dxf).unwrap();
|
||||
let y0 = tags.iter().find(|t| t.code == 20).unwrap();
|
||||
let x1 = tags.iter().find(|t| t.code == 11).unwrap();
|
||||
assert_eq!(y0.value, Value::Invalid("NaN".into()));
|
||||
assert_eq!(x1.value, Value::Invalid("corrupted".into()));
|
||||
assert!(y0.is_invalid());
|
||||
assert!(x1.is_invalid());
|
||||
// Legacy callers still get 0.0
|
||||
assert_eq!(y0.f64(), 0.0);
|
||||
assert_eq!(x1.f64(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ascii_accepts_bom_and_cr_only_line_ends() {
|
||||
let want = vec![Tag::s(0, "SECTION"), Tag::s(2, "ENTITIES"), Tag::s(0, "ENDSEC"), Tag::s(0, "EOF")];
|
||||
@@ -107,19 +126,68 @@ fn trailing_spaces_keep_sections_and_eof() {
|
||||
#[test]
|
||||
fn integer_groups_reject_non_finite_and_clamp() {
|
||||
let t = parse(b"70\ninf\n70\nNaN\n70\n1e30\n70\n-1e30\n90\n1e30\n160\n1e30\n160\n-inf\n62\n12.0\n0\nEOF\n").unwrap();
|
||||
assert_eq!(t[0], Tag::i(70, 0));
|
||||
assert_eq!(t[1], Tag::i(70, 0));
|
||||
assert_eq!(t[0], Tag::invalid(70, "inf"));
|
||||
assert_eq!(t[0].i64(), 0);
|
||||
assert_eq!(t[1], Tag::invalid(70, "NaN"));
|
||||
assert_eq!(t[1].i64(), 0);
|
||||
// Clamped to what the group's width holds, unsigned values included (the binary writer
|
||||
// keeps up to 65535 and 4294967295 as their bit patterns).
|
||||
assert_eq!(t[2], Tag::i(70, i64::from(u16::MAX)));
|
||||
assert_eq!(t[3], Tag::i(70, i64::from(i16::MIN)));
|
||||
assert_eq!(t[4], Tag::i(90, i64::from(u32::MAX)));
|
||||
assert_eq!(t[5], Tag::i(160, i64::MAX));
|
||||
assert_eq!(t[6], Tag::i(160, 0));
|
||||
assert_eq!(t[6], Tag::invalid(160, "-inf"));
|
||||
assert_eq!(t[6].i64(), 0);
|
||||
assert_eq!(t[7], Tag::i(62, 12));
|
||||
assert_eq!(Value::Str("inf".into()).as_i64(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tag_f_non_finite_creates_invalid() {
|
||||
let nan_tag = Tag::f(10, f64::NAN);
|
||||
assert!(nan_tag.is_invalid());
|
||||
assert_eq!(nan_tag.f64(), 0.0);
|
||||
assert_eq!(nan_tag.checked_f64(), None);
|
||||
assert_eq!(nan_tag.checked_i64(), None);
|
||||
assert_eq!(nan_tag.invalid_str(), Some("NaN"));
|
||||
|
||||
let inf_tag = Tag::f(20, f64::INFINITY);
|
||||
assert!(inf_tag.is_invalid());
|
||||
assert_eq!(inf_tag.f64(), 0.0);
|
||||
assert_eq!(inf_tag.checked_f64(), None);
|
||||
assert_eq!(inf_tag.checked_i64(), None);
|
||||
assert_eq!(inf_tag.invalid_str(), Some("inf"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_numbers_with_dxf_escapes_roundtrip_through_ascii_write_and_parse() {
|
||||
let tags =
|
||||
vec![Tag::invalid(10, "12.34\\U+0020xyz"), Tag::invalid(20, "bad\\U+005Cpath"), Tag::invalid(70, "corrupted\\U+0041"), Tag::s(0, "EOF")];
|
||||
let ascii_out = write_ascii(&tags);
|
||||
let back = parse(ascii_out.as_bytes()).unwrap();
|
||||
assert_eq!(back[0], Tag::invalid(10, "12.34\\U+0020xyz"));
|
||||
assert_eq!(back[1], Tag::invalid(20, "bad\\U+005Cpath"));
|
||||
assert_eq!(back[2], Tag::invalid(70, "corrupted\\U+0041"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_integer_writer_reports_error_unless_lossy_normalized() {
|
||||
let invalid_int_tag = Tag::invalid(70, "corrupted");
|
||||
assert!(invalid_int_tag.is_invalid());
|
||||
assert_eq!(invalid_int_tag.checked_i64(), None);
|
||||
assert_eq!(invalid_int_tag.i64(), 0);
|
||||
|
||||
// Binary DXF integer groups have no NaN marker, so write_binary reports conversion error
|
||||
let res = write_binary(&[invalid_int_tag.clone(), Tag::s(0, "EOF")], true);
|
||||
assert!(matches!(res, Err(craft_dxf::DxfError::InvalidInteger { code: 70, .. })));
|
||||
|
||||
// Explicit write_binary_lossy normalizes invalid integer to 0
|
||||
let lossy_bin = craft_dxf::write_binary_lossy(&[invalid_int_tag, Tag::s(0, "EOF")], true);
|
||||
let back = parse(&lossy_bin).unwrap();
|
||||
assert_eq!(back[0], Tag::i(70, 0));
|
||||
assert_eq!(back[0].checked_i64(), Some(0));
|
||||
}
|
||||
|
||||
/// An unsigned value spelled as a float reads as the same spelled as an integer (#1026 review):
|
||||
/// `65535.0` is 65535 like `65535`, not 32767.
|
||||
#[test]
|
||||
@@ -139,7 +207,7 @@ fn hex_groups_pad_odd_digits_and_drop_junk() {
|
||||
assert_eq!(t[2].value, Value::Hex(String::new()));
|
||||
assert_eq!(t[3].value, Value::Hex("0aF0".into()));
|
||||
// The binary writer agrees with the reader: the odd digit is padded, nothing shifts.
|
||||
let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true)).unwrap();
|
||||
let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true).unwrap()).unwrap();
|
||||
assert_eq!(back[0].value, Value::Hex("ABC0".into()));
|
||||
}
|
||||
|
||||
@@ -171,7 +239,7 @@ fn binary_sixteen_and_thirty_two_bit_values_wrap_in_range_and_clamp_outside() {
|
||||
Tag::i(90, -(1 << 40)),
|
||||
Tag::s(0, "EOF"),
|
||||
];
|
||||
let back = parse(&write_binary(&tags, true)).unwrap();
|
||||
let back = parse(&write_binary(&tags, true).unwrap()).unwrap();
|
||||
assert_eq!(back[0], Tag::i(70, -1));
|
||||
assert_eq!(back[1], Tag::i(70, 40000 - 65536));
|
||||
assert_eq!(back[2], Tag::i(70, i64::from(i16::MAX)));
|
||||
|
||||
@@ -52,7 +52,7 @@ fn check_ascii(code: i32, bytes: &[u8], utf8: bool) {
|
||||
}
|
||||
|
||||
fn check_binary(code: i32, bytes: &[u8], utf8: bool) {
|
||||
let wire = write_binary(&input(code, bytes), utf8);
|
||||
let wire = write_binary(&input(code, bytes), utf8).unwrap();
|
||||
let mut chunks = wire.strip_prefix(SENTINEL).unwrap().strip_suffix(FOLLOWING_BINARY).unwrap();
|
||||
assert!(!chunks.is_empty(), "an empty payload must still have a tag");
|
||||
let context = format!("binary code={code} bytes={} utf8={utf8}", bytes.len());
|
||||
|
||||
@@ -10,7 +10,7 @@ fn an_intact_file_reads_as_parse_reads_it() {
|
||||
assert_eq!(damaged, None);
|
||||
assert_eq!(tags, parse(WHOLE.as_bytes()).expect("reads"));
|
||||
// Binary files are read as before.
|
||||
let binary = write_binary(&tags, true);
|
||||
let binary = write_binary(&tags, true).unwrap();
|
||||
assert_eq!(parse_recovering(&binary).expect("reads"), (tags, None));
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,8 @@ fn check(case: &str, body: &[Tag]) {
|
||||
let mut current = original.clone();
|
||||
for pass in 1..=2 {
|
||||
let context = format!("{case} · {version} · binary={binary} · pass={pass}");
|
||||
let bytes = if binary { write_binary(¤t, version.utf8()) } else { write_ascii_as(¤t, version.utf8()).into_bytes() };
|
||||
let bytes =
|
||||
if binary { write_binary(¤t, version.utf8()).unwrap() } else { write_ascii_as(¤t, version.utf8()).into_bytes() };
|
||||
assert_eq!(is_binary(&bytes), binary, "{context}");
|
||||
let back = parse(&bytes).unwrap_or_else(|e| panic!("{context}: {e}"));
|
||||
assert_eq!(back.len(), original.len(), "{context}: tag count");
|
||||
|
||||
@@ -18,6 +18,7 @@ decode = ["dep:exr", "dep:half", "dep:thiserror", "zlib-inflate"]
|
||||
zlib-inflate = ["dep:flate2"]
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
exr = { version = "1.73", default-features = false, optional = true }
|
||||
half = { version = "2", optional = true }
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! sample type, over the part's data window. Every compression the `exr` crate reads is read,
|
||||
//! scan lines and tiles alike (the largest resolution level). Other parts' chunks are skipped
|
||||
//! unread, and channels the filter drops are never allocated. Other parts may be deep.
|
||||
//! - [`fn@write`] writes one scan-line part.
|
||||
//! - [`fn@write`] writes one scan-line part. [`crate::write`] accepts rows incrementally for one
|
||||
//! or more parts.
|
||||
//!
|
||||
//! The `exr` crate sizes buffers from headers before it reads pixels, so everything that reaches
|
||||
//! it is checked first: preview attributes against their own size, each part's samples against
|
||||
@@ -65,6 +66,10 @@ fn map_exr(e: exr::error::Error) -> Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most attributes one header may hold, standard ones included. The readers refuse a header
|
||||
/// above it and the writer refuses to produce one.
|
||||
pub(crate) const MAX_HEADER_ATTRIBUTES: usize = 4096;
|
||||
|
||||
/// Caps on what a file may ask the reader to allocate. `#[non_exhaustive]`: start from
|
||||
/// [`Limits::default`] and set the fields you change.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -1072,7 +1077,7 @@ pub enum SampleDepth {
|
||||
Half,
|
||||
}
|
||||
|
||||
fn to_exr_compression(compression: Compression) -> ExrCompression {
|
||||
pub(crate) fn to_exr_compression(compression: Compression) -> ExrCompression {
|
||||
match compression {
|
||||
Compression::None => ExrCompression::Uncompressed,
|
||||
Compression::Rle => ExrCompression::RLE,
|
||||
|
||||
@@ -351,7 +351,16 @@ fn limits_are_checked_from_the_headers() {
|
||||
// is over; the 1 MiB slack always admits small pictures.
|
||||
assert!(ok(Limits { max_ratio: 0, ..d }));
|
||||
// A header claiming a huge data window over a few bytes of file is refused by the ratio.
|
||||
let big = file(vec![layer(None, 4096, 4096, &["R"], false, exr::prelude::Compression::ZIP16)], (4096, 4096));
|
||||
// Only headers are read here: keep the large declared windows without encoding their pixels.
|
||||
let mut big = file(vec![layer(None, 8, 4, &["R"], false, exr::prelude::Compression::ZIP16)], (8, 4));
|
||||
let window: Vec<u8> = [0i32, 0, 4095, 4095].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
for tag in ["dataWindow\0box2i\0", "displayWindow\0box2i\0"] {
|
||||
let tag = tag.as_bytes();
|
||||
let at = big.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len() + 4;
|
||||
big[at..at + 16].copy_from_slice(&window);
|
||||
}
|
||||
// At 1024 file bytes the default ratio admits 64 MiB, but ratio 1 plus 1 MiB slack does not.
|
||||
big.resize(1024, 0);
|
||||
assert!(ok_big(&big));
|
||||
assert!(matches!(parts(&big, &Limits { max_ratio: 1, ..d }), Err(Error::LimitExceeded(_))));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
//! The optional `craftLayerStack` string attribute describes an editable raster layer stack.
|
||||
//! The EXR remains readable as an ordinary image without this attribute. Version 1 is an
|
||||
//! ASCII-safe JSON object. Layer array order is bottom-to-top within each parent. The beauty
|
||||
//! image and other passes can be stored in EXR parts or channels outside the manifest.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::{self, Write};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const ATTRIBUTE_NAME: &str = "craftLayerStack";
|
||||
pub const MAX_ATTRIBUTE_BYTES: usize = 1 << 20;
|
||||
const VERSION: u64 = 1;
|
||||
const MAX_LAYERS: usize = 4096;
|
||||
const MAX_GROUP_DEPTH: usize = 100;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Limit(&'static str),
|
||||
Malformed(&'static str),
|
||||
Json(serde_json::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{ATTRIBUTE_NAME}: ")?;
|
||||
match self {
|
||||
Self::Limit(message) | Self::Malformed(message) => f.write_str(message),
|
||||
Self::Json(error) => error.fmt(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct LayerStack {
|
||||
pub layers: Vec<Layer>,
|
||||
/// The producer's original RGB compositing encoding. A portable profile ID or
|
||||
/// `icc:<base64>` describing an ICC profile. EXR chromaticities describe the stored pixels.
|
||||
pub original_blend_profile: Option<String>,
|
||||
/// The producer's document sample depth before conversion to EXR channels.
|
||||
pub original_sample_depth: Option<SampleDepth>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SampleDepth {
|
||||
U8,
|
||||
U16,
|
||||
F32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Layer {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<u64>,
|
||||
pub visible: bool,
|
||||
/// Portable blend mode identifier. Consumers may warn and use Normal for unsupported modes.
|
||||
pub blend: String,
|
||||
pub opacity: f32,
|
||||
pub fill_opacity: f32,
|
||||
pub clipped: bool,
|
||||
pub content: LayerContent,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum LayerContent {
|
||||
Group,
|
||||
Raster { pixels: PixelRef, sampling: PixelSampling },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub enum PixelRef {
|
||||
/// A named, flat EXR part. Use part names that are unique within the file.
|
||||
Part { name: String },
|
||||
/// The exact prefix of the RGB(A) channels in the zero-based flat EXR part.
|
||||
/// An empty prefix selects unprefixed channels such as `R`, `G` and `B`.
|
||||
ChannelGroup { part: u32, prefix: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PixelSampling {
|
||||
/// Raster pixels from the source layer.
|
||||
Raw,
|
||||
/// Raster pixels derived by rendering the source layer. Transforms, effects or masks may
|
||||
/// be baked into the pixels. The manifest's stack compositing properties still apply.
|
||||
Baked,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Version {
|
||||
version: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct Input {
|
||||
version: u64,
|
||||
layers: Vec<Layer>,
|
||||
original_blend_profile: Option<String>,
|
||||
original_sample_depth: Option<SampleDepth>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Output<'a> {
|
||||
version: u64,
|
||||
layers: &'a [Layer],
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
original_blend_profile: Option<&'a str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
original_sample_depth: Option<SampleDepth>,
|
||||
}
|
||||
|
||||
impl LayerStack {
|
||||
/// Parse the attribute, returning `None` for an unsupported version. A caller can still
|
||||
/// open the EXR as a flat image in that case.
|
||||
pub fn parse(text: &str) -> Result<Option<Self>, Error> {
|
||||
if text.len() > MAX_ATTRIBUTE_BYTES {
|
||||
return Err(Error::Limit("attribute is too large"));
|
||||
}
|
||||
if !text.trim_start().starts_with('{') {
|
||||
return Err(Error::Malformed("expected a JSON object"));
|
||||
}
|
||||
let version = serde_json::from_str::<Version>(text).map_err(Error::Json)?.version;
|
||||
if version != VERSION {
|
||||
return Ok(None);
|
||||
}
|
||||
let Input { version, layers, original_blend_profile, original_sample_depth } = serde_json::from_str(text).map_err(Error::Json)?;
|
||||
if version != VERSION {
|
||||
return Ok(None);
|
||||
}
|
||||
let stack = Self { layers, original_blend_profile, original_sample_depth };
|
||||
stack.validate()?;
|
||||
Ok(Some(stack))
|
||||
}
|
||||
|
||||
/// Validate and serialize version 1. Unicode layer names are escaped to keep the EXR
|
||||
/// header ASCII-safe.
|
||||
pub fn to_attribute(&self) -> Result<String, Error> {
|
||||
self.validate()?;
|
||||
let json = serde_json::to_string(&Output {
|
||||
version: VERSION,
|
||||
layers: &self.layers,
|
||||
original_blend_profile: self.original_blend_profile.as_deref(),
|
||||
original_sample_depth: self.original_sample_depth,
|
||||
})
|
||||
.map_err(Error::Json)?;
|
||||
if json.len() > MAX_ATTRIBUTE_BYTES {
|
||||
return Err(Error::Limit("attribute is too large"));
|
||||
}
|
||||
let mut text = String::with_capacity(json.len());
|
||||
for c in json.chars() {
|
||||
if c.is_ascii() {
|
||||
text.push(c);
|
||||
} else {
|
||||
for unit in c.encode_utf16(&mut [0; 2]) {
|
||||
write!(text, "\\u{unit:04x}").map_err(|_| Error::Limit("could not encode attribute text"))?;
|
||||
}
|
||||
}
|
||||
if text.len() > MAX_ATTRIBUTE_BYTES {
|
||||
return Err(Error::Limit("attribute is too large"));
|
||||
}
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// Check the manifest's intrinsic constraints. Consumers check its pixel references
|
||||
/// against the file headers before decoding.
|
||||
pub fn validate(&self) -> Result<(), Error> {
|
||||
if self.layers.len() > MAX_LAYERS {
|
||||
return Err(Error::Limit("too many layers"));
|
||||
}
|
||||
if self.original_blend_profile.as_deref().is_some_and(|profile| !valid_profile(profile)) {
|
||||
return Err(Error::Malformed("invalid original RGB blend profile"));
|
||||
}
|
||||
let mut text_bytes = self.original_blend_profile.as_ref().map_or(0, String::len);
|
||||
let mut by_id = HashMap::with_capacity(self.layers.len());
|
||||
for layer in &self.layers {
|
||||
if by_id.insert(layer.id, layer).is_some() {
|
||||
return Err(Error::Malformed("duplicate layer ID"));
|
||||
}
|
||||
if layer.name.len() > 4096 {
|
||||
return Err(Error::Limit("layer name is too large"));
|
||||
}
|
||||
if !valid_label(&layer.blend) {
|
||||
return Err(Error::Malformed("invalid blend mode identifier"));
|
||||
}
|
||||
if !(0.0..=1.0).contains(&layer.opacity) || !(0.0..=1.0).contains(&layer.fill_opacity) {
|
||||
return Err(Error::Malformed("opacity and fill opacity must be between zero and one"));
|
||||
}
|
||||
text_bytes = text_bytes.saturating_add(layer.name.len()).saturating_add(layer.blend.len());
|
||||
if let LayerContent::Raster { pixels, .. } = &layer.content {
|
||||
let (name, min, max) = match pixels {
|
||||
PixelRef::Part { name } => (name, 1, 255),
|
||||
PixelRef::ChannelGroup { prefix, .. } => (prefix, 0, 253),
|
||||
};
|
||||
if !(min..=max).contains(&name.chars().count()) || name.chars().any(|c| c.is_control() || u32::from(c) > 255) {
|
||||
return Err(Error::Malformed("invalid EXR part or channel group name"));
|
||||
}
|
||||
text_bytes = text_bytes.saturating_add(name.len());
|
||||
}
|
||||
if text_bytes > MAX_ATTRIBUTE_BYTES {
|
||||
return Err(Error::Limit("attribute is too large"));
|
||||
}
|
||||
}
|
||||
for layer in &self.layers {
|
||||
let mut at = layer;
|
||||
let mut depth = 0;
|
||||
while let Some(parent) = at.parent {
|
||||
let ancestor = by_id.get(&parent).ok_or(Error::Malformed("unknown parent layer"))?;
|
||||
if ancestor.content != LayerContent::Group {
|
||||
return Err(Error::Malformed("a parent layer must be a group"));
|
||||
}
|
||||
if ancestor.id == layer.id {
|
||||
return Err(Error::Malformed("cyclic layer hierarchy"));
|
||||
}
|
||||
depth += 1;
|
||||
if depth > MAX_GROUP_DEPTH {
|
||||
return Err(Error::Limit("layer hierarchy is too deep"));
|
||||
}
|
||||
at = ancestor;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_label(label: &str) -> bool {
|
||||
!label.trim().is_empty() && label.len() <= 128 && label.bytes().all(|b| b == b' ' || b.is_ascii_graphic())
|
||||
}
|
||||
|
||||
fn valid_profile(profile: &str) -> bool {
|
||||
if let Some(encoded) = profile.strip_prefix("icc:") {
|
||||
if encoded.is_empty() || encoded.len() > MAX_ATTRIBUTE_BYTES || !encoded.len().is_multiple_of(4) {
|
||||
return false;
|
||||
}
|
||||
let data = encoded.trim_end_matches('=');
|
||||
!data.is_empty() && encoded.len() - data.len() <= 2 && data.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/'))
|
||||
} else {
|
||||
valid_label(profile)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn stack() -> LayerStack {
|
||||
LayerStack {
|
||||
layers: vec![
|
||||
Layer {
|
||||
id: u64::MAX,
|
||||
name: "東京 🎞".into(),
|
||||
parent: Some(8),
|
||||
visible: false,
|
||||
blend: "multiply".into(),
|
||||
opacity: 0.4,
|
||||
fill_opacity: 0.5,
|
||||
clipped: true,
|
||||
content: LayerContent::Raster { pixels: PixelRef::Part { name: "Layer".into() }, sampling: PixelSampling::Baked },
|
||||
},
|
||||
Layer {
|
||||
id: 8,
|
||||
name: "Group".into(),
|
||||
parent: None,
|
||||
visible: true,
|
||||
blend: "passThrough".into(),
|
||||
opacity: 1.0,
|
||||
fill_opacity: 1.0,
|
||||
clipped: false,
|
||||
content: LayerContent::Group,
|
||||
},
|
||||
],
|
||||
original_blend_profile: Some("icc:AAE=".into()),
|
||||
original_sample_depth: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_and_compositing_fields_round_trip_through_an_ascii_attribute() {
|
||||
let stack = stack();
|
||||
let encoded = stack.to_attribute().unwrap();
|
||||
assert!(encoded.is_ascii());
|
||||
assert_eq!(LayerStack::parse(&encoded).unwrap(), Some(stack));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn original_sample_depth_is_optional_in_version_one() {
|
||||
let old = r#"{"version":1,"layers":[]}"#;
|
||||
let stack = LayerStack::parse(old).unwrap().unwrap();
|
||||
assert_eq!(stack.original_sample_depth, None);
|
||||
assert_eq!(stack.to_attribute().unwrap(), old);
|
||||
|
||||
for (depth, wire) in [(SampleDepth::U8, "u8"), (SampleDepth::U16, "u16"), (SampleDepth::F32, "f32")] {
|
||||
let stack = LayerStack { original_sample_depth: Some(depth), ..stack.clone() };
|
||||
let text = format!(r#"{{"version":1,"layers":[],"originalSampleDepth":"{wire}"}}"#);
|
||||
assert_eq!(stack.to_attribute().unwrap(), text);
|
||||
assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack));
|
||||
}
|
||||
assert!(LayerStack::parse(r#"{"version":1,"layers":[],"originalSampleDepth":"f16"}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_channel_group_prefix_round_trips_but_empty_part_name_is_invalid() {
|
||||
let mut stack = stack();
|
||||
stack.layers[0].content =
|
||||
LayerContent::Raster { pixels: PixelRef::ChannelGroup { part: 0, prefix: String::new() }, sampling: PixelSampling::Raw };
|
||||
let text = stack.to_attribute().unwrap();
|
||||
assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack.clone()));
|
||||
|
||||
stack.layers[0].content = LayerContent::Raster { pixels: PixelRef::Part { name: String::new() }, sampling: PixelSampling::Raw };
|
||||
assert!(matches!(stack.to_attribute(), Err(Error::Malformed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_a_raster_inside_one_hundred_groups() {
|
||||
let mut stack = stack();
|
||||
let group = stack.layers[1].clone();
|
||||
stack.layers.truncate(1);
|
||||
stack.layers[0].parent = Some(100);
|
||||
for id in 1..=100 {
|
||||
stack.layers.push(Layer { id, parent: (id > 1).then_some(id - 1), ..group.clone() });
|
||||
}
|
||||
let text = stack.to_attribute().unwrap();
|
||||
assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack.clone()));
|
||||
|
||||
stack.layers.push(Layer { id: 101, parent: Some(100), ..group });
|
||||
stack.layers[0].parent = Some(101);
|
||||
assert!(matches!(stack.to_attribute(), Err(Error::Limit(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_flat_image_fallback_for_unknown_versions_and_rejects_bad_v1() {
|
||||
assert!(LayerStack::parse(r#"{"version":2,"layout":{"different":true}}"#).unwrap().is_none());
|
||||
for text in [
|
||||
r#"{"version":1,"layers":[],"unexpected":null}"#,
|
||||
r#"{"version":1,"version":2,"layers":[]}"#,
|
||||
r#"{"version":1,"layers":[],"originalBlendProfile":"icc:abc?"}"#,
|
||||
r#"{"version":"1","layers":[]}"#,
|
||||
] {
|
||||
assert!(LayerStack::parse(text).is_err(), "{text}");
|
||||
}
|
||||
assert!(matches!(LayerStack::parse(&" ".repeat(MAX_ATTRIBUTE_BYTES + 1)), Err(Error::Limit(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ambiguous_identity_invalid_opacity_and_bad_hierarchy() {
|
||||
let mut s = stack();
|
||||
s.layers[0].id = 8;
|
||||
assert!(s.to_attribute().is_err());
|
||||
let mut s = stack();
|
||||
s.layers[0].fill_opacity = f32::NAN;
|
||||
assert!(s.to_attribute().is_err());
|
||||
let mut s = stack();
|
||||
s.layers[1].parent = Some(8);
|
||||
assert!(s.to_attribute().is_err());
|
||||
let mut s = stack();
|
||||
s.layers[1].parent = Some(u64::MAX);
|
||||
assert!(s.to_attribute().is_err());
|
||||
let mut s = stack();
|
||||
s.layers[0].parent = Some(9);
|
||||
assert!(s.to_attribute().is_err());
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
//! and alpha.
|
||||
//! - [`cryptomatte`]: Cryptomatte (specification 1.2) IDs, metadata keys, manifests and rank
|
||||
//! channel names.
|
||||
//! - [`layer_stack`]: optional layer hierarchy and compositing metadata for editable EXR exchange.
|
||||
//!
|
||||
//! Those take names and attribute text and depend on no decoder. With the `decode` feature:
|
||||
//!
|
||||
@@ -18,6 +19,7 @@
|
||||
//! - `seek`: any channels, display rows and reduced resolution of a file's flat parts, read from
|
||||
//! a seekable source and delivered band by band (or collected into planes).
|
||||
//! - `stream`: one flat scan-line part read block by block, for pictures larger than memory.
|
||||
//! - `write`: write flat scan-line parts from a row callback to a seekable destination.
|
||||
//! - `cryptomatte_samples`: a file's Cryptomatte layers and their per-pixel (ID, coverage) ranks.
|
||||
|
||||
/// Bounded RLE expansion and inverse byte prediction for EXR blocks.
|
||||
@@ -53,9 +55,14 @@ pub mod deep;
|
||||
mod deep_tests;
|
||||
#[cfg(feature = "decode")]
|
||||
mod dwa_guard;
|
||||
pub mod layer_stack;
|
||||
#[cfg(feature = "decode")]
|
||||
pub mod seek;
|
||||
#[cfg(all(test, feature = "decode"))]
|
||||
mod seek_tests;
|
||||
#[cfg(feature = "decode")]
|
||||
pub mod stream;
|
||||
#[cfg(feature = "decode")]
|
||||
pub mod write;
|
||||
#[cfg(all(test, feature = "decode"))]
|
||||
mod write_tests;
|
||||
+57
-18
@@ -60,7 +60,7 @@ use exr::meta::MetaData;
|
||||
use exr::meta::attribute::SampleType as ExrSample;
|
||||
use exr::meta::header::Header;
|
||||
|
||||
use crate::decode::{Limits, PartInfo, Window, check_previews, part_info};
|
||||
use crate::decode::{Limits, MAX_HEADER_ATTRIBUTES, PartInfo, Window, check_previews, part_info};
|
||||
|
||||
/// Why a read failed. More kinds may be added: a `match` needs a catch-all arm.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
@@ -119,10 +119,10 @@ fn exr_error(e: exr::error::Error) -> Error {
|
||||
}
|
||||
|
||||
const MAGIC: [u8; 4] = [0x76, 0x2f, 0x31, 0x01];
|
||||
/// Headers of all parts together: at most this many bytes, parts, and attributes per part.
|
||||
/// Headers of all parts together: at most this many bytes and parts. Attributes per header are
|
||||
/// bounded by `MAX_HEADER_ATTRIBUTES`.
|
||||
const META_BYTES: usize = 8 << 20;
|
||||
const MAX_PARTS: usize = 1024;
|
||||
const MAX_ATTRIBUTES: usize = 4096;
|
||||
/// The most chunks all parts of a file may have together. The offset tables and the index hold
|
||||
/// a few bytes per chunk, so a header declaring billions of tiny tiles (whose tables a short file
|
||||
/// can't hold anyway) is refused before anything is sized by it. 16 million chunks is a 64K ×
|
||||
@@ -293,6 +293,13 @@ impl Index {
|
||||
self.display
|
||||
}
|
||||
|
||||
/// Stored RGB primaries and white point (red, green, blue, white in CIE xy), from the first
|
||||
/// part that supplies the shared chromaticities attribute.
|
||||
pub fn chromaticities(&self) -> Option<[[f32; 2]; 4]> {
|
||||
let c = self.meta.headers.iter().find_map(|header| header.shared_attributes.chromaticities.as_ref())?;
|
||||
Some([c.red, c.green, c.blue, c.white].map(|v| [v.0, v.1]))
|
||||
}
|
||||
|
||||
/// The chunks of part `part`'s full-resolution level, in offset-table order (none for a deep
|
||||
/// part or a part that doesn't exist): where each lies in the file and which pixels of the
|
||||
/// part's data window it holds. For diagnostics and tests; [`read_bands`] picks the chunks a
|
||||
@@ -386,8 +393,8 @@ fn read_headers<R: Read + ?Sized>(r: &mut R, cancel: &dyn Fn() -> bool) -> Resul
|
||||
break;
|
||||
}
|
||||
attributes += 1;
|
||||
if attributes > MAX_ATTRIBUTES {
|
||||
return Err(Error::LimitExceeded("more than 4096 attributes in a header".into()));
|
||||
if attributes > MAX_HEADER_ATTRIBUTES {
|
||||
return Err(Error::LimitExceeded(format!("more than {MAX_HEADER_ATTRIBUTES} attributes in a header")));
|
||||
}
|
||||
read_name(r, &mut prefix, None)?;
|
||||
let mut size = [0u8; 4];
|
||||
@@ -606,11 +613,14 @@ pub struct Request<'a> {
|
||||
/// them. A channel may be named more than once (each slot gets its own bands). A channel of a
|
||||
/// deep part is refused.
|
||||
pub channels: &'a [(usize, usize)],
|
||||
/// Use this part's data window as the output grid, keeping samples beyond the display
|
||||
/// window. Every requested channel must belong to this part. Default: the display window.
|
||||
pub data_window: Option<usize>,
|
||||
/// The value of each requested channel (same order) where the file has no samples; missing
|
||||
/// entries count as 0. Only [`read_planes`] uses it ([`read_bands`] delivers samples only).
|
||||
pub fill: &'a [f32],
|
||||
/// The rows to read, counted from the display window's top row (0, whatever the display
|
||||
/// window's absolute position), at full resolution; `None`: all.
|
||||
/// The rows to read, counted from the output window's top row, at full resolution.
|
||||
/// `None`: all rows.
|
||||
pub rows: Option<Range<i64>>,
|
||||
/// Every `2^level`-th row and column of the display window (0: full resolution, at most 16).
|
||||
pub level: u32,
|
||||
@@ -644,7 +654,7 @@ impl<'a> Request<'a> {
|
||||
/// Every row of `channels` at full resolution, fill 0, up to `max_bytes` of samples, with as
|
||||
/// many decoding threads as the machine runs at once.
|
||||
pub fn new(channels: &'a [(usize, usize)], max_bytes: usize) -> Request<'a> {
|
||||
Request { channels, fill: &[], rows: None, level: 0, max_bytes, workers: None, max_block_bytes: None, groups: &[] }
|
||||
Request { channels, data_window: None, fill: &[], rows: None, level: 0, max_bytes, workers: None, max_block_bytes: None, groups: &[] }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -657,7 +667,7 @@ pub fn level_size((width, height): (usize, usize), level: u32) -> (usize, usize)
|
||||
/// A rectangle of rows of one requested channel, or of a group of them ([`Request::groups`]),
|
||||
/// decoded: `samples` holds `height` rows of `width` pixels, row by row, each pixel
|
||||
/// `values_per_pixel` values in slot order. `x` and `y` are in the output grid, counted from the
|
||||
/// display window's top-left corner (0, 0, not its absolute position): display-window pixels at
|
||||
/// selected window's top-left corner (0, 0, whatever its absolute position): window pixels at
|
||||
/// level 0, every `2^level`-th pixel above.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Band {
|
||||
@@ -761,6 +771,7 @@ struct Geometry<'a> {
|
||||
size: (usize, usize),
|
||||
out: (usize, usize),
|
||||
stride: i64,
|
||||
in_data_window: bool,
|
||||
/// The display rows read.
|
||||
rows: Range<i64>,
|
||||
/// Each part's channel → the request slots that name it.
|
||||
@@ -771,6 +782,10 @@ struct Geometry<'a> {
|
||||
}
|
||||
|
||||
impl Geometry<'_> {
|
||||
fn offset(&self, part: &PartLayout) -> (i64, i64) {
|
||||
if self.in_data_window { (0, 0) } else { part.offset }
|
||||
}
|
||||
|
||||
/// A display row is read: in the rows, on the level's grid.
|
||||
fn wanted(&self, row: i64) -> bool {
|
||||
row >= self.rows.start && row < self.rows.end && row.rem_euclid(self.stride) == 0
|
||||
@@ -810,6 +825,7 @@ struct Plan {
|
||||
size: (usize, usize),
|
||||
out: (usize, usize),
|
||||
stride: i64,
|
||||
in_data_window: bool,
|
||||
rows: Range<i64>,
|
||||
/// The chunks to read, in file order.
|
||||
jobs: Vec<Planned>,
|
||||
@@ -821,7 +837,26 @@ struct Plan {
|
||||
|
||||
impl Plan {
|
||||
fn geometry(&self) -> Geometry<'_> {
|
||||
Geometry { size: self.size, out: self.out, stride: self.stride, rows: self.rows.clone(), slots: &self.slots, units: &self.units }
|
||||
Geometry {
|
||||
size: self.size,
|
||||
out: self.out,
|
||||
stride: self.stride,
|
||||
in_data_window: self.in_data_window,
|
||||
rows: self.rows.clone(),
|
||||
slots: &self.slots,
|
||||
units: &self.units,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request_window(index: &Index, request: &Request) -> Result<Window> {
|
||||
if let Some(part) = request.data_window {
|
||||
if request.channels.iter().any(|(p, _)| *p != part) {
|
||||
return Err(malformed("every channel in a data-window request must belong to that part"));
|
||||
}
|
||||
index.parts.get(part).map(|p| p.data_window).ok_or_else(|| malformed("no such data window part"))
|
||||
} else {
|
||||
Ok(index.display)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -830,7 +865,9 @@ impl Plan {
|
||||
fn plan(index: &Index, request: &Request) -> Result<Plan> {
|
||||
let level = request.level.min(16);
|
||||
let stride = 1i64 << level;
|
||||
let (w, h) = (index.display.width as usize, index.display.height as usize);
|
||||
let window = request_window(index, request)?;
|
||||
let (w, h) = (window.width as usize, window.height as usize);
|
||||
let in_data_window = request.data_window.is_some();
|
||||
let out = level_size((w, h), level);
|
||||
// Per part and channel: the request slots that name it.
|
||||
let mut slots: Vec<Vec<Vec<usize>>> = index.parts.iter().map(|p| vec![Vec::new(); p.channels.len()]).collect();
|
||||
@@ -872,7 +909,7 @@ fn plan(index: &Index, request: &Request) -> Result<Plan> {
|
||||
// (both ends inside the display window, so an empty or reversed range at either end of i64
|
||||
// stays empty instead of overflowing when aligned to the level's grid)
|
||||
let rows = rows.start.clamp(0, h as i64)..rows.end.clamp(0, h as i64);
|
||||
let geometry = Geometry { size: (w, h), out, stride, rows: rows.clone(), slots: &slots, units: &units };
|
||||
let geometry = Geometry { size: (w, h), out, stride, in_data_window, rows: rows.clone(), slots: &slots, units: &units };
|
||||
// What the request delivers: the rows read, at the level, of every requested channel.
|
||||
let need = plane_bytes((out.0, geometry.rows_read()), request.channels.len());
|
||||
if need > request.max_bytes {
|
||||
@@ -888,7 +925,7 @@ fn plan(index: &Index, request: &Request) -> Result<Plan> {
|
||||
continue;
|
||||
}
|
||||
for c in &part.chunks {
|
||||
let top = (c.y as i64).saturating_add(part.offset.1);
|
||||
let top = (c.y as i64).saturating_add(geometry.offset(part).1);
|
||||
if !geometry.any_wanted(top, top.saturating_add(c.rows as i64)) {
|
||||
continue;
|
||||
}
|
||||
@@ -914,7 +951,7 @@ fn plan(index: &Index, request: &Request) -> Result<Plan> {
|
||||
// (no more threads than chunks can be in flight: two pieces)
|
||||
let workers =
|
||||
request.workers.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, usize::from)).min(jobs.len()).min(2 * PIECE_CHUNKS);
|
||||
Ok(Plan { slots, size: (w, h), out, stride, rows, jobs, workers, units })
|
||||
Ok(Plan { slots, size: (w, h), out, stride, in_data_window, rows, jobs, workers, units })
|
||||
}
|
||||
|
||||
impl Index {
|
||||
@@ -1188,7 +1225,8 @@ fn next_result(results: &Receiver<(usize, Decoded)>, cancel: &dyn Fn() -> bool)
|
||||
/// is [`Error::OutOfMemory`], not an abort), so the cost is known before the first chunk is
|
||||
/// read.
|
||||
pub fn read_planes<R: Read + Seek + ?Sized>(source: &mut R, index: &Index, request: &Request, cancel: &dyn Fn() -> bool) -> Result<Planes> {
|
||||
let (w, h) = (index.display.width as usize, index.display.height as usize);
|
||||
let window = request_window(index, request)?;
|
||||
let (w, h) = (window.width as usize, window.height as usize);
|
||||
let (ow, oh) = level_size((w, h), request.level.min(16));
|
||||
let n = ow.checked_mul(oh).ok_or_else(|| Error::LimitExceeded("display window".into()))?;
|
||||
let need = plane_bytes((ow, oh), request.channels.len());
|
||||
@@ -1451,12 +1489,13 @@ fn chunk_bands(index: &Index, pi: usize, expected: &ChunkRef, buf: &[u8], g: &Ge
|
||||
let slots = g.slots.get(pi).map_or(&[][..], Vec::as_slice);
|
||||
let lines = block.index.pixel_size.1;
|
||||
let ((lw, lh), (w, h)) = (part.size, g.size);
|
||||
let (offset_x, offset_y) = g.offset(part);
|
||||
let (ow, _) = g.out;
|
||||
// The output rows of the block: its data-window rows that land in the display window on a
|
||||
// wanted row. They are consecutive in the output grid (wanted rows are every stride-th).
|
||||
let (by, bh) = (block.index.pixel_position.1, block.index.pixel_size.1);
|
||||
let out_rows: Vec<usize> = (by..by.saturating_add(bh))
|
||||
.filter_map(|y| usize::try_from(y as i64 + part.offset.1).ok())
|
||||
.filter_map(|y| usize::try_from(y as i64 + offset_y).ok())
|
||||
.filter(|ty| *ty < h && g.wanted(*ty as i64))
|
||||
.map(|ty| ty / g.stride as usize)
|
||||
.collect();
|
||||
@@ -1477,11 +1516,11 @@ fn chunk_bands(index: &Index, pi: usize, expected: &ChunkRef, buf: &[u8], g: &Ge
|
||||
if y >= lh || x0.checked_add(count).is_none_or(|end| end > lw) {
|
||||
continue;
|
||||
}
|
||||
let Some(ty) = usize::try_from(y as i64 + part.offset.1).ok().filter(|ty| *ty < h) else { continue };
|
||||
let Some(ty) = usize::try_from(y as i64 + offset_y).ok().filter(|ty| *ty < h) else { continue };
|
||||
if !g.wanted(ty as i64) {
|
||||
continue;
|
||||
}
|
||||
let tx0 = x0 as i64 + part.offset.0;
|
||||
let tx0 = x0 as i64 + offset_x;
|
||||
let skip = usize::try_from(-tx0).unwrap_or(0).min(count);
|
||||
let tx = usize::try_from(tx0.max(0)).unwrap_or(usize::MAX);
|
||||
let take = (count - skip).min(w.saturating_sub(tx));
|
||||
|
||||
@@ -14,7 +14,7 @@ use exr::prelude::{
|
||||
WritableImage,
|
||||
};
|
||||
|
||||
use super::decode::{Limits, decode_display_part};
|
||||
use super::decode::{Limits, Window, decode_display_part};
|
||||
use super::seek::*;
|
||||
|
||||
fn value(i: usize, k: usize) -> f32 {
|
||||
@@ -52,6 +52,29 @@ fn indexed(bytes: &[u8]) -> Index {
|
||||
Index::build(&mut Cursor::new(bytes), &Limits::default(), &never).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_finds_chromaticities_in_a_later_part_header() {
|
||||
let window = Window { x: 0, y: 0, width: 1, height: 1 };
|
||||
let channels = [crate::write::Channel { name: "Y", sample: crate::decode::SampleType::F32 }];
|
||||
let first = crate::write::Part { name: Some("First"), data_window: window, channels: &channels, compression: crate::decode::Compression::None };
|
||||
let second = crate::write::Part { name: Some("Second"), ..first };
|
||||
let chromaticities = [[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]];
|
||||
let metadata = crate::write::Metadata { chromaticities: Some(chromaticities), ..Default::default() };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
crate::write::write_scanlines_with_metadata(&mut out, window, &[first, second], &metadata, |_, _, _, row| Ok(row.len())).unwrap();
|
||||
let mut bytes = out.into_inner();
|
||||
|
||||
// Rename the first header's attribute without shifting the second header or any offsets.
|
||||
let attr = b"chromaticities\0chromaticities\0";
|
||||
let positions: Vec<_> = bytes.windows(attr.len()).enumerate().filter_map(|(offset, bytes)| (bytes == attr).then_some(offset)).collect();
|
||||
assert_eq!(positions.len(), 2);
|
||||
bytes[positions[0]] = b'x';
|
||||
let headers = exr::meta::MetaData::read_from_buffered(Cursor::new(&bytes), false).unwrap().headers;
|
||||
assert!(headers[0].shared_attributes.chromaticities.is_none());
|
||||
assert!(headers[1].shared_attributes.chromaticities.is_some());
|
||||
assert_eq!(indexed(&bytes).chromaticities(), Some(chromaticities));
|
||||
}
|
||||
|
||||
/// What the whole-part decoder places in the display window for each channel of part `part`.
|
||||
fn oracle(bytes: &[u8], part: usize, fill: f32) -> Vec<Vec<f32>> {
|
||||
decode_display_part(bytes, part, &|_| true, &|_| fill, &Limits::default()).unwrap().channels.into_iter().map(|c| c.samples).collect()
|
||||
@@ -89,6 +112,25 @@ fn only_the_requested_channels_are_returned_in_the_requested_order() {
|
||||
assert_eq!(read.planes, [whole[3].clone(), whole[0].clone()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_in_a_parts_data_window_keeps_off_display_tiles() {
|
||||
let bytes = file(
|
||||
vec![
|
||||
layer(Some("beauty"), (0, 0), (8, 6), &["R"], false, Compression::ZIP1),
|
||||
layer(Some("paint"), (-2, -3), (9, 7), &["R"], true, Compression::ZIP1),
|
||||
],
|
||||
(8, 6),
|
||||
);
|
||||
let index = indexed(&bytes);
|
||||
let request = Request { data_window: Some(1), ..Request::new(&[(1, 0)], usize::MAX) };
|
||||
let output = read_planes(&mut Cursor::new(&bytes), &index, &request, &never).unwrap();
|
||||
assert_eq!((output.width, output.height), (9, 7));
|
||||
assert_eq!(output.stats.chunks[0], 0);
|
||||
assert_eq!(output.planes[0], (0..9 * 7).map(|i| value(i, 0)).collect::<Vec<_>>());
|
||||
let wrong_part = Request { data_window: Some(1), ..Request::new(&[(0, 0)], usize::MAX) };
|
||||
assert!(index.estimate(&wrong_part).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_part_with_no_requested_channel_is_not_read() {
|
||||
let bytes = file(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Bounded block-by-block reading of one flat scan-line part (feature `decode`): a reader that
|
||||
//! never sizes a buffer by the whole picture. [`Decoder::new`] reads the headers (at most 8 MiB
|
||||
//! and 4096 attributes) and the offset table through `Read + Seek`; [`Decoder::next_band`] then
|
||||
//! and 4,096 attributes) and the offset table through `Read + Seek`; [`Decoder::next_band`] then
|
||||
//! returns one compression block at a time as interleaved f32 samples. A caller that writes bands
|
||||
//! into tiled storage can open pictures larger than memory.
|
||||
//!
|
||||
@@ -21,7 +21,7 @@ use exr::{
|
||||
};
|
||||
|
||||
use crate::channels::{ColorLayout, color_channels};
|
||||
use crate::decode::{Error, Result};
|
||||
use crate::decode::{Error, MAX_HEADER_ATTRIBUTES, Result};
|
||||
|
||||
const META_BYTES: usize = 8 << 20;
|
||||
const BLOCK_BYTES: usize = 64 << 20;
|
||||
@@ -73,8 +73,8 @@ fn metadata(r: &mut impl Read, cancel: &dyn Fn() -> bool) -> Result<Vec<u8>> {
|
||||
break;
|
||||
}
|
||||
attributes += 1;
|
||||
if attributes > 4096 {
|
||||
return Err(limit("EXR metadata exceeds 4096 attributes"));
|
||||
if attributes > MAX_HEADER_ATTRIBUTES {
|
||||
return Err(limit(&format!("EXR metadata exceeds {MAX_HEADER_ATTRIBUTES} attributes")));
|
||||
}
|
||||
string(r, &mut prefix)?;
|
||||
let length = read::<4>(r)?;
|
||||
|
||||
@@ -0,0 +1,660 @@
|
||||
//! Incremental flat OpenEXR output (feature `decode`).
|
||||
//!
|
||||
//! [`write_scanlines`] asks for one typed channel row at a time. [`write_tiles`] asks for one
|
||||
//! tile at a time. Both buffer a single compression block, with sample and codec scratch space,
|
||||
//! metadata and one offset per chunk.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::{Seek, SeekFrom, Write};
|
||||
use std::ops::Range;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
use exr::block::writer::ChunksWriter;
|
||||
use exr::block::{BlockIndex, UncompressedBlock, enumerate_ordered_header_block_indices};
|
||||
use exr::math::{RoundingMode, Vec2};
|
||||
use exr::meta::attribute::{
|
||||
AttributeValue, ChannelDescription, Chromaticities, IntegerBounds, LevelMode, LineOrder, SampleType as ExrSample, Text, TileDescription,
|
||||
};
|
||||
use exr::meta::{BlockDescription, Headers, header::Header};
|
||||
|
||||
use crate::decode::{Compression, Error, MAX_HEADER_ATTRIBUTES, Result, SampleType, Window, f16, to_exr_compression};
|
||||
|
||||
const MAX_PARTS: usize = 1024;
|
||||
const MAX_CHANNELS: usize = 16_384;
|
||||
const MAX_CHUNKS: usize = 1 << 20;
|
||||
const MAX_BLOCK_BYTES: usize = 64 << 20;
|
||||
const MAX_NAME_BYTES: usize = 255;
|
||||
const SHORT_NAME_BYTES: usize = 31;
|
||||
const VERSION_WORD_OFFSET: u64 = 4;
|
||||
const MAX_HEADER_BYTES: usize = 8 << 20;
|
||||
const MAX_TEXT_ATTRIBUTES: usize = 16_384;
|
||||
|
||||
/// Name and stored sample type of a full-resolution channel.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Channel<'a> {
|
||||
pub name: &'a str,
|
||||
pub sample: SampleType,
|
||||
}
|
||||
|
||||
/// The window, channels and encoding of one flat part.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Part<'a> {
|
||||
/// Required and unique in a multipart file. Optional in a single-part file.
|
||||
pub name: Option<&'a str>,
|
||||
pub data_window: Window,
|
||||
pub channels: &'a [Channel<'a>],
|
||||
/// Per-part compression.
|
||||
pub compression: Compression,
|
||||
}
|
||||
|
||||
/// One flat tiled part with a single resolution level.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TilePart<'a> {
|
||||
pub part: Part<'a>,
|
||||
pub tile_width: u32,
|
||||
pub tile_height: u32,
|
||||
}
|
||||
|
||||
/// Names and values of the `string` attributes of one part.
|
||||
pub type TextAttributes<'a> = &'a [(&'a str, &'a str)];
|
||||
|
||||
/// Optional file and part attributes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub struct Metadata<'a> {
|
||||
/// CIE xy for red, green, blue and white, shared by every part.
|
||||
pub chromaticities: Option<[[f32; 2]; 4]>,
|
||||
/// Text attributes by input part index. An empty slice supplies no attributes. The file
|
||||
/// accepts at most 16,384 text attributes and 8 MiB of estimated headers. A part's header
|
||||
/// holds at most 4,096 attributes, so its text attributes leave room for the standard
|
||||
/// attributes the writer adds (channels, windows, compression and the like, plus the part
|
||||
/// name and type in a multipart file).
|
||||
pub text_attributes: &'a [TextAttributes<'a>],
|
||||
}
|
||||
|
||||
/// A buffer to fill in the channel's stored type. Tiles use a contiguous, row-major channel plane.
|
||||
#[derive(Debug)]
|
||||
pub enum RowSamples<'a> {
|
||||
F16(&'a mut [f16]),
|
||||
F32(&'a mut [f32]),
|
||||
U32(&'a mut [u32]),
|
||||
}
|
||||
|
||||
impl RowSamples<'_> {
|
||||
pub fn len(&self) -> usize {
|
||||
match self {
|
||||
Self::F16(row) => row.len(),
|
||||
Self::F32(row) => row.len(),
|
||||
Self::U32(row) => row.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
fn reborrow(&mut self) -> RowSamples<'_> {
|
||||
match self {
|
||||
Self::F16(row) => RowSamples::F16(row),
|
||||
Self::F32(row) => RowSamples::F32(row),
|
||||
Self::U32(row) => RowSamples::U32(row),
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
match self {
|
||||
Self::F16(row) => row.fill(f16::ZERO),
|
||||
Self::F32(row) => row.fill(0.0),
|
||||
Self::U32(row) => row.fill(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn append_to(&self, data: &mut Vec<u8>) {
|
||||
match self {
|
||||
Self::F16(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_bits().to_ne_bytes())),
|
||||
Self::F32(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_ne_bytes())),
|
||||
Self::U32(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_ne_bytes())),
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_range_to(&self, range: Range<usize>, data: &mut [u8]) -> Result<()> {
|
||||
fn copy<T, const N: usize>(samples: &[T], range: Range<usize>, data: &mut [u8], bytes: impl Fn(&T) -> [u8; N]) -> Result<()> {
|
||||
let samples = samples.get(range).ok_or_else(|| encode("invalid tile sample range"))?;
|
||||
let (destinations, remainder) = data.as_chunks_mut::<N>();
|
||||
if !remainder.is_empty() || destinations.len() != samples.len() {
|
||||
return Err(encode("invalid tile channel byte length"));
|
||||
}
|
||||
for (sample, dest) in samples.iter().zip(destinations) {
|
||||
*dest = bytes(sample);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
match self {
|
||||
Self::F16(samples) => copy(samples, range, data, |sample| sample.to_bits().to_ne_bytes()),
|
||||
Self::F32(samples) => copy(samples, range, data, |sample| sample.to_ne_bytes()),
|
||||
Self::U32(samples) => copy(samples, range, data, |sample| sample.to_ne_bytes()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes one or more flat scan-line parts with a common `display_window`.
|
||||
///
|
||||
/// `fill_row(part, row, channel, samples)` fills the given buffer and returns the number of
|
||||
/// samples supplied. `part` and `channel` are indices into the supplied descriptors. Parts
|
||||
/// follow input order and rows increase from `0` at each part's data-window top. Within a row,
|
||||
/// channels are requested in file name order. A callback error stops writing and is returned.
|
||||
///
|
||||
/// Pass a fresh seekable output positioned at byte zero. The caller owns buffering, truncation
|
||||
/// and cleanup of partial output after an I/O or callback error. Invalid descriptors are rejected
|
||||
/// before output begins. Maximums are 1,024 parts, 16,384 channels across all parts, 1,048,576
|
||||
/// chunks across all parts and 64 MiB of uncompressed samples per chunk.
|
||||
pub fn write_scanlines<W: Write + Seek + ?Sized>(
|
||||
out: &mut W,
|
||||
display_window: Window,
|
||||
parts: &[Part<'_>],
|
||||
fill_row: impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result<usize>,
|
||||
) -> Result<()> {
|
||||
write_scanlines_with_metadata(out, display_window, parts, &Metadata::default(), fill_row)
|
||||
}
|
||||
|
||||
/// [`write_scanlines`] with optional file and part attributes.
|
||||
pub fn write_scanlines_with_metadata<W: Write + Seek + ?Sized>(
|
||||
out: &mut W,
|
||||
display_window: Window,
|
||||
parts: &[Part<'_>],
|
||||
metadata: &Metadata<'_>,
|
||||
mut fill_row: impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result<usize>,
|
||||
) -> Result<()> {
|
||||
let (headers, channel_orders) = prepare_headers(display_window, parts.iter().map(|&part| (part, Storage::ScanLines)), metadata)?;
|
||||
let mut rows = SampleBuffers::new(&headers, |header| header.layer_size.0)?;
|
||||
write_blocks(out, headers, |index, header| {
|
||||
let order = channel_orders.get(index.layer).ok_or_else(|| encode("invalid scan-line block part"))?;
|
||||
fill_block(index, header, order, &mut rows, &mut fill_row)
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes one or more flat tiled parts with a common display window and one resolution level.
|
||||
///
|
||||
/// `fill_tile(part, window, writer)` is called once per tile and supplies each channel once
|
||||
/// through [`TileWriter::fill_channel`]. `part` is the input part index. `window` gives the
|
||||
/// tile's absolute coordinates and its actual size, clipped to its part's data window at edges.
|
||||
/// Parts follow input order and tiles are requested left to right, then top to bottom.
|
||||
/// The output and block limits are as for [`write_scanlines`], with the uncompressed block
|
||||
/// limit applied to the nominal tile dimensions.
|
||||
pub fn write_tiles<W: Write + Seek + ?Sized>(
|
||||
out: &mut W,
|
||||
display_window: Window,
|
||||
parts: &[TilePart<'_>],
|
||||
metadata: &Metadata<'_>,
|
||||
mut fill_tile: impl FnMut(usize, Window, &mut TileWriter<'_>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let layouts = parts.iter().map(|part| (part.part, Storage::Tiles(part.tile_width, part.tile_height)));
|
||||
let (headers, channel_orders) = prepare_headers(display_window, layouts, metadata)?;
|
||||
let mut planes = SampleBuffers::new(&headers, |header| {
|
||||
let Vec2(w, h) = header.max_block_pixel_size();
|
||||
w.min(header.layer_size.0).saturating_mul(h.min(header.layer_size.1))
|
||||
})?;
|
||||
let layouts: Vec<_> = headers.iter().zip(&channel_orders).map(|(header, order)| tile_layout(header, order)).collect::<Result<_>>()?;
|
||||
let mut supplied = vec![false; layouts.iter().map(Vec::len).max().unwrap_or_default()];
|
||||
write_blocks(out, headers, |index, header| {
|
||||
let layout = layouts.get(index.layer).ok_or_else(|| encode("invalid tile part"))?;
|
||||
let supplied = supplied.get_mut(..layout.len()).ok_or_else(|| encode("invalid tile channel count"))?;
|
||||
supplied.fill(false);
|
||||
let window = tile_window(index, header)?;
|
||||
let bytes = block_bytes(index, header)?;
|
||||
let mut data = block_buffer(bytes)?;
|
||||
data.resize(bytes, 0);
|
||||
let Vec2(width, height) = index.pixel_size;
|
||||
let mut writer =
|
||||
TileWriter { width, height, bytes_per_pixel: header.channels.bytes_per_pixel, layout, supplied, data: &mut data, planes: &mut planes };
|
||||
fill_tile(index.layer, window, &mut writer)?;
|
||||
if let Some(channel) = writer.supplied.iter().position(|&supplied| !supplied) {
|
||||
return Err(encode(format_args!("part {}, tile at ({}, {}): missing channel {channel}", index.layer, window.x, window.y)));
|
||||
}
|
||||
Ok(data)
|
||||
})
|
||||
}
|
||||
|
||||
/// Receives the channel planes of one tile in the caller's channel order.
|
||||
pub struct TileWriter<'a> {
|
||||
width: usize,
|
||||
height: usize,
|
||||
bytes_per_pixel: usize,
|
||||
layout: &'a [TileChannel],
|
||||
supplied: &'a mut [bool],
|
||||
data: &'a mut [u8],
|
||||
planes: &'a mut SampleBuffers,
|
||||
}
|
||||
|
||||
impl TileWriter<'_> {
|
||||
/// Fills a typed, row-major channel plane containing one sample per pixel. The callback
|
||||
/// returns the number of samples it supplied.
|
||||
pub fn fill_channel(&mut self, channel: usize, fill: impl FnOnce(RowSamples<'_>) -> Result<usize>) -> Result<()> {
|
||||
let layout = self.layout.get(channel).ok_or_else(|| encode(format_args!("unknown tile channel {channel}")))?;
|
||||
let supplied = self.supplied.get_mut(channel).ok_or_else(|| encode("invalid tile channel bookkeeping"))?;
|
||||
if *supplied {
|
||||
return Err(encode(format_args!("duplicate tile channel {channel}")));
|
||||
}
|
||||
let len = self.width.checked_mul(self.height).ok_or_else(|| encode("tile sample count overflow"))?;
|
||||
let mut plane = self.planes.get(layout.sample, len)?;
|
||||
plane.clear();
|
||||
let count = fill(plane.reborrow())?;
|
||||
if count != len {
|
||||
return Err(encode(format_args!("tile channel {channel}: expected {len} samples, got {count}")));
|
||||
}
|
||||
let stride = self.width * self.bytes_per_pixel;
|
||||
let start = self.width * layout.offset;
|
||||
let end = start + self.width * layout.sample.bytes_per_sample();
|
||||
for (y, row) in self.data.chunks_exact_mut(stride).enumerate() {
|
||||
let dest = row.get_mut(start..end).ok_or_else(|| encode("invalid tile channel byte range"))?;
|
||||
plane.copy_range_to(y * self.width..(y + 1) * self.width, dest)?;
|
||||
}
|
||||
*supplied = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct TileChannel {
|
||||
sample: ExrSample,
|
||||
// Width-independent byte count of the channels preceding this one in file order.
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
fn tile_layout(header: &Header, order: &[usize]) -> Result<Vec<TileChannel>> {
|
||||
let mut channels = vec![TileChannel { sample: ExrSample::F16, offset: 0 }; order.len()];
|
||||
let mut offset = 0;
|
||||
for (&input, channel) in order.iter().zip(&header.channels.list) {
|
||||
let entry = channels.get_mut(input).ok_or_else(|| encode("invalid tile channel order"))?;
|
||||
*entry = TileChannel { sample: channel.sample_type, offset };
|
||||
offset += channel.sample_type.bytes_per_sample();
|
||||
}
|
||||
Ok(channels)
|
||||
}
|
||||
|
||||
fn tile_window(index: BlockIndex, header: &Header) -> Result<Window> {
|
||||
let position = |start: i32, offset: usize| {
|
||||
i32::try_from(offset).ok().and_then(|offset| start.checked_add(offset)).ok_or_else(|| encode("tile coordinate overflow"))
|
||||
};
|
||||
let origin = header.own_attributes.layer_position;
|
||||
Ok(Window {
|
||||
x: position(origin.0, index.pixel_position.0)?,
|
||||
y: position(origin.1, index.pixel_position.1)?,
|
||||
width: u32::try_from(index.pixel_size.0).map_err(encode)?,
|
||||
height: u32::try_from(index.pixel_size.1).map_err(encode)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn write_blocks<W: Write + Seek + ?Sized>(
|
||||
mut out: &mut W,
|
||||
headers: Headers,
|
||||
mut read_block: impl FnMut(BlockIndex, &Header) -> Result<Vec<u8>>,
|
||||
) -> Result<()> {
|
||||
if out.stream_position().map_err(encode)? != 0 {
|
||||
return Err(encode("output must start at byte zero"));
|
||||
}
|
||||
let has_long_names = headers.iter().any(|header| {
|
||||
header.own_attributes.layer_name.as_ref().is_some_and(|name| name.bytes().len() > SHORT_NAME_BYTES)
|
||||
|| header.channels.list.iter().any(|channel| channel.name.bytes().len() > SHORT_NAME_BYTES)
|
||||
});
|
||||
let mut version_update = None;
|
||||
let mut block_error = None;
|
||||
let written = catch_unwind(AssertUnwindSafe(|| {
|
||||
exr::block::write(&mut *out, headers, true, |meta, writer| {
|
||||
if has_long_names && !meta.requirements.has_long_names {
|
||||
version_update = Some(exr::meta::Requirements { has_long_names: true, ..meta.requirements });
|
||||
}
|
||||
for (chunk_index, index) in enumerate_ordered_header_block_indices(&meta.headers) {
|
||||
let data =
|
||||
meta.headers.get(index.layer).ok_or_else(|| encode("invalid block part")).and_then(|header| read_block(index, header)).map_err(
|
||||
|error| {
|
||||
block_error = Some(error);
|
||||
exr::error::Error::Aborted
|
||||
},
|
||||
)?;
|
||||
let chunk = UncompressedBlock { index, data }.compress_to_chunk(&meta.headers)?;
|
||||
writer.write_chunk(chunk_index, chunk)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}));
|
||||
if let Some(error) = block_error {
|
||||
return Err(error);
|
||||
}
|
||||
written.map_err(|_| encode("block writer panicked"))?.map_err(encode)?;
|
||||
// The codec can omit bit 10 when inferring requirements from channel names. Update the
|
||||
// OpenEXR v2 version word in place, preserving the codec's other flags and all chunk offsets.
|
||||
if let Some(requirements) = version_update {
|
||||
let position = out.stream_position().map_err(encode)?;
|
||||
out.seek(SeekFrom::Start(VERSION_WORD_OFFSET)).map_err(encode)?;
|
||||
requirements.write(&mut out).map_err(encode)?;
|
||||
out.seek(SeekFrom::Start(position)).map_err(encode)?;
|
||||
}
|
||||
out.flush().map_err(encode)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Storage {
|
||||
ScanLines,
|
||||
Tiles(u32, u32),
|
||||
}
|
||||
|
||||
impl Storage {
|
||||
fn describe(self, size: Vec2<usize>, compression: exr::compression::Compression) -> Result<(BlockDescription, Vec2<usize>, usize)> {
|
||||
match self {
|
||||
Self::ScanLines => {
|
||||
let rows = compression.scan_lines_per_block();
|
||||
Ok((BlockDescription::ScanLines, Vec2(size.0, rows), size.1.div_ceil(rows)))
|
||||
}
|
||||
Self::Tiles(width, height) => {
|
||||
let dimension = |n| usize::try_from(n).ok().filter(|&n| n > 0 && n <= MAX_BLOCK_BYTES);
|
||||
let (w, h) = dimension(width).zip(dimension(height)).ok_or_else(|| encode("invalid tile dimensions"))?;
|
||||
let chunks = size.0.div_ceil(w).checked_mul(size.1.div_ceil(h)).ok_or_else(|| encode("tile count overflow"))?;
|
||||
let tile_size = Vec2(w, h);
|
||||
let tiles = TileDescription { tile_size, level_mode: LevelMode::Singular, rounding_mode: RoundingMode::Down };
|
||||
Ok((BlockDescription::Tiles(tiles), tile_size, chunks))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_headers<'a>(
|
||||
display_window: Window,
|
||||
parts: impl ExactSizeIterator<Item = (Part<'a>, Storage)>,
|
||||
metadata: &Metadata<'_>,
|
||||
) -> Result<(Headers, Vec<Vec<usize>>)> {
|
||||
let part_count = parts.len();
|
||||
if part_count == 0 || part_count > MAX_PARTS {
|
||||
return Err(encode("expected 1 to 1,024 parts"));
|
||||
}
|
||||
if !metadata.text_attributes.is_empty() && metadata.text_attributes.len() != part_count {
|
||||
return Err(encode("text attributes must have one entry per part"));
|
||||
}
|
||||
if metadata.text_attributes.iter().map(|attributes| attributes.len()).fold(0usize, usize::saturating_add) > MAX_TEXT_ATTRIBUTES {
|
||||
return Err(encode(format_args!("more than {MAX_TEXT_ATTRIBUTES} text attributes")));
|
||||
}
|
||||
let chromaticities = metadata.chromaticities.map(checked_chromaticities).transpose()?;
|
||||
let display = window_bounds(display_window)?;
|
||||
let mut headers = Headers::new();
|
||||
let mut channel_orders = Vec::with_capacity(part_count);
|
||||
let mut part_names = HashSet::new();
|
||||
let (mut channel_count, mut chunk_count) = (0usize, 0usize);
|
||||
let mut max_file_bytes = 16usize; // Magic, version and header-list terminator.
|
||||
let mut header_bytes = 16usize;
|
||||
for (index, (part, storage)) in parts.enumerate() {
|
||||
let name = part.name.map(|name| checked_name(name, "part")).transpose()?;
|
||||
if let Some(name) = &name {
|
||||
if !part_names.insert(name.clone()) {
|
||||
return Err(encode(format_args!("duplicate part name {name}")));
|
||||
}
|
||||
} else if part_count > 1 {
|
||||
return Err(encode(format_args!("multipart part {index} needs a name")));
|
||||
}
|
||||
|
||||
let data = window_bounds(part.data_window)?;
|
||||
let (width, height) = (data.size.0, data.size.1);
|
||||
channel_count = channel_count.saturating_add(part.channels.len());
|
||||
if part.channels.is_empty() || channel_count > MAX_CHANNELS {
|
||||
return Err(encode(format_args!("part {index} needs channels and the file supports up to {MAX_CHANNELS} channels")));
|
||||
}
|
||||
|
||||
let compression = to_exr_compression(part.compression);
|
||||
let (blocks, Vec2(block_width, block_height), chunks) = storage.describe(data.size, compression)?;
|
||||
chunk_count = chunk_count.saturating_add(chunks);
|
||||
if chunk_count > MAX_CHUNKS {
|
||||
return Err(encode(format_args!("more than {MAX_CHUNKS} blocks")));
|
||||
}
|
||||
|
||||
let mut channels = Vec::with_capacity(part.channels.len());
|
||||
for (channel_index, channel) in part.channels.iter().enumerate() {
|
||||
let name = checked_name(channel.name, "channel")?;
|
||||
let sample = match channel.sample {
|
||||
SampleType::F16 => ExrSample::F16,
|
||||
SampleType::F32 => ExrSample::F32,
|
||||
SampleType::U32 => ExrSample::U32,
|
||||
};
|
||||
channels.push((channel_index, ChannelDescription::named(name, sample)));
|
||||
}
|
||||
channels.sort_unstable_by(|(_, a), (_, b)| a.name.cmp(&b.name));
|
||||
if let Some([(_, a), _]) = channels.windows(2).find(|pair| matches!(pair, [(_, a), (_, b)] if a.name == b.name)) {
|
||||
return Err(encode(format_args!("duplicate channel name {} in part {index}", a.name)));
|
||||
}
|
||||
|
||||
let bytes_per_pixel: usize = channels.iter().map(|(_, channel)| channel.sample_type.bytes_per_sample()).sum();
|
||||
let bounded_height = if matches!(storage, Storage::ScanLines) { block_height.min(height) } else { block_height };
|
||||
if block_width.saturating_mul(bounded_height).saturating_mul(bytes_per_pixel) > MAX_BLOCK_BYTES {
|
||||
return Err(encode(format_args!("a block in part {index} exceeds {MAX_BLOCK_BYTES} uncompressed bytes")));
|
||||
}
|
||||
// The codec uses usize for the nominal block size and output offsets. Allow space
|
||||
// beyond raw samples for standard attributes, channel entries, and chunk prefixes/offsets.
|
||||
if block_width.checked_mul(block_height).and_then(|n| n.checked_mul(bytes_per_pixel)).is_none() {
|
||||
return Err(encode(format_args!("a block in part {index} exceeds the codec's addressable size")));
|
||||
}
|
||||
let header_estimate = 1024 + channels.iter().map(|(_, channel)| channel.name.bytes().len() + 32).sum::<usize>();
|
||||
header_bytes = header_bytes.saturating_add(header_estimate);
|
||||
let attributes = metadata.text_attributes.get(index).copied().unwrap_or_default();
|
||||
let extra_bytes = text_bytes(attributes, &mut header_bytes)?;
|
||||
let overhead = header_estimate + extra_bytes + chunks * 32;
|
||||
max_file_bytes = width
|
||||
.checked_mul(height)
|
||||
.and_then(|pixels| pixels.checked_mul(bytes_per_pixel))
|
||||
.and_then(|samples| samples.checked_add(overhead))
|
||||
.and_then(|part_bytes| max_file_bytes.checked_add(part_bytes))
|
||||
.ok_or_else(|| encode("file may exceed the codec's addressable size"))?;
|
||||
|
||||
let (order, descriptions) = channels.into_iter().unzip();
|
||||
let mut header = Header::new(Text::from_slice_unchecked(b""), data.size, descriptions)
|
||||
.with_display_window(display)
|
||||
.with_position(data.position)
|
||||
.with_encoding(compression, blocks, LineOrder::Increasing);
|
||||
header.own_attributes.layer_name = name;
|
||||
header.shared_attributes.chromaticities = chromaticities;
|
||||
set_text_attributes(&mut header, attributes)?;
|
||||
let header_attributes = header.all_named_attributes().count();
|
||||
if header_attributes > MAX_HEADER_ATTRIBUTES {
|
||||
return Err(encode(format_args!(
|
||||
"part {index} has {header_attributes} attributes, standard ones included, and a header holds at most {MAX_HEADER_ATTRIBUTES}"
|
||||
)));
|
||||
}
|
||||
headers.push(header);
|
||||
channel_orders.push(order);
|
||||
}
|
||||
Ok((headers, channel_orders))
|
||||
}
|
||||
|
||||
fn checked_name(name: &str, kind: &str) -> Result<Text> {
|
||||
// exr::Text stores one byte per character. Check the character count before allocating it.
|
||||
if name.is_empty() || name.chars().take(MAX_NAME_BYTES + 1).count() > MAX_NAME_BYTES || name.bytes().any(|byte| byte == 0) {
|
||||
return Err(encode(format_args!("invalid {kind} name: expected 1 to {MAX_NAME_BYTES} OpenEXR bytes without NUL")));
|
||||
}
|
||||
Text::new_or_none(name).ok_or_else(|| encode(format_args!("invalid {kind} name: unsupported characters")))
|
||||
}
|
||||
|
||||
fn checked_chromaticities(points: [[f32; 2]; 4]) -> Result<Chromaticities> {
|
||||
if points.iter().flatten().any(|value| !value.is_finite()) {
|
||||
return Err(encode("chromaticities must be finite"));
|
||||
}
|
||||
let [red, green, blue, white] = points.map(|[x, y]| Vec2(x, y));
|
||||
Ok(Chromaticities { red, green, blue, white })
|
||||
}
|
||||
|
||||
fn text_bytes(attributes: TextAttributes<'_>, header_bytes: &mut usize) -> Result<usize> {
|
||||
let start = *header_bytes;
|
||||
if start > MAX_HEADER_BYTES {
|
||||
return Err(encode("OpenEXR headers exceed 8 MiB"));
|
||||
}
|
||||
for &(key, value) in attributes {
|
||||
*header_bytes = header_bytes.saturating_add(key.len()).saturating_add(value.len()).saturating_add(16);
|
||||
if *header_bytes > MAX_HEADER_BYTES {
|
||||
return Err(encode("OpenEXR headers exceed 8 MiB"));
|
||||
}
|
||||
}
|
||||
Ok(*header_bytes - start)
|
||||
}
|
||||
|
||||
fn set_text_attributes(header: &mut Header, attributes: TextAttributes<'_>) -> Result<()> {
|
||||
let mut seen = HashSet::new();
|
||||
for &(name, value) in attributes {
|
||||
let key = checked_name(name, "attribute")?;
|
||||
if !seen.insert(name) {
|
||||
return Err(encode(format_args!("duplicate attribute {name}")));
|
||||
}
|
||||
let value = Text::new_or_none(value).ok_or_else(|| encode(format_args!("invalid string attribute {name}: unsupported characters")))?;
|
||||
if value.bytes().contains(&0) {
|
||||
return Err(encode(format_args!("invalid string attribute {name}: contains NUL")));
|
||||
}
|
||||
let attrs = &mut header.own_attributes;
|
||||
let field = match name {
|
||||
"owner" => &mut attrs.owner,
|
||||
"comments" => &mut attrs.comments,
|
||||
"capDate" => &mut attrs.capture_date,
|
||||
"wrapmodes" => &mut attrs.wrap_mode_name,
|
||||
"view" => &mut attrs.view_name,
|
||||
"software" => &mut attrs.software_name,
|
||||
"renderingTransform" => &mut attrs.rendering_transform_name,
|
||||
"lookModTransform" => &mut attrs.look_modification_transform_name,
|
||||
"channels"
|
||||
| "compression"
|
||||
| "dataWindow"
|
||||
| "displayWindow"
|
||||
| "lineOrder"
|
||||
| "pixelAspectRatio"
|
||||
| "screenWindowCenter"
|
||||
| "screenWindowWidth"
|
||||
| "name"
|
||||
| "type"
|
||||
| "version"
|
||||
| "chunkCount"
|
||||
| "tiles"
|
||||
| "maxSamplesPerPixel"
|
||||
| "chromaticities"
|
||||
| "timeCode"
|
||||
| "preview"
|
||||
| "whiteLuminance"
|
||||
| "adoptedNeutral"
|
||||
| "xDensity"
|
||||
| "utcOffset"
|
||||
| "longitude"
|
||||
| "latitude"
|
||||
| "altitude"
|
||||
| "focus"
|
||||
| "expTime"
|
||||
| "aperture"
|
||||
| "isoSpeed"
|
||||
| "envmap"
|
||||
| "keyCode"
|
||||
| "framesPerSecond"
|
||||
| "multiView"
|
||||
| "worldToCamera"
|
||||
| "worldToNDC"
|
||||
| "deepImageState"
|
||||
| "originalDataWindow"
|
||||
| "nearClipPlane"
|
||||
| "farClipPlane"
|
||||
| "horizontalFieldOfView"
|
||||
| "verticalFieldOfView" => {
|
||||
return Err(encode(format_args!("reserved attribute {name}")));
|
||||
}
|
||||
_ => {
|
||||
attrs.other.insert(key, AttributeValue::Text(value));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
*field = Some(value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn window_bounds(window: Window) -> Result<IntegerBounds> {
|
||||
let axis = |position: i32, size: u32| {
|
||||
// The codec works with inclusive and exclusive ends and negates the origin in i32.
|
||||
let size = i32::try_from(size).ok().filter(|&size| size > 0)?;
|
||||
position.checked_neg()?;
|
||||
position.checked_add(size)?;
|
||||
usize::try_from(size).ok()
|
||||
};
|
||||
let size = axis(window.x, window.width).zip(axis(window.y, window.height)).ok_or_else(|| encode("invalid OpenEXR window dimensions"))?;
|
||||
Ok(IntegerBounds::new((window.x, window.y), size))
|
||||
}
|
||||
|
||||
struct SampleBuffers {
|
||||
half: Vec<f16>,
|
||||
float: Vec<f32>,
|
||||
uint: Vec<u32>,
|
||||
}
|
||||
|
||||
impl SampleBuffers {
|
||||
fn new(headers: &[Header], samples: impl Fn(&Header) -> usize) -> Result<Self> {
|
||||
let mut lengths = (0, 0, 0);
|
||||
for header in headers {
|
||||
for channel in &header.channels.list {
|
||||
let len = match channel.sample_type {
|
||||
ExrSample::F16 => &mut lengths.0,
|
||||
ExrSample::F32 => &mut lengths.1,
|
||||
ExrSample::U32 => &mut lengths.2,
|
||||
};
|
||||
*len = (*len).max(samples(header));
|
||||
}
|
||||
}
|
||||
fn zeroed<T: Default + Clone>(width: usize) -> Result<Vec<T>> {
|
||||
let mut samples = Vec::new();
|
||||
samples.try_reserve_exact(width).map_err(|_| encode("could not allocate sample buffer"))?;
|
||||
samples.resize(width, T::default());
|
||||
Ok(samples)
|
||||
}
|
||||
Ok(Self { half: zeroed(lengths.0)?, float: zeroed(lengths.1)?, uint: zeroed(lengths.2)? })
|
||||
}
|
||||
|
||||
fn get(&mut self, sample: ExrSample, width: usize) -> Result<RowSamples<'_>> {
|
||||
match sample {
|
||||
ExrSample::F16 => self.half.get_mut(..width).map(RowSamples::F16),
|
||||
ExrSample::F32 => self.float.get_mut(..width).map(RowSamples::F32),
|
||||
ExrSample::U32 => self.uint.get_mut(..width).map(RowSamples::U32),
|
||||
}
|
||||
.ok_or_else(|| encode("sample buffer has the wrong size"))
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_block(
|
||||
index: BlockIndex,
|
||||
header: &Header,
|
||||
order: &[usize],
|
||||
rows: &mut SampleBuffers,
|
||||
fill_row: &mut impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result<usize>,
|
||||
) -> Result<Vec<u8>> {
|
||||
let part = index.layer;
|
||||
let Vec2(width, height) = index.pixel_size;
|
||||
let mut data = block_buffer(block_bytes(index, header)?)?;
|
||||
let first = index.pixel_position.1;
|
||||
let end = first.checked_add(height).ok_or_else(|| encode("scan-line row index overflow"))?;
|
||||
for row in first..end {
|
||||
for (&channel, description) in order.iter().zip(&header.channels.list) {
|
||||
let mut samples = rows.get(description.sample_type, width)?;
|
||||
samples.clear();
|
||||
let count = fill_row(part, row, channel, samples.reborrow())?;
|
||||
if count != width {
|
||||
return Err(encode(format_args!("part {part}, channel {channel}, row {row}: expected {width} samples, got {count}")));
|
||||
}
|
||||
samples.append_to(&mut data);
|
||||
}
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn block_bytes(index: BlockIndex, header: &Header) -> Result<usize> {
|
||||
let Vec2(width, height) = index.pixel_size;
|
||||
width
|
||||
.checked_mul(height)
|
||||
.and_then(|pixels| pixels.checked_mul(header.channels.bytes_per_pixel))
|
||||
.filter(|&bytes| (1..=MAX_BLOCK_BYTES).contains(&bytes))
|
||||
.ok_or_else(|| encode("invalid block size"))
|
||||
}
|
||||
|
||||
fn block_buffer(bytes: usize) -> Result<Vec<u8>> {
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact(bytes).map_err(|_| encode("could not allocate block buffer"))?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn encode(message: impl std::fmt::Display) -> Error {
|
||||
Error::Encode(message.to_string())
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
use std::cell::Cell;
|
||||
use std::io::{self, Cursor, Seek, SeekFrom, Write};
|
||||
|
||||
use crate::decode::{self, Compression, Error, Limits, MAX_HEADER_ATTRIBUTES, SampleType, Samples, Window, f16};
|
||||
use crate::seek::{Index, Request, read_planes};
|
||||
use crate::write::{Channel, Metadata, Part, RowSamples, TilePart, TileWriter, write_scanlines, write_scanlines_with_metadata, write_tiles};
|
||||
|
||||
const WINDOW: Window = Window { x: -3, y: -5, width: 64, height: 35 };
|
||||
const HALF: Channel<'_> = Channel { name: "R", sample: SampleType::F16 };
|
||||
const FLOAT: Channel<'_> = Channel { name: "Z", sample: SampleType::F32 };
|
||||
const UINT: Channel<'_> = Channel { name: "ID", sample: SampleType::U32 };
|
||||
|
||||
fn half_value(row: usize, channel: usize, x: usize) -> f16 {
|
||||
f16::from_f32((row * 8 + channel * 32 + x / 8) as f32 / 16.0)
|
||||
}
|
||||
|
||||
fn depth_value(row: usize, x: usize) -> f32 {
|
||||
f32::from_bits(0x3f80_0001 + (row * 8 + x / 8) as u32)
|
||||
}
|
||||
|
||||
fn id_value(row: usize, x: usize) -> u32 {
|
||||
u32::MAX - (row * 8 + x / 8) as u32
|
||||
}
|
||||
|
||||
fn sample_row(_: usize, row: usize, channel: usize, mut samples: RowSamples<'_>) -> decode::Result<usize> {
|
||||
match &mut samples {
|
||||
RowSamples::F16(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = half_value(row, channel, x)),
|
||||
RowSamples::F32(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = depth_value(row, x)),
|
||||
RowSamples::U32(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = id_value(row, x)),
|
||||
}
|
||||
Ok(samples.len())
|
||||
}
|
||||
|
||||
fn whole_plane<T>(window: Window, sample: impl Fn(usize, usize) -> T) -> Vec<T> {
|
||||
(0..window.height as usize).flat_map(|row| (0..window.width as usize).map(move |x| (row, x))).map(|(row, x)| sample(row, x)).collect()
|
||||
}
|
||||
|
||||
fn fill_tile(part: TilePart<'_>, window: Window, tile: &mut TileWriter<'_>) -> decode::Result<()> {
|
||||
let x0 = (window.x - part.part.data_window.x) as usize;
|
||||
let y0 = (window.y - part.part.data_window.y) as usize;
|
||||
let width = window.width as usize;
|
||||
// Supply in reverse descriptor order to exercise channel placement independent of callback order.
|
||||
for channel in (0..part.part.channels.len()).rev() {
|
||||
tile.fill_channel(channel, |mut samples| {
|
||||
let at = |i: usize| (y0 + i / width, x0 + i % width);
|
||||
match &mut samples {
|
||||
RowSamples::F16(values) => values.iter_mut().enumerate().for_each(|(i, value)| {
|
||||
let (y, x) = at(i);
|
||||
*value = half_value(y, channel, x);
|
||||
}),
|
||||
RowSamples::F32(values) => values.iter_mut().enumerate().for_each(|(i, value)| {
|
||||
let (y, x) = at(i);
|
||||
*value = depth_value(y, x);
|
||||
}),
|
||||
RowSamples::U32(values) => values.iter_mut().enumerate().for_each(|(i, value)| {
|
||||
let (y, x) = at(i);
|
||||
*value = id_value(y, x);
|
||||
}),
|
||||
}
|
||||
Ok(samples.len())
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiled_lossless_round_trips_all_sample_types_and_clips_edge_tiles() {
|
||||
for (compression, name) in [
|
||||
(Compression::None, "Uncompressed"),
|
||||
(Compression::Rle, "RLE"),
|
||||
(Compression::Zip1, "ZIP1"),
|
||||
(Compression::Zip16, "ZIP16"),
|
||||
(Compression::Piz, "PIZ"),
|
||||
] {
|
||||
let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression };
|
||||
let tiled = TilePart { part, tile_width: 30, tile_height: 18 };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let mut windows = Vec::new();
|
||||
write_tiles(&mut out, WINDOW, &[tiled], &Metadata::default(), |part, window, tile| {
|
||||
assert_eq!(part, 0);
|
||||
windows.push(window);
|
||||
fill_tile(tiled, window, tile)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(windows.len(), 6);
|
||||
assert_eq!(windows[0], Window { width: 30, height: 18, ..WINDOW });
|
||||
assert_eq!(windows[5], Window { x: WINDOW.x + 60, y: WINDOW.y + 18, width: 4, height: 17 });
|
||||
|
||||
let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap();
|
||||
assert!(decoded.info.tiled);
|
||||
assert_eq!(decoded.info.compression, name);
|
||||
assert_eq!(decoded.info.data_window, WINDOW);
|
||||
assert_eq!(decoded.channel("Z").unwrap().samples, Samples::F32(whole_plane(WINDOW, depth_value)));
|
||||
assert_eq!(decoded.channel("R").unwrap().samples, Samples::F16(whole_plane(WINDOW, |y, x| half_value(y, 1, x))));
|
||||
assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiled_multipart_keeps_distinct_tile_sizes_and_metadata() {
|
||||
let depth = Part { name: Some("Depth"), data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let beauty = Part { name: Some("Beauty"), data_window: WINDOW, channels: &[HALF], compression: Compression::Piz };
|
||||
let parts = [TilePart { part: depth, tile_width: 16, tile_height: 14 }, TilePart { part: beauty, tile_width: 31, tile_height: 20 }];
|
||||
let chromaticities = [[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]];
|
||||
let text = [&[("craftLayerStack", "{\"version\":1}"), ("comments", "Preview")][..], &[("passLabel", "Beauty")][..]];
|
||||
let metadata = Metadata { chromaticities: Some(chromaticities), text_attributes: &text };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
write_tiles(&mut out, WINDOW, &parts, &metadata, |part, window, tile| fill_tile(parts[part], window, tile)).unwrap();
|
||||
let mut source = Cursor::new(out.into_inner());
|
||||
let index = Index::build(&mut source, &Limits::default(), &|| false).unwrap();
|
||||
let info = index.parts();
|
||||
assert_eq!(info[0].name.as_deref(), Some("Depth"));
|
||||
assert_eq!(info[1].name.as_deref(), Some("Beauty"));
|
||||
assert!(info.iter().all(|part| part.tiled));
|
||||
assert_eq!(info[0].text("craftLayerStack"), Some("{\"version\":1}"));
|
||||
assert_eq!(info[1].text("craftLayerStack"), None);
|
||||
assert_eq!(info[1].text("passLabel"), Some("Beauty"));
|
||||
let headers = exr::meta::MetaData::read_from_buffered(Cursor::new(source.get_ref()), true).unwrap().headers;
|
||||
assert_eq!(headers[0].own_attributes.comments.as_ref().unwrap().to_string(), "Preview");
|
||||
for header in &headers {
|
||||
let c = header.shared_attributes.chromaticities.unwrap();
|
||||
assert_eq!([[c.red.0, c.red.1], [c.green.0, c.green.1], [c.blue.0, c.blue.1], [c.white.0, c.white.1]], chromaticities);
|
||||
}
|
||||
let requested_row = 31;
|
||||
let request = Request { rows: Some(requested_row..requested_row + 1), ..Request::new(&[(0, 0), (1, 0)], usize::MAX) };
|
||||
let read = read_planes(&mut source, &index, &request, &|| false).unwrap();
|
||||
assert_eq!(read.stats.chunks, [4, 3]);
|
||||
let requested_row = requested_row as usize;
|
||||
assert_eq!(read.planes[0], whole_plane(WINDOW, |y, x| if y == requested_row { depth_value(y, x) } else { 0.0 }));
|
||||
assert_eq!(read.planes[1], whole_plane(WINDOW, |y, x| if y == requested_row { half_value(y, 0, x).to_f32() } else { 0.0 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanline_metadata_round_trips_a_custom_string() {
|
||||
let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let text = [&[("cryptomatte/abc1234/name", "CryptoObject")][..]];
|
||||
let metadata = Metadata { text_attributes: &text, ..Metadata::default() };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
write_scanlines_with_metadata(&mut out, WINDOW, &[part], &metadata, sample_row).unwrap();
|
||||
let parts = decode::parts(out.get_ref(), &Limits::default()).unwrap();
|
||||
assert_eq!(parts[0].text("cryptomatte/abc1234/name"), Some("CryptoObject"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_names_set_the_long_name_flag_at_the_openexr_byte_boundary() {
|
||||
let window = Window { width: 1, height: 1, ..WINDOW };
|
||||
for len in [31, 32, 255] {
|
||||
let name = "Z".repeat(len);
|
||||
let part = Part { name: None, data_window: window, channels: &[Channel { name: &name, ..FLOAT }], compression: Compression::None };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
write_scanlines(&mut out, window, &[part], sample_row).unwrap();
|
||||
assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 2 | if len > 31 { 0x400 } else { 0 });
|
||||
assert_eq!(decode::parts(out.get_ref(), &Limits::default()).unwrap()[0].channels[0].name, name);
|
||||
|
||||
let tiled = TilePart { part, tile_width: 1, tile_height: 1 };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
write_tiles(&mut out, window, &[tiled], &Metadata::default(), |_, window, tile| fill_tile(tiled, window, tile)).unwrap();
|
||||
assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 0x202 | if len > 31 { 0x400 } else { 0 });
|
||||
let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap();
|
||||
assert_eq!(decoded.channel(&name).unwrap().samples, Samples::F32(vec![depth_value(0, 0)]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_part_names_set_the_flag_in_multipart_files() {
|
||||
let window = Window { width: 1, height: 1, ..WINDOW };
|
||||
let part = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::None };
|
||||
for len in [31, 32, 255] {
|
||||
let name = "P".repeat(len);
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
write_scanlines(&mut out, window, &[part, Part { name: Some(&name), ..part }], sample_row).unwrap();
|
||||
assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 0x1002 | if len > 31 { 0x400 } else { 0 });
|
||||
assert_eq!(decode::parts(out.get_ref(), &Limits::default()).unwrap()[1].name.as_deref(), Some(name.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_tile_dimensions_and_metadata_fail_before_output() {
|
||||
let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let tiled = TilePart { part, tile_width: 16, tile_height: 16 };
|
||||
let no_metadata = Metadata::default();
|
||||
let duplicate = [&[("pass", "Z"), ("pass", "depth")][..]];
|
||||
let reserved = [&[("tiles", "unexpected")][..]];
|
||||
let invalid_chromaticities = Metadata { chromaticities: Some([[f32::NAN; 2]; 4]), ..no_metadata };
|
||||
for (part, metadata) in [
|
||||
(TilePart { tile_width: 0, ..tiled }, no_metadata),
|
||||
(TilePart { tile_width: 16_384, tile_height: 16_384, ..tiled }, no_metadata),
|
||||
(tiled, invalid_chromaticities),
|
||||
(tiled, Metadata { text_attributes: &duplicate, ..no_metadata }),
|
||||
(tiled, Metadata { text_attributes: &reserved, ..no_metadata }),
|
||||
] {
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let result = write_tiles(&mut out, WINDOW, &[part], &metadata, |_, _, _| panic!("invalid descriptors reached callback"));
|
||||
assert!(matches!(result, Err(Error::Encode(_))), "{result:?}");
|
||||
assert!(out.get_ref().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
// Chunk count, channels, compression, line order, display and data windows, pixel aspect ratio,
|
||||
// screen window centre and width, block type and part name
|
||||
const MULTIPART_SCANLINE_ATTRIBUTES: usize = 11;
|
||||
|
||||
fn numbered_attributes(count: usize) -> Vec<(String, String)> {
|
||||
(0..count).map(|n| (format!("pass{n}"), format!("value{n}"))).collect()
|
||||
}
|
||||
|
||||
fn borrowed(attributes: &[(String, String)]) -> Vec<(&str, &str)> {
|
||||
attributes.iter().map(|(name, value)| (name.as_str(), value.as_str())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multipart_header_at_the_attribute_limit_round_trips() {
|
||||
let window = Window { width: 2, height: 2, ..WINDOW };
|
||||
let beauty = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let depth = Part { name: Some("Depth"), ..beauty };
|
||||
let user_attributes = numbered_attributes(MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES);
|
||||
let borrowed_attributes = borrowed(&user_attributes);
|
||||
let text = [&borrowed_attributes[..], &[("passLabel", "Depth")][..]];
|
||||
let metadata = Metadata { text_attributes: &text, ..Metadata::default() };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
|
||||
write_scanlines_with_metadata(&mut out, window, &[beauty, depth], &metadata, sample_row).unwrap();
|
||||
|
||||
let index = Index::build(&mut out, &Limits::default(), &|| false).unwrap();
|
||||
let last = user_attributes.len() - 1;
|
||||
assert_eq!(index.parts()[0].text("pass0"), Some("value0"));
|
||||
assert_eq!(index.parts()[0].text(&format!("pass{last}")), Some(format!("value{last}").as_str()));
|
||||
assert_eq!(index.parts()[1].text("passLabel"), Some("Depth"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multipart_header_over_the_attribute_limit_is_refused_before_output() {
|
||||
let window = Window { width: 2, height: 2, ..WINDOW };
|
||||
let beauty = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let depth = Part { name: Some("Depth"), ..beauty };
|
||||
let user_attributes = numbered_attributes(MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES + 1);
|
||||
let borrowed_attributes = borrowed(&user_attributes);
|
||||
let text = [&[][..], &borrowed_attributes[..]];
|
||||
let metadata = Metadata { text_attributes: &text, ..Metadata::default() };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
|
||||
let result = write_scanlines_with_metadata(&mut out, window, &[beauty, depth], &metadata, |_, _, _, _| panic!("reached callback"));
|
||||
|
||||
assert!(matches!(&result, Err(Error::Encode(message)) if message.contains("part 1") && message.contains("4096")), "{result:?}");
|
||||
assert!(out.get_ref().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiled_header_with_chromaticities_counts_them_against_the_attribute_limit() {
|
||||
let window = Window { width: 2, height: 2, ..WINDOW };
|
||||
let part = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let tiled = TilePart { part, tile_width: 2, tile_height: 2 };
|
||||
let chromaticities = Some([[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]]);
|
||||
// The scan-line set plus the tile description and the shared chromaticities
|
||||
let user_count = MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES - 2;
|
||||
let user_attributes = numbered_attributes(user_count);
|
||||
let borrowed_attributes = borrowed(&user_attributes);
|
||||
let text = [&borrowed_attributes[..]];
|
||||
let metadata = Metadata { chromaticities, text_attributes: &text };
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
|
||||
write_tiles(&mut out, window, &[tiled], &metadata, |_, window, tile| fill_tile(tiled, window, tile)).unwrap();
|
||||
|
||||
Index::build(&mut out, &Limits::default(), &|| false).unwrap();
|
||||
let over_attributes = numbered_attributes(user_count + 1);
|
||||
let borrowed_over = borrowed(&over_attributes);
|
||||
let over_text = [&borrowed_over[..]];
|
||||
let over = Metadata { chromaticities, text_attributes: &over_text };
|
||||
let mut refused = Cursor::new(Vec::new());
|
||||
let result = write_tiles(&mut refused, window, &[tiled], &over, |_, _, _| panic!("reached callback"));
|
||||
assert!(matches!(result, Err(Error::Encode(_))), "{result:?}");
|
||||
assert!(refused.get_ref().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_tiles_are_rejected() {
|
||||
let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let tiled = TilePart { part, tile_width: 4, tile_height: 5 };
|
||||
let result = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, _| Ok(()));
|
||||
assert!(matches!(result, Err(Error::Encode(message)) if message.contains("missing channel 0")));
|
||||
|
||||
let short = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, tile| {
|
||||
tile.fill_channel(0, |plane| Ok(plane.len() - 1))
|
||||
});
|
||||
assert!(matches!(short, Err(Error::Encode(message)) if message.contains("expected 20 samples, got 19")));
|
||||
|
||||
let duplicate = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, tile| {
|
||||
tile.fill_channel(0, |plane| Ok(plane.len()))?;
|
||||
tile.fill_channel(0, |plane| Ok(plane.len()))
|
||||
});
|
||||
assert!(matches!(duplicate, Err(Error::Encode(message)) if message.contains("duplicate tile channel 0")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_part_lossless_round_trips_all_sample_types() {
|
||||
for (compression, name) in [
|
||||
(Compression::None, "Uncompressed"),
|
||||
(Compression::Rle, "RLE"),
|
||||
(Compression::Zip1, "ZIP1"),
|
||||
(Compression::Zip16, "ZIP16"),
|
||||
(Compression::Piz, "PIZ"),
|
||||
] {
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression };
|
||||
write_scanlines(&mut out, WINDOW, &[part], sample_row).unwrap();
|
||||
let limits = Limits::default();
|
||||
let bytes = out.get_ref();
|
||||
assert_eq!(decode::parts(bytes, &limits).unwrap().len(), 1);
|
||||
let decoded = decode::decode_part(bytes, 0, &|_| true, &limits).unwrap();
|
||||
assert_eq!(decoded.info.name, None);
|
||||
assert_eq!(decoded.info.compression, name);
|
||||
assert_eq!(decoded.info.data_window, WINDOW);
|
||||
assert_eq!(decoded.channel("Z").unwrap().samples, Samples::F32(whole_plane(WINDOW, depth_value)));
|
||||
assert_eq!(decoded.channel("R").unwrap().samples, Samples::F16(whole_plane(WINDOW, |row, x| half_value(row, 1, x))));
|
||||
assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lossy_encodings_preserve_integer_ids() {
|
||||
for compression in [Compression::Pxr24, Compression::B44, Compression::B44a, Compression::Dwaa, Compression::Dwab] {
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression };
|
||||
write_scanlines(&mut out, WINDOW, &[part], sample_row).unwrap();
|
||||
let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap();
|
||||
assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value)), "{compression:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_parts_round_trip_and_support_selective_reads() {
|
||||
let beauty = [HALF, Channel { name: "G", ..HALF }, Channel { name: "B", ..HALF }, Channel { name: "A", ..HALF }];
|
||||
let depth_window = Window { x: WINDOW.x + 1, y: WINDOW.y + 2, width: WINDOW.width - 1, height: WINDOW.height - 2 };
|
||||
let parts = [
|
||||
Part { name: Some("Depth"), data_window: depth_window, channels: &[FLOAT], compression: Compression::Zip1 },
|
||||
Part { name: Some("Beauty"), data_window: WINDOW, channels: &beauty, compression: Compression::Zip16 },
|
||||
];
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
write_scanlines(&mut out, WINDOW, &parts, sample_row).unwrap();
|
||||
let limits = Limits::default();
|
||||
let mut source = Cursor::new(out.into_inner());
|
||||
let index = Index::build(&mut source, &limits, &|| false).unwrap();
|
||||
let headers = index.parts();
|
||||
assert_eq!(headers.iter().map(|part| part.name.as_deref().unwrap()).collect::<Vec<_>>(), ["Depth", "Beauty"]);
|
||||
assert_eq!(decode::pick_part(headers), Some(1));
|
||||
assert_eq!((&*headers[0].compression, &*headers[1].compression), ("ZIP1", "ZIP16"));
|
||||
assert_eq!(headers[0].data_window, depth_window);
|
||||
assert!(headers.iter().all(|part| part.display_window == WINDOW));
|
||||
let beauty = &headers[1].channels;
|
||||
assert_eq!(beauty.iter().map(|channel| channel.name.as_str()).collect::<Vec<_>>(), ["A", "B", "G", "R"]);
|
||||
assert!(beauty.iter().all(|channel| channel.sample == SampleType::F16));
|
||||
assert_eq!(headers[0].channels[0].sample, SampleType::F32);
|
||||
let depth = decode::decode_part(source.get_ref(), 0, &|_| true, &limits).unwrap();
|
||||
assert_eq!(depth.channel("Z").unwrap().samples, Samples::F32(whole_plane(depth_window, depth_value)));
|
||||
|
||||
let row = 17;
|
||||
let request = Request { rows: Some(row..row + 1), fill: &[-1.0, -2.0], ..Request::new(&[(1, 3), (0, 0)], usize::MAX) };
|
||||
let read = read_planes(&mut source, &index, &request, &|| false).unwrap();
|
||||
assert_eq!(read.stats.chunks, [1, 1]);
|
||||
let row = row as usize;
|
||||
for (plane, expected) in [
|
||||
(&read.planes[0], whole_plane(WINDOW, |y, x| if y == row { half_value(y, 0, x).to_f32() } else { -1.0 })),
|
||||
(&read.planes[1], whole_plane(WINDOW, |y, x| if y == row && x > 0 { depth_value(y - 2, x - 1) } else { -2.0 })),
|
||||
] {
|
||||
assert_eq!(plane, &expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_descriptors_fail_before_writing_or_requesting_rows() {
|
||||
let part = Part { name: Some("Depth"), data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let duplicate = [FLOAT, FLOAT];
|
||||
let bad_channel = [Channel { name: "Z\0hidden", ..FLOAT }];
|
||||
let long_name = "Z".repeat(256);
|
||||
let long_channel = [Channel { name: &long_name, ..FLOAT }];
|
||||
let empty_name = [Channel { name: "", ..FLOAT }];
|
||||
for parts in [
|
||||
vec![],
|
||||
vec![part, part],
|
||||
vec![part, Part { name: None, ..part }],
|
||||
vec![Part { name: Some("🎞"), ..part }],
|
||||
vec![Part { channels: &duplicate, ..part }],
|
||||
vec![Part { channels: &bad_channel, ..part }],
|
||||
vec![Part { channels: &long_channel, ..part }],
|
||||
vec![Part { channels: &empty_name, ..part }],
|
||||
vec![Part { channels: &[], ..part }],
|
||||
vec![Part { data_window: Window { width: 0, ..WINDOW }, ..part }],
|
||||
vec![Part { data_window: Window { x: i32::MAX, ..WINDOW }, ..part }],
|
||||
vec![Part { data_window: Window { width: 1 << 27, ..WINDOW }, ..part }],
|
||||
vec![Part { data_window: Window { height: 1 << 21, ..WINDOW }, compression: Compression::Zip1, ..part }],
|
||||
] {
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let result = write_scanlines(&mut out, WINDOW, &parts, |_, _, _, _| panic!("invalid descriptors reached callback"));
|
||||
assert!(matches!(result, Err(Error::Encode(_))), "{parts:?}: {result:?}");
|
||||
assert!(out.get_ref().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_rows_and_callback_errors_stop_writing() {
|
||||
let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let mut calls = 0;
|
||||
let short = write_scanlines(&mut Cursor::new(Vec::new()), WINDOW, &[part], |_, _, _, row| {
|
||||
calls += 1;
|
||||
Ok(row.len() - 1)
|
||||
});
|
||||
assert!(matches!(short, Err(Error::Encode(message)) if message.contains("expected 64 samples, got 63")));
|
||||
assert_eq!(calls, 1);
|
||||
|
||||
let stopped = Error::Encode("source became unavailable".into());
|
||||
let result = write_scanlines(&mut Cursor::new(Vec::new()), WINDOW, &[part], |_, _, _, _| Err(stopped.clone()));
|
||||
assert_eq!(result, Err(stopped));
|
||||
}
|
||||
|
||||
struct LimitedOutput<'a> {
|
||||
cursor: Cursor<Vec<u8>>,
|
||||
limit: &'a Cell<u64>,
|
||||
}
|
||||
|
||||
impl Write for LimitedOutput<'_> {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
if self.cursor.position() + bytes.len() as u64 > self.limit.get() {
|
||||
return Err(io::Error::other("synthetic full disk"));
|
||||
}
|
||||
self.cursor.write(bytes)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Seek for LimitedOutput<'_> {
|
||||
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
|
||||
self.cursor.seek(position)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_are_written_before_requesting_more_rows() {
|
||||
let limit = Cell::new(u64::MAX);
|
||||
let mut out = LimitedOutput { cursor: Cursor::new(Vec::new()), limit: &limit };
|
||||
let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 };
|
||||
let mut rows = 0;
|
||||
let result = write_scanlines(&mut out, WINDOW, &[part], |_, _, _, row| {
|
||||
rows += 1;
|
||||
// Let the header and offset placeholders through, then fail the first block write.
|
||||
limit.set(0);
|
||||
Ok(row.len())
|
||||
});
|
||||
assert!(matches!(result, Err(Error::Encode(message)) if message.contains("synthetic full disk")));
|
||||
assert!(rows > 0 && rows < WINDOW.height, "received {rows} rows before first block write");
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
//! FilmCraft `.fcproj` JSON envelope, version detection and historical migrations.
|
||||
//! Project and editor-view types are supplied by the caller.
|
||||
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
|
||||
pub mod records;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
/// The `format` tag written in every envelope.
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Reversible record boundaries for a FilmCraft project. A bin owns an ordered list of
|
||||
//! references; each project item (including a sequence) has one payload. Fields outside
|
||||
//! those boundaries stay in their original JSON objects, including editor and extension data.
|
||||
//!
|
||||
//! These types describe logical records, independent of directory names, hashing, and commits.
|
||||
|
||||
use crate::{FormatError, MIGRATIONS, check_supported, detect_bytes, migrate_with};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
type Result<T> = std::result::Result<T, FormatError>;
|
||||
type Payloads = BTreeMap<u64, Value>;
|
||||
|
||||
// Reassembly follows links between separately supplied records, outside the JSON parser's
|
||||
// recursion limit. A repeated or cyclic bin is also rejected on its second visit.
|
||||
const MAX_BIN_DEPTH: usize = 64;
|
||||
|
||||
/// The envelope carries the root bin ID and a complete inventory of item IDs, including
|
||||
/// items outside any bin. The map keys are persisted project IDs, never display names.
|
||||
#[derive(Debug)]
|
||||
pub struct ProjectRecords {
|
||||
pub envelope: Value,
|
||||
pub bins: BTreeMap<u64, Value>,
|
||||
pub items: BTreeMap<u64, Value>,
|
||||
}
|
||||
|
||||
fn corrupt(message: impl Into<String>) -> FormatError {
|
||||
FormatError::Corrupt(message.into())
|
||||
}
|
||||
|
||||
fn object_id(value: &Value) -> Result<u64> {
|
||||
value.get("id").and_then(Value::as_u64).ok_or_else(|| corrupt("record lacks an unsigned id"))
|
||||
}
|
||||
|
||||
fn children(bin: &mut Value, depth: usize) -> Result<&mut Vec<Value>> {
|
||||
if depth > MAX_BIN_DEPTH {
|
||||
return Err(corrupt("bin nesting exceeds the supported depth"));
|
||||
}
|
||||
bin.get_mut("children").and_then(Value::as_array_mut).ok_or_else(|| corrupt("bin lacks children"))
|
||||
}
|
||||
|
||||
// Only nested bins change representation. Item references retain their original position.
|
||||
fn nested_or_item<'a>(child: &'a mut Value, items: &Payloads) -> Result<Option<&'a mut Value>> {
|
||||
let entry = child.as_object_mut().filter(|o| o.len() == 1).ok_or_else(|| corrupt("invalid bin entry"))?;
|
||||
if let Some(item) = entry.get("Item") {
|
||||
let id = item.as_u64().ok_or_else(|| corrupt("invalid item reference"))?;
|
||||
if !items.contains_key(&id) {
|
||||
return Err(corrupt(format!("bin references missing item {id}")));
|
||||
}
|
||||
Ok(None)
|
||||
} else {
|
||||
entry.get_mut("Bin").map(Some).ok_or_else(|| corrupt("unknown bin entry"))
|
||||
}
|
||||
}
|
||||
|
||||
fn split_bin(mut bin: Value, bins: &mut Payloads, items: &Payloads, depth: usize) -> Result<u64> {
|
||||
let id = object_id(&bin)?;
|
||||
for child in children(&mut bin, depth)? {
|
||||
if let Some(nested) = nested_or_item(child, items)? {
|
||||
*nested = Value::from(split_bin(nested.take(), bins, items, depth + 1)?);
|
||||
}
|
||||
}
|
||||
if bins.insert(id, bin).is_some() {
|
||||
return Err(corrupt(format!("duplicate bin id {id}")));
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn join_bin(reference: &Value, bins: &mut Payloads, items: &Payloads, depth: usize) -> Result<Value> {
|
||||
let id = reference.as_u64().ok_or_else(|| corrupt("invalid bin reference"))?;
|
||||
let mut bin = bins.remove(&id).ok_or_else(|| corrupt(format!("missing or repeated bin {id}")))?;
|
||||
if object_id(&bin)? != id {
|
||||
return Err(corrupt(format!("bin payload does not match id {id}")));
|
||||
}
|
||||
for child in children(&mut bin, depth)? {
|
||||
if let Some(nested) = nested_or_item(child, items)? {
|
||||
*nested = join_bin(nested, bins, items, depth + 1)?;
|
||||
}
|
||||
}
|
||||
Ok(bin)
|
||||
}
|
||||
|
||||
impl ProjectRecords {
|
||||
/// Split supported project bytes, applying the same historical migrations as the
|
||||
/// ordinary reader. Callers reading from storage must bound input size before parsing.
|
||||
pub fn split(bytes: &[u8]) -> Result<Self> {
|
||||
let version = detect_bytes(bytes)?;
|
||||
let doc = serde_json::from_slice(bytes).map_err(|e| corrupt(e.to_string()))?;
|
||||
let mut envelope = migrate_with(MIGRATIONS, doc, version)?;
|
||||
let project = envelope.get_mut("project").and_then(Value::as_object_mut).ok_or_else(|| corrupt("missing project"))?;
|
||||
let Some(Value::Object(payloads)) = project.remove("items") else { return Err(corrupt("missing project items")) };
|
||||
let mut items = Payloads::new();
|
||||
let mut inventory = Vec::with_capacity(payloads.len());
|
||||
for (key, value) in payloads {
|
||||
let id = object_id(&value)?;
|
||||
if id.to_string() != key {
|
||||
return Err(corrupt(format!("item key does not match id {id}")));
|
||||
}
|
||||
items.insert(id, value);
|
||||
inventory.push(Value::from(id));
|
||||
}
|
||||
project.insert("items".into(), Value::Array(inventory));
|
||||
let root = project.get_mut("root").ok_or_else(|| corrupt("missing root bin"))?;
|
||||
let mut bins = Payloads::new();
|
||||
*root = Value::from(split_bin(root.take(), &mut bins, &items, 0)?);
|
||||
Ok(Self { envelope, bins, items })
|
||||
}
|
||||
|
||||
/// Reassemble a complete set, refusing missing, extra or misidentified payloads.
|
||||
/// A successful result preserves the migrated document as JSON, including unknown
|
||||
/// fields; the application still validates timeline and media semantics on load.
|
||||
pub fn into_document(mut self) -> Result<Value> {
|
||||
let probe = crate::Probe::deserialize(&self.envelope).map_err(|e| corrupt(e.to_string()))?;
|
||||
check_supported(crate::probe_version(&probe)?)?;
|
||||
let project = self.envelope.get_mut("project").and_then(Value::as_object_mut).ok_or_else(|| corrupt("missing project"))?;
|
||||
let root = project.get_mut("root").ok_or_else(|| corrupt("missing root bin"))?;
|
||||
*root = join_bin(root, &mut self.bins, &self.items, 0)?;
|
||||
if !self.bins.is_empty() {
|
||||
return Err(corrupt("unreferenced bin payload"));
|
||||
}
|
||||
let Some(Value::Array(ids)) = project.remove("items") else { return Err(corrupt("missing item inventory")) };
|
||||
let mut items = Map::new();
|
||||
for key in ids {
|
||||
let id = key.as_u64().ok_or_else(|| corrupt("invalid item inventory entry"))?;
|
||||
let item = self.items.remove(&id).ok_or_else(|| corrupt(format!("missing or repeated item {id}")))?;
|
||||
if object_id(&item)? != id {
|
||||
return Err(corrupt(format!("item payload does not match id {id}")));
|
||||
}
|
||||
items.insert(id.to_string(), item);
|
||||
}
|
||||
if !self.items.is_empty() {
|
||||
return Err(corrupt("unreferenced item payload"));
|
||||
}
|
||||
project.insert("items".into(), Value::Object(items));
|
||||
Ok(self.envelope)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Original, generated project fragments exercise record ownership and preservation.
|
||||
use craft_fcproj_format::{FormatError, MIGRATIONS, SCHEMA_VERSION, migrate_with, records::ProjectRecords};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn project() -> Value {
|
||||
json!({
|
||||
"format": "filmcraft.project", "schema_version": SCHEMA_VERSION, "view": {"tabs":[12]},
|
||||
"generator": "test", "extra": [null, {}],
|
||||
"project": {
|
||||
"root": {"id":0,"name":"Cut","children":[
|
||||
{"Item":12},{"Bin":{"id":19,"name":"Cut","children":[{"Item":4}]}}
|
||||
]},
|
||||
"items": {
|
||||
"4":{"id":4,"media":{"path":"../offline/shot.mov"},"label":"A"},
|
||||
"12":{"id":12,"sequence":{"nested":[4],"duration":123}},
|
||||
"9":{"id":9,"name":"Unfiled","extra":{}}
|
||||
},
|
||||
"next_id":20, "transcripts":{}, "new_project_field":{"value":null}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn split(doc: &Value) -> ProjectRecords {
|
||||
ProjectRecords::split(&serde_json::to_vec(doc).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_one_sequence_preserves_all_other_records_and_the_view() {
|
||||
let original = project();
|
||||
let mut changed = original.clone();
|
||||
changed["project"]["items"]["12"]["sequence"]["duration"] = json!(124);
|
||||
let before = split(&original);
|
||||
let after = split(&changed);
|
||||
assert_eq!(before.envelope, after.envelope);
|
||||
assert_eq!(before.bins, after.bins);
|
||||
assert_eq!(before.items.keys().filter(|id| before.items[id] != after.items[id]).copied().collect::<Vec<_>>(), [12]);
|
||||
assert_eq!(before.into_document().unwrap(), original);
|
||||
assert_eq!(after.into_document().unwrap(), changed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_uses_the_same_migrations_and_future_versions_are_refused() {
|
||||
let mut bare = project()["project"].take();
|
||||
bare["version"] = json!(1);
|
||||
assert_eq!(split(&bare).into_document().unwrap(), migrate_with(MIGRATIONS, bare, 1).unwrap());
|
||||
let mut doc = project();
|
||||
doc["schema_version"] = json!(SCHEMA_VERSION + 1);
|
||||
assert!(matches!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()), Err(FormatError::TooNew { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_or_conflicting_records_cannot_be_reassembled() {
|
||||
let make = || split(&project());
|
||||
let mut missing = make();
|
||||
missing.items.remove(&9); // Unfiled; a bin traversal alone cannot detect the lost item.
|
||||
assert!(missing.into_document().is_err());
|
||||
let mut extra = make();
|
||||
extra.items.insert(11, json!({"id":11}));
|
||||
assert!(extra.into_document().is_err());
|
||||
let mut cycle = make();
|
||||
cycle.bins.get_mut(&19).unwrap()["children"] = json!([{"Bin":0}]);
|
||||
assert!(cycle.into_document().is_err());
|
||||
let mut mismatch = make();
|
||||
mismatch.items.get_mut(&4).unwrap()["id"] = json!(19);
|
||||
assert!(mismatch.into_document().is_err());
|
||||
let mut detached = make();
|
||||
detached.bins.get_mut(&0).unwrap()["children"] = json!([]);
|
||||
assert!(detached.into_document().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversion_refuses_ambiguous_bins_and_dangling_membership() {
|
||||
let mut doc = project();
|
||||
doc["project"]["root"]["children"][1]["Bin"]["id"] = json!(0);
|
||||
assert!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()).is_err());
|
||||
doc["project"]["root"]["children"] = json!([{"Item":100}]);
|
||||
assert!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()).is_err());
|
||||
}
|
||||
@@ -529,6 +529,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec<Para> {
|
||||
wrap: None,
|
||||
index: None,
|
||||
group: None,
|
||||
item: p.props.list_item.filter(|_| list.is_none()).map(|l| l.min(8)),
|
||||
};
|
||||
if opts.paras {
|
||||
out.extra = para_extra(doc, &p.props);
|
||||
@@ -579,6 +580,8 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec<Para> {
|
||||
wrap: None,
|
||||
index: None,
|
||||
group: None,
|
||||
// A list item's further paragraph, each piece of it.
|
||||
item: out.item,
|
||||
};
|
||||
let prev = std::mem::replace(&mut out, next);
|
||||
if prev.inlines.is_empty() {
|
||||
@@ -952,9 +955,50 @@ fn kept_index(doc: &Document, bl: &Blocks, i: usize) -> Option<(usize, std::sync
|
||||
(paras.len() == *n && craft_wordmodel::kept::run_fingerprint(paras.into_iter()) == *run).then(|| (*n, xml.clone()))
|
||||
}
|
||||
|
||||
/// Where the text of each level's last numbered paragraph starts, points.
|
||||
type ItemText = [Option<f32>; 9];
|
||||
|
||||
/// The flow paragraphs of `p`, a list item's further paragraph only while it still sits at its
|
||||
/// item's text: one moved out of it (Enter, then Decrease Indent to the margin, the ruler, the
|
||||
/// Paragraph dialog…) is body text after the list. Asked of the paragraph itself, so whichever
|
||||
/// command moved it, the paragraph is where it shows.
|
||||
fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemText) -> Vec<Para> {
|
||||
let rp = doc.styles.resolve_para(&p.props);
|
||||
// (Its own indent, or its style's.)
|
||||
let left = rp.indent_left;
|
||||
let mut paras = flow_paras_in(doc, p, opts);
|
||||
if let Some(n) = rp.numbering.filter(|n| n.num != 0) {
|
||||
// The paragraph's own indent, else its level's, else its style's (as Word places it).
|
||||
let level = doc.numbering.level(n.num, n.level).map(|l| l.indent);
|
||||
// Nonzero character indents override point indents, including an explicit zero.
|
||||
let text = if rp.indent_chars[0] != 0.0 { left } else { p.props.indent_left.or(level).unwrap_or(left) };
|
||||
if let Some(t) = at.get_mut(usize::from(n.level)) {
|
||||
*t = Some(text);
|
||||
}
|
||||
} else if let Some(l) = p.props.list_item {
|
||||
// Before any numbered paragraph, an explicit header has no prior baseline to outdent from.
|
||||
let kept = match at.get(usize::from(l)).copied().flatten() {
|
||||
Some(text) => left >= text - 0.5,
|
||||
None => true,
|
||||
};
|
||||
if !kept {
|
||||
for q in &mut paras {
|
||||
q.item = None;
|
||||
}
|
||||
// Moved out of its item, it is body text: the lists before it have ended.
|
||||
*at = [None; 9];
|
||||
}
|
||||
} else {
|
||||
// Body text: the lists before it have ended, and where their items' text was with them.
|
||||
*at = [None; 9];
|
||||
}
|
||||
paras
|
||||
}
|
||||
|
||||
fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> Vec<FBlock> {
|
||||
let mut out = Vec::new();
|
||||
let mut skip = 0usize;
|
||||
let mut at: ItemText = [None; 9];
|
||||
for (i, b) in bl.iter().enumerate() {
|
||||
if skip > 0 {
|
||||
skip -= 1;
|
||||
@@ -969,7 +1013,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) ->
|
||||
let from = out.len();
|
||||
for b in bl.get(i..i + ix.0).unwrap_or(&[]) {
|
||||
if let Block::Para(p) = &**b {
|
||||
out.extend(flow_paras_in(doc, p, tracked).into_iter().map(FBlock::Para));
|
||||
out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para));
|
||||
}
|
||||
}
|
||||
let n = out.len() - from;
|
||||
@@ -980,7 +1024,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) ->
|
||||
continue;
|
||||
}
|
||||
match &**b {
|
||||
Block::Para(p) => out.extend(flow_paras_in(doc, p, tracked).into_iter().map(FBlock::Para)),
|
||||
Block::Para(p) => out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)),
|
||||
Block::Table(t) if depth < MAX_DEPTH => out.push(FBlock::Table(flow_table(doc, t, depth, tracked))),
|
||||
Block::Table(t) => {
|
||||
for r in &t.rows {
|
||||
@@ -1105,6 +1149,8 @@ fn with_cell_text(doc: &Document, blocks: &Blocks, chr: &CharProps, align: Optio
|
||||
if !table.is_empty() {
|
||||
let mut props = doc.styles.table_para_patch(&p.props, &table);
|
||||
props.overlay(&p.props);
|
||||
// Direct only, so no overlay carries it: a list item's further paragraph stays one.
|
||||
props.list_item = p.props.list_item;
|
||||
p.props = props;
|
||||
}
|
||||
Arc::new(Block::Para(p))
|
||||
|
||||
@@ -26,6 +26,7 @@ mod media;
|
||||
pub mod odf_object;
|
||||
mod to_doc;
|
||||
mod types;
|
||||
pub use types::continues_list;
|
||||
|
||||
pub use color::parse_color;
|
||||
pub use from_doc::{
|
||||
@@ -210,4 +211,149 @@ mod tests {
|
||||
p.trim();
|
||||
assert_eq!(p.inlines, vec![Inline::Text("a ".into(), i), Inline::Text("b".into(), b)]);
|
||||
}
|
||||
|
||||
/// Paragraphs of `text` in order, each with its props set by `set`.
|
||||
fn doc_of(paras: &[(&str, &dyn Fn(&mut craft_wordmodel::ParaProps))]) -> craft_wordmodel::Document {
|
||||
let mut doc = craft_wordmodel::Document::new();
|
||||
doc.body = paras
|
||||
.iter()
|
||||
.map(|(t, set)| {
|
||||
let mut p = craft_wordmodel::Paragraph::with_text(t, Default::default());
|
||||
set(&mut p.props);
|
||||
std::sync::Arc::new(craft_wordmodel::Block::Para(p))
|
||||
})
|
||||
.collect();
|
||||
doc
|
||||
}
|
||||
|
||||
/// The text and `item` of each flow paragraph, a table cell's included.
|
||||
fn items(blocks: &[FBlock]) -> Vec<(String, Option<u8>)> {
|
||||
let mut out = Vec::new();
|
||||
for b in blocks {
|
||||
match b {
|
||||
FBlock::Para(p) => out.push((p.text(), p.item)),
|
||||
FBlock::Table(t) => {
|
||||
for c in t.rows.iter().flatten() {
|
||||
out.extend(items(&c.blocks));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_indents_set_the_list_continuation_baseline() {
|
||||
let mut doc = craft_wordmodel::Document::new();
|
||||
let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered);
|
||||
let numbered = move |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.numbering = Some(NumRef { num, level: 0 });
|
||||
p.indent_left = Some(0.0);
|
||||
p.indent_left_chars = Some(6.0);
|
||||
};
|
||||
let outdented = |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.list_item = Some(0);
|
||||
p.indent_left = Some(0.0);
|
||||
};
|
||||
doc.body = doc_of(&[("One", &numbered), ("Out", &outdented)]).body;
|
||||
let got = items(&from_doc(&doc).blocks);
|
||||
assert_eq!(got.iter().find(|r| r.0 == "Out").map(|r| r.1), Some(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_indent_header_keeps_its_explicit_list_membership() {
|
||||
let header = |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.list_item = Some(0);
|
||||
p.indent_left = Some(0.0);
|
||||
};
|
||||
let doc = doc_of(&[("Header", &header)]);
|
||||
assert_eq!(items(&from_doc(&doc).blocks), [("Header".into(), Some(0))]);
|
||||
}
|
||||
|
||||
/// A list item's further paragraph cut by a page break is that paragraph on both pages: the
|
||||
/// text after the break stays in the item too.
|
||||
#[test]
|
||||
fn a_further_paragraph_stays_in_its_item_past_a_page_break() {
|
||||
let cont = |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.list_item = Some(0);
|
||||
p.indent_left = Some(36.0);
|
||||
};
|
||||
let doc = doc_of(&[("Before\u{c}After", &cont)]);
|
||||
let got = items(&from_doc(&doc).blocks);
|
||||
assert_eq!(got, [("Before".to_string(), Some(0)), ("After".to_string(), Some(0))], "{got:?}");
|
||||
}
|
||||
|
||||
/// Body text ends the lists before it: a list starting with a header (no number) at its text
|
||||
/// is a list's paragraph however far an earlier list's text was indented.
|
||||
#[test]
|
||||
fn a_list_header_after_body_text_is_in_its_list() {
|
||||
let mut doc = craft_wordmodel::Document::new();
|
||||
let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered);
|
||||
let numbered = move |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.numbering = Some(NumRef { num, level: 0 });
|
||||
p.indent_left = Some(72.0);
|
||||
};
|
||||
let header = |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.list_item = Some(0);
|
||||
p.indent_left = Some(36.0);
|
||||
};
|
||||
let numbered_36 = move |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.numbering = Some(NumRef { num, level: 0 });
|
||||
p.indent_left = Some(36.0);
|
||||
};
|
||||
let body = doc_of(&[("One", &numbered), ("Body", &|_| {}), ("Header", &header), ("Two", &numbered_36)]).body;
|
||||
doc.body = body;
|
||||
let got = items(&from_doc(&doc).blocks);
|
||||
assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}");
|
||||
}
|
||||
|
||||
/// A further paragraph moved out of its item (to the margin) is body text: a list starting with
|
||||
/// a header after it, less indented than the list before, keeps the header in its list.
|
||||
#[test]
|
||||
fn a_list_header_after_an_outdented_further_paragraph_is_in_its_list() {
|
||||
let mut doc = craft_wordmodel::Document::new();
|
||||
let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered);
|
||||
let numbered = move |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.numbering = Some(NumRef { num, level: 0 });
|
||||
p.indent_left = Some(72.0);
|
||||
};
|
||||
let outdented = |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.list_item = Some(0);
|
||||
p.indent_left = Some(0.0);
|
||||
};
|
||||
let header = |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.list_item = Some(0);
|
||||
p.indent_left = Some(36.0);
|
||||
};
|
||||
let numbered_36 = move |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.numbering = Some(NumRef { num, level: 0 });
|
||||
p.indent_left = Some(36.0);
|
||||
};
|
||||
let body = doc_of(&[("One", &numbered), ("Out", &outdented), ("Header", &header), ("Two", &numbered_36)]).body;
|
||||
doc.body = body;
|
||||
let got = items(&from_doc(&doc).blocks);
|
||||
assert_eq!(got.iter().find(|r| r.0 == "Out").map(|r| r.1), Some(None), "{got:?}");
|
||||
assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}");
|
||||
}
|
||||
|
||||
/// A list item's further paragraph in a table cell a table style formats stays one.
|
||||
#[test]
|
||||
fn a_further_paragraph_in_a_styled_cell_stays_in_its_item() {
|
||||
let cont = |p: &mut craft_wordmodel::ParaProps| {
|
||||
p.list_item = Some(0);
|
||||
p.indent_left = Some(36.0);
|
||||
};
|
||||
let mut doc = craft_wordmodel::Document::new();
|
||||
// Table Grid: paragraph formatting of its own (no space after, single spacing).
|
||||
let mut t = craft_wordmodel::table::Table::new(1, 1, 200.0);
|
||||
if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) {
|
||||
c.blocks = doc_of(&[("Cont", &cont)]).body;
|
||||
}
|
||||
doc.body = vec![
|
||||
std::sync::Arc::new(craft_wordmodel::Block::Table(t)),
|
||||
std::sync::Arc::new(craft_wordmodel::Block::Para(craft_wordmodel::Paragraph::new())),
|
||||
];
|
||||
let got = items(&from_doc_with(&doc, FlowOpts { paras: true, ..Default::default() }).blocks);
|
||||
assert_eq!(got.iter().find(|r| r.0 == "Cont").map(|r| r.1), Some(Some(0)), "{got:?}");
|
||||
}
|
||||
}
|
||||
@@ -158,6 +158,9 @@ fn para_props(p: &Para, list_num: Option<u32>) -> ParaProps {
|
||||
}
|
||||
out.numbering = Some(NumRef { num, level: li.level.min(8) });
|
||||
}
|
||||
if p.list.is_none() {
|
||||
out.list_item = p.item.map(|l| l.min(8));
|
||||
}
|
||||
out.align = p.align;
|
||||
if p.rtl {
|
||||
out.bidi = Some(true);
|
||||
@@ -766,6 +769,12 @@ impl<'a> Builder<'a> {
|
||||
|
||||
fn blocks(&mut self, blocks: &[FBlock], depth: usize) -> Blocks {
|
||||
let mut out = Blocks::new();
|
||||
// Each list the source numbers, all of it in these blocks: a run of it after a paragraph
|
||||
// it doesn't number may be the first to use a level.
|
||||
let mut of_list: std::collections::HashMap<u32, Vec<ListInfo>> = std::collections::HashMap::new();
|
||||
for li in blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { p.list } else { None }).filter(|li| li.list != 0) {
|
||||
of_list.entry(li.list).or_default().push(li);
|
||||
}
|
||||
let mut i = 0;
|
||||
while let Some(b) = blocks.get(i) {
|
||||
match b {
|
||||
@@ -779,7 +788,14 @@ impl<'a> Builder<'a> {
|
||||
let mut top: Option<bool> = None;
|
||||
let id = p.list.map_or(0, |l| l.list);
|
||||
while let Some(FBlock::Para(q)) = blocks.get(j) {
|
||||
let Some(li) = q.list else { break };
|
||||
let Some(li) = q.list else {
|
||||
// An item's further paragraph is in the list: it goes on after it.
|
||||
if super::continues_list(blocks, j).is_some() {
|
||||
j += 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
};
|
||||
if li.list != id {
|
||||
break;
|
||||
}
|
||||
@@ -795,7 +811,9 @@ impl<'a> Builder<'a> {
|
||||
let num = match self.lists.get(&id) {
|
||||
Some(num) if id != 0 => *num,
|
||||
_ => {
|
||||
let num = self.new_list(&group);
|
||||
// First met here, so this is the only time it's asked for.
|
||||
let all = if id == 0 { group } else { of_list.remove(&id).unwrap_or(group) };
|
||||
let num = self.new_list(&all);
|
||||
if id != 0 {
|
||||
self.lists.insert(id, num);
|
||||
}
|
||||
|
||||
@@ -716,6 +716,9 @@ pub struct Para {
|
||||
pub index: Option<Box<(std::sync::Arc<str>, usize)>>,
|
||||
/// The group of paragraphs its markup kept as read belongs to (see [`Group`]).
|
||||
pub group: Option<Box<Group>>,
|
||||
/// A list item's further paragraph, with no number of its own (`list` is `None`): the level
|
||||
/// of the item it belongs to.
|
||||
pub item: Option<u8>,
|
||||
}
|
||||
|
||||
/// Paragraphs whose markup kept as read ties them together (a comment from one to another, a
|
||||
@@ -1107,3 +1110,14 @@ pub fn ruby_as_text(inlines: &[Inline]) -> std::borrow::Cow<'_, [Inline]> {
|
||||
pub fn clean_text(s: &str) -> String {
|
||||
s.chars().filter(|c| *c != OBJ && (!c.is_control() || matches!(c, '\t' | '\n' | '\u{000C}' | '\u{000E}'))).collect()
|
||||
}
|
||||
|
||||
/// Whether the paragraph at `i` in `blocks` is a list item's further paragraph, and the level of
|
||||
/// its item: HTML and Markdown keep it in its item, so the list doesn't start again after it.
|
||||
/// A plain paragraph or a heading (ODF's `text:h` may sit in a list item); the writers have no
|
||||
/// way to put the other kinds in an item.
|
||||
pub fn continues_list(blocks: &[FBlock], i: usize) -> Option<u8> {
|
||||
match blocks.get(i) {
|
||||
Some(FBlock::Para(p)) if p.list.is_none() && matches!(p.kind, Kind::Normal | Kind::Heading(_)) => p.item.map(|l| l.min(8)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -433,7 +433,19 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize, spaced: bool)
|
||||
// Nested lists from consecutive list paragraphs.
|
||||
let mut stack: Vec<(bool, bool)> = Vec::new(); // (ordered, li open)
|
||||
while let Some(FBlock::Para(q)) = blocks.get(i) {
|
||||
let Some(li) = q.list else { break };
|
||||
let Some(li) = q.list else {
|
||||
// A list item's further paragraph, in its item (its sublists end first).
|
||||
let Some(lv) = model::continues_list(blocks, i).map(usize::from) else { break };
|
||||
while stack.len() > lv + 1 {
|
||||
close_list(&mut stack, out);
|
||||
}
|
||||
if stack.len() != lv + 1 || !stack.last().is_some_and(|s| s.1) {
|
||||
break;
|
||||
}
|
||||
out.push_str(¶_html(q, false));
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
let lv = li.level.min(8) as usize;
|
||||
while stack.len() > lv + 1 {
|
||||
close_list(&mut stack, out);
|
||||
|
||||
@@ -985,6 +985,18 @@ fn hostile_style_sheets_never_panic() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A list item's further paragraph keeps its alignment (and page break) in its item.
|
||||
#[test]
|
||||
fn an_items_further_paragraph_keeps_its_alignment() {
|
||||
let mut one = Para { list: Some(model::ListInfo { ordered: true, ..Default::default() }), ..Default::default() };
|
||||
one.push_text("One", &Fmt::default());
|
||||
let mut cont = Para { item: Some(0), align: Some(Align::Center), ..Default::default() };
|
||||
cont.spacing.left = Some(36.0);
|
||||
cont.push_text("Cont", &Fmt::default());
|
||||
let html = export(&model::to_doc(&Flow { blocks: vec![FBlock::Para(one), FBlock::Para(cont)], meta: Meta::default() }));
|
||||
assert!(html.contains("<li>One<p style=\"text-align:center\">Cont</p></li>"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_mso_vmerge_declarations_last_wins() {
|
||||
let html_restart_wins = "<table><tr><td style='mso-yfti-vmerge: continue; mso-yfti-vmerge: restart'>A</td></tr></table>";
|
||||
@@ -2153,6 +2165,28 @@ fn the_fragment_spaces_only_top_level_paragraphs_and_headings() {
|
||||
assert!(fragment.contains("<ul><li>Item</li></ul>"), "{fragment}");
|
||||
}
|
||||
|
||||
/// A list item's further paragraph keeps its alignment and page break in the fragment, without
|
||||
/// spacing or indents, as the item itself.
|
||||
#[test]
|
||||
fn the_fragment_leaves_a_list_items_further_paragraph_unspaced() {
|
||||
let chr = craft_wordmodel::CharProps::default();
|
||||
let mut d = Document::new();
|
||||
let num = std::sync::Arc::make_mut(&mut d.numbering).add_list(craft_wordmodel::ListKind::Bullet);
|
||||
let mut item = craft_wordmodel::Paragraph::with_text("Item", chr.clone()).styled("ListParagraph");
|
||||
item.props.numbering = Some(craft_wordmodel::props::NumRef { num, level: 0 });
|
||||
let mut more = craft_wordmodel::Paragraph::with_text("More", chr);
|
||||
more.props.list_item = Some(0);
|
||||
more.props.align = Some(craft_wordmodel::Align::Center);
|
||||
more.props.page_break_before = Some(true);
|
||||
more.props.indent_left = Some(72.0);
|
||||
more.props.space_after = Some(6.0);
|
||||
d.body = vec![craft_wordmodel::para_block(item), craft_wordmodel::para_block(more)];
|
||||
let fragment = export_fragment(&d);
|
||||
let more = fragment.split("<li>Item").nth(1).and_then(|s| s.split("</li>").next()).unwrap();
|
||||
assert!(more.contains("More") && more.contains("text-align:center") && more.contains("break-before:page"), "{fragment}");
|
||||
assert!(!fragment.contains("margin-"), "{fragment}");
|
||||
}
|
||||
|
||||
/// Code blocks and the paragraphs of a table cell keep the fragment's plain markup, whatever their
|
||||
/// spacing.
|
||||
#[test]
|
||||
|
||||
@@ -127,15 +127,14 @@ fn container_rotation_is_applied_once() {
|
||||
|
||||
#[test]
|
||||
fn exif_and_xmp_survive_and_exif_orientation_is_not_applied_twice() {
|
||||
let img = decode(with_exif()).unwrap();
|
||||
// HEIF's EXIF Orientation repeats what irot says; the container is the authority.
|
||||
let tagged = with_exif_orientation(with_exif(), 6);
|
||||
let img = decode(&tagged).unwrap();
|
||||
assert_eq!(img.dimensions(), (2048, 1536));
|
||||
let exif = img.meta.exif.as_deref().unwrap();
|
||||
assert!(exif.starts_with(b"MM\0*"), "TIFF-structured EXIF, without the HEIF offset header");
|
||||
assert!(img.meta.xmp.as_deref().unwrap().contains("x:xmpmeta"));
|
||||
|
||||
// HEIF's EXIF Orientation repeats what irot says; the container is the authority.
|
||||
let tagged = with_exif_orientation(with_exif(), 6);
|
||||
let img = decode(&tagged).unwrap();
|
||||
assert_eq!(img.dimensions(), (2048, 1536), "not turned by the EXIF tag");
|
||||
assert_eq!(exif_orientation(img.meta.exif.as_deref().unwrap()), 1, "rewritten so exports don't turn it either");
|
||||
let raw = decode_with(&tagged, &keep()).unwrap();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! [`LassoTool`]: the freehand Lasso with Alt-latched straight segments, and the pieces the Polygonal Lasso shares.
|
||||
|
||||
use craft_behavior::geometry::{ConstrainStyle, DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft, SelectionOperation};
|
||||
use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerButton, PointerGlyph};
|
||||
use craft_behavior::{CancelReason, Cursor, CursorIcon, PaintedCursor, PointerButton, PointerGlyph};
|
||||
use craft_keymap::{Key, Mods};
|
||||
use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon};
|
||||
@@ -53,7 +53,8 @@ pub(super) struct LassoCursor<'a> {
|
||||
|
||||
/// The arrow with its tip on the point the outline starts from, the lasso icon below and right of it and the
|
||||
/// operation's badge beside the icon: the latched one while an outline is open, else the live modifiers';
|
||||
/// Cmd is the Move tool's, so it shows none. Over the selection, the cursors of [`cursor_over`].
|
||||
/// Cmd is the Move tool's, so it shows none. Under the canvas's precise cursor, the crosshair with the badge. Over the
|
||||
/// selection, the cursors of [`cursor_over`].
|
||||
pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &ToolContext<'_>) -> Cursor {
|
||||
let LassoCursor { icon, draft, operation, bar, inside, rule } = shown;
|
||||
if !draft.is_open()
|
||||
@@ -69,6 +70,11 @@ pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &T
|
||||
} else {
|
||||
SelectionOperation::resolve(*bar, cx.mods, probe.has_selection()).badge()
|
||||
};
|
||||
// Under the canvas's precise cursor (Other Cursors > Precise, swapped by Caps Lock) the pointer is the crosshair,
|
||||
// its centre the point the outline takes, with the operation's badge.
|
||||
if cx.precise() {
|
||||
return badge.map_or(CursorIcon::Crosshair.into(), |badge| PaintedCursor::badged(CursorIcon::Crosshair, badge).into());
|
||||
}
|
||||
PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, icon.icon(), badge).into()
|
||||
}
|
||||
|
||||
|
||||
@@ -951,6 +951,37 @@ fn the_magnetic_lasso_shows_the_width_circle_under_the_precise_cursor() {
|
||||
}
|
||||
}
|
||||
|
||||
// The Lasso and the Polygonal Lasso follow the canvas's precise cursor too (Other Cursors > Precise, swapped by Caps
|
||||
// Lock): the crosshair, its centre the point the outline takes, while it is on; the arrow with the lasso icon otherwise.
|
||||
// Before, Caps Lock left the arrow and icon in place.
|
||||
#[trial]
|
||||
fn the_lassos_show_the_crosshair_under_the_precise_cursor() {
|
||||
use craft_behavior::{Cursor, CursorIcon, PaintedCursor, PointerGlyph};
|
||||
fn check<T: Reports + 'static>(mut rig: Rig<T>, what: &str)
|
||||
where
|
||||
for<'a> SelectToolPass<'a, T>: CanvasTool,
|
||||
{
|
||||
let over = rig.canvas().center();
|
||||
let ctx = rig.fixture().ctx().clone();
|
||||
rig.fixture().frame(vec![pointer::moved(over)]);
|
||||
for caps_lock in [false, true, false] {
|
||||
craft_ui::runtime::windows::WindowHost::of(&ctx).set_caps_lock(Some(caps_lock));
|
||||
rig.fixture().frame(Vec::new());
|
||||
rig.fixture().frame(Vec::new());
|
||||
let cursor = craft_ui::runtime::cursor::current(&ctx);
|
||||
let crosshair = matches!(
|
||||
cursor,
|
||||
Some(Cursor::System(CursorIcon::Crosshair) | Cursor::Painted(PaintedCursor::Badged { base: CursorIcon::Crosshair, .. }))
|
||||
);
|
||||
let arrow = matches!(cursor, Some(Cursor::Painted(PaintedCursor::PointerTool { pointer: PointerGlyph::Arrow, .. })));
|
||||
assert_eq!(crosshair, caps_lock, "{what}, Caps Lock {caps_lock}: {cursor:?}");
|
||||
assert_eq!(arrow, !caps_lock, "{what}, Caps Lock {caps_lock}: {cursor:?}");
|
||||
}
|
||||
}
|
||||
check(rig("Lasso", LassoTool::new(), Fake::empty()), "Lasso");
|
||||
check(rig("Polygonal Lasso", PolygonLassoTool::new(), Fake::empty()), "Polygonal Lasso");
|
||||
}
|
||||
|
||||
/// The cursor `rig` shows over the middle of its canvas with `mods` held.
|
||||
fn lasso_cursor<T: Reports + 'static>(rig: &mut Rig<T>, mods: Modifiers) -> Option<craft_behavior::Cursor>
|
||||
where
|
||||
|
||||
@@ -14,3 +14,7 @@ workspace = true
|
||||
craft-flow = { workspace = true }
|
||||
craft-html = { workspace = true }
|
||||
craft-wordmodel = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# A test writes imported Markdown to HTML, to check a list stays one there.
|
||||
craft-html = { workspace = true, features = ["flow"] }
|
||||
@@ -593,6 +593,19 @@ fn parse_quote(lines: &[String], i: &mut usize, depth: usize, level: u8, refs: &
|
||||
&& p.kind == Kind::Normal
|
||||
{
|
||||
p.kind = Kind::Quote;
|
||||
// A quoted list item's further paragraph: the writers keep only plain paragraphs in
|
||||
// an item, so it joins the item's last paragraph with a line break, as a block in an
|
||||
// item does, and the list goes on after it.
|
||||
if p.item.is_some() {
|
||||
p.item = None;
|
||||
if let Some(FBlock::Para(prev)) = out.last_mut()
|
||||
&& prev.list.is_some()
|
||||
{
|
||||
prev.push_text("\n", &Fmt::default());
|
||||
prev.inlines.append(&mut p.inlines);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(block);
|
||||
}
|
||||
@@ -682,21 +695,31 @@ fn parse_list(lines: &[String], mut i: usize, depth: usize, level: u8, out: &mut
|
||||
}
|
||||
for b in inner {
|
||||
match b {
|
||||
FBlock::Para(mut p) if p.list.is_none() => {
|
||||
FBlock::Para(mut p) if p.list.is_none() && p.item.is_none() => {
|
||||
if !placed {
|
||||
p.list = Some(li);
|
||||
placed = true;
|
||||
out.push(FBlock::Para(p));
|
||||
} else if p.kind == Kind::Normal {
|
||||
// The item's further paragraph: one with no number, at the item's text.
|
||||
p.item = Some(li.level);
|
||||
p.spacing.left = Some((f32::from(li.level) + 1.0) * 36.0);
|
||||
p.spacing.first = Some(0.0);
|
||||
} else if let Some(FBlock::Para(prev)) = out.last_mut()
|
||||
&& prev.list.is_some_and(|x| x.level == li.level)
|
||||
&& (prev.list.is_some_and(|x| x.level >= li.level) || prev.item.is_some_and(|l| l >= li.level))
|
||||
{
|
||||
// A continuation paragraph joins the item with a line break.
|
||||
// A code block, quote or heading in the item joins the item's last
|
||||
// paragraph, a sublist's included, with a line break: it is no item of
|
||||
// its own, and only a plain paragraph is read as a further one.
|
||||
prev.push_text("\n", &Fmt::default());
|
||||
prev.inlines.extend(p.inlines);
|
||||
continue;
|
||||
} else {
|
||||
p.list = Some(li);
|
||||
out.push(FBlock::Para(p));
|
||||
// One after a table: no number either, at the item's text.
|
||||
p.item = Some(li.level);
|
||||
p.spacing.left = Some((f32::from(li.level) + 1.0) * 36.0);
|
||||
p.spacing.first = Some(0.0);
|
||||
}
|
||||
out.push(FBlock::Para(p));
|
||||
}
|
||||
FBlock::Para(p) => {
|
||||
if !placed {
|
||||
|
||||
@@ -335,6 +335,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec<String>) {
|
||||
let mut i = 0;
|
||||
let mut counters = [0u32; 9];
|
||||
let mut prev_list = false;
|
||||
// How far each level's last item's text is indented (where its further paragraphs go), and
|
||||
// the level of the last item.
|
||||
let mut conts = [0usize; 9];
|
||||
let mut prev_level = 0usize;
|
||||
let mut prev_top_ordered = false;
|
||||
while let Some(b) = blocks.get(i) {
|
||||
match b {
|
||||
@@ -365,6 +369,8 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec<String>) {
|
||||
}
|
||||
FBlock::Para(p) => {
|
||||
let body = inlines_md(&p.inlines);
|
||||
// A further paragraph of an item still open: its level.
|
||||
let in_item = model::continues_list(blocks, i).map(usize::from).filter(|lv| prev_list && *lv <= prev_level);
|
||||
match p.list {
|
||||
Some(li) => {
|
||||
let lv = li.level.min(8) as usize;
|
||||
@@ -387,6 +393,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec<String>) {
|
||||
let marker = if li.ordered { format!("{}.", n.unwrap_or(1)) } else { "-".to_string() };
|
||||
let pad = " ".repeat(4 * lv);
|
||||
let cont = " ".repeat(4 * lv + marker.len() + 1);
|
||||
if let Some(c) = conts.get_mut(lv) {
|
||||
*c = cont.len();
|
||||
}
|
||||
prev_level = lv;
|
||||
let body = if p.kind == Kind::Code {
|
||||
code_span(&p.text())
|
||||
} else {
|
||||
@@ -408,6 +418,22 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec<String>) {
|
||||
out.push(String::new());
|
||||
}
|
||||
}
|
||||
// A list item's further paragraph: in its item, and the list goes on after it.
|
||||
None if in_item.is_some() => {
|
||||
let lv = in_item.unwrap_or_default();
|
||||
prev_level = lv;
|
||||
// A sublist after it is a new one.
|
||||
for d in counters.iter_mut().skip(lv + 1) {
|
||||
*d = 0;
|
||||
}
|
||||
let pad = " ".repeat(conts.get(lv).copied().unwrap_or(0));
|
||||
let text = match p.kind {
|
||||
Kind::Heading(n) => format!("{} {}", "#".repeat(n.clamp(1, 6) as usize), heading_text(&body)),
|
||||
_ => escape_lines(body).replace("\\\n", &format!("\\\n{pad}")),
|
||||
};
|
||||
out.push(format!("{pad}{text}").trim_end().to_string());
|
||||
out.push(String::new());
|
||||
}
|
||||
None => {
|
||||
prev_list = false;
|
||||
let line = match p.kind {
|
||||
|
||||
@@ -793,3 +793,90 @@ fn heading_trailing_hash_survives_round_trip() {
|
||||
assert_eq!(export(&import(&md)), want, "second export of {src:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A list item's further paragraph is read as a paragraph of its own in the item, with no number:
|
||||
/// written and read again, it stays one, and the list goes on after it.
|
||||
#[test]
|
||||
fn an_items_further_paragraph_round_trips() {
|
||||
let src = "1. One\n\n Cont\n\n2. Two\n - Sub\n\n More\n";
|
||||
let shape = |d: &Document| {
|
||||
d.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.map(|n| n.num), p.props.indent_left)).collect::<Vec<_>>()
|
||||
};
|
||||
let d = import(src);
|
||||
let rows = shape(&d);
|
||||
assert_eq!(rows.iter().map(|r| r.0.as_str()).collect::<Vec<_>>(), ["One", "Cont", "Two", "Sub", "More"], "{rows:?}");
|
||||
for (t, at) in [("Cont", 36.0), ("More", 36.0)] {
|
||||
let r = rows.iter().find(|r| r.0 == t).unwrap();
|
||||
assert_eq!((r.1, r.2), (None, Some(at)), "{t}: no number, at the item's text: {rows:?}");
|
||||
}
|
||||
assert_eq!(rows[0].1, rows[2].1, "one list: {rows:?}");
|
||||
let md = export(&d);
|
||||
assert!(md.starts_with("1. One\n\n Cont\n\n2. Two\n"), "{md}");
|
||||
assert!(md.contains("\n\n More"), "{md}");
|
||||
assert_eq!(shape(&import(&md)), rows, "{md}");
|
||||
// A numbered sublist after an item's further paragraph starts again.
|
||||
let md = export(&import("1. One\n 1. a\n 2. b\n\n More\n\n 1. c\n"));
|
||||
assert!(md.contains("\n 1. c"), "{md}");
|
||||
}
|
||||
|
||||
/// A code block, quote or heading inside a list item is no item of its own: it gets no number,
|
||||
/// and the list's next item keeps its number (#5723 review).
|
||||
#[test]
|
||||
fn a_block_inside_an_item_gets_no_number() {
|
||||
let numbered =
|
||||
|d: &Document| d.body.iter().filter_map(|b| b.as_para()).filter(|p| p.props.numbering.is_some()).map(|p| p.text.clone()).collect::<Vec<_>>();
|
||||
for (src, last) in [
|
||||
("1. Install:\n\n ```\n cargo build\n cargo test\n ```\n\n2. Run\n", "2. Run"),
|
||||
("1. Install:\n\n > quoted\n\n2. Run\n", "2. Run"),
|
||||
("1. Install:\n\n # Heading\n\n2. Run\n", "2. Run"),
|
||||
("1. Install:\n\n Cont\n\n ```\n cargo build\n ```\n\n2. Run\n", "2. Run"),
|
||||
] {
|
||||
let d = import(src);
|
||||
let rows = numbered(&d);
|
||||
assert_eq!(rows.len(), 2, "{src:?}: two numbered items: {rows:?}");
|
||||
assert!(rows[0].starts_with("Install:"), "{src:?}: {rows:?}");
|
||||
assert_eq!(rows[1], "Run", "{src:?}: {rows:?}");
|
||||
let md = export(&d);
|
||||
assert!(md.contains(&format!("\n{last}")), "{src:?}: {md}");
|
||||
assert!(!md.contains("3."), "{src:?}: {md}");
|
||||
}
|
||||
let d = import("1. Install:\n\n ```\n cargo build\n cargo test\n ```\n\n2. Run\n");
|
||||
assert!(numbered(&d)[0].contains("cargo build") && numbered(&d)[0].contains("cargo test"), "the code stays in its item: {:?}", numbered(&d));
|
||||
}
|
||||
|
||||
/// A code block, quote or heading after a sublist in an item stays in the list: the list's next
|
||||
/// item keeps its number in Markdown and HTML (#5723 review).
|
||||
#[test]
|
||||
fn a_block_after_a_sublist_keeps_the_next_items_number() {
|
||||
for src in
|
||||
["1. a\n - sub\n\n ```\n code\n ```\n2. b\n", "1. a\n - sub\n\n > quoted\n\n2. b\n", "1. a\n - sub\n\n # Heading\n\n2. b\n"]
|
||||
{
|
||||
let d = import(src);
|
||||
let text: String = d.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::<Vec<_>>().join("|");
|
||||
for w in ["code", "quoted", "Heading"] {
|
||||
if src.contains(w) {
|
||||
assert!(text.contains(w), "{src:?}: the block's text stays: {text}");
|
||||
}
|
||||
}
|
||||
let md = export(&d);
|
||||
assert!(md.contains("\n2. b"), "{src:?}: {md}");
|
||||
let html = craft_html::doc::export(&d);
|
||||
assert_eq!(html.matches("<ol").count(), 1, "{src:?}: one list: {html}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A quoted list item's further paragraph stays in its item: the list goes on after it, in the
|
||||
/// quote, and keeps its numbers.
|
||||
#[test]
|
||||
fn a_quoted_items_further_paragraph_keeps_the_list() {
|
||||
let d = import("> 1. One\n>\n> Cont\n>\n> 2. Two\n");
|
||||
let nums: Vec<u32> = d.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect();
|
||||
assert_eq!(nums.len(), 2, "{nums:?}");
|
||||
assert_eq!(nums[0], nums[1], "one list: {nums:?}");
|
||||
let text: String = d.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::<Vec<_>>().join("|");
|
||||
assert!(text.contains("Cont"), "{text}");
|
||||
let md = export(&d);
|
||||
assert!(md.contains("> 2. Two") && !md.contains("> 1. Two"), "{md}");
|
||||
let html = craft_html::doc::export(&d);
|
||||
assert_eq!(html.matches("<ol").count(), 1, "one list: {html}");
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
autotests = false
|
||||
name = "craft-media"
|
||||
description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, an MPEG-TS/PS demuxer and MPEG-TS muxer, and Ogg and AVI demuxers."
|
||||
description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, an MPEG-TS/PS demuxer and MPEG-TS muxer, and Ogg, AVI and Bink demuxers."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -21,6 +21,8 @@ isobmff = ["bitstream", "dep:thiserror"]
|
||||
matroska = []
|
||||
# AVI (RIFF) and OpenDML demuxer and muxer (`craft_media::avi`).
|
||||
avi = []
|
||||
# Bink 1 (BIK) demuxer (`craft_media::bink`).
|
||||
bink = []
|
||||
# MXF demuxer and writer (`craft_media::mxf`); the writer formats dates with chrono.
|
||||
mxf = ["dep:chrono"]
|
||||
# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`), and the
|
||||
|
||||
+37
-1
@@ -21,6 +21,7 @@ that codec crates use to describe a file and configure a decoder.
|
||||
| `matroska` | `craft_media::matroska` | none |
|
||||
| `ogg` | `craft_media::ogg` | none |
|
||||
| `avi` | `craft_media::avi` | none |
|
||||
| `bink` | `craft_media::bink` | none |
|
||||
| `mxf` | `craft_media::mxf` | `chrono` |
|
||||
| `mpegts` | `craft_media::mpegts` | none |
|
||||
| `vmd` | `craft_media::vmd` | none |
|
||||
@@ -29,7 +30,7 @@ that codec crates use to describe a file and configure a decoder.
|
||||
|
||||
`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`, `mpegts` and `vmd` are opt-in as well. The features are independent.
|
||||
do not read Matroska. `ogg`, `avi`, `bink`, `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"] }
|
||||
@@ -474,6 +475,41 @@ audio pages at a byte or packet target, and can replace the final granule positi
|
||||
end trimming. `opus_tags` and `vorbis_comment` build the comment headers; tag names that are not
|
||||
valid field names (Vorbis I §5.2.1) are left out.
|
||||
|
||||
## `bink`
|
||||
|
||||
A clean-room Bink 1 (`.bik`) demuxer. Bink has no published specification: the layout follows the
|
||||
public description of the container on the MultimediaWiki (`wiki.multimedia.cx`, "Bink Container")
|
||||
and was checked against ffprobe on real files. No FFmpeg or other Bink implementation was read;
|
||||
ffprobe is a test oracle only. No muxer.
|
||||
|
||||
```rust
|
||||
use craft_media::bink::open;
|
||||
|
||||
let file = open(&bytes)?; // any ByteSource
|
||||
let video = file.video_params(); // CodecId::BinkVideo, signature as tag, size, flags as extradata
|
||||
for i in 0..file.frames.len() {
|
||||
let frame = file.read_frame(&bytes, i)?;
|
||||
let packets = file.split_frame(&frame)?; // one optional packet per audio track, then video
|
||||
}
|
||||
```
|
||||
|
||||
| Part | |
|
||||
|---|---|
|
||||
| Header | signature and revision letter, frame count, picture size, frame rate, video flags (alpha, grayscale, scaling) |
|
||||
| Audio tracks | sample rate, stereo flag, RDFT or DCT form (`CodecId::BinkAudioRdft` / `BinkAudioDct`), track ID |
|
||||
| Index | one offset per frame; bit 0 marks a key frame |
|
||||
| Frames | per audio track a length, decoded size and packet; the video packet is the rest |
|
||||
| Damage | a truncated file opens with the frames that are whole |
|
||||
|
||||
Limits, each with a test: at most 256 audio tracks and a picture of at most 32767 by 32767 (more
|
||||
is refused), and a frame table bounded by the index entries the file could hold. Bink 2 files
|
||||
(`KB2`) are refused with `Error::Bink2`.
|
||||
|
||||
Tests: hand-built files, truncation, invalid headers and random damage (never a panic).
|
||||
`tests/oracle_bink.rs` compares the stream, size and key flag of every packet with ffprobe's for the `.bik` files
|
||||
under `CRAFT_BINK_SAMPLES`, and is skipped when that is not set: no tool here writes Bink
|
||||
files, and existing ones are not ours to commit.
|
||||
|
||||
## `avi`
|
||||
|
||||
A clean-room AVI demuxer from FilmCraft's `filmcraft-avi` (storytold/filmcraft@4bec22b), and a
|
||||
|
||||
@@ -0,0 +1,372 @@
|
||||
//! Clean-room Bink (`.bik`) demuxer for Bink 1 files.
|
||||
//!
|
||||
//! Bink has no published specification. The layout here follows the public description of the
|
||||
//! container on the MultimediaWiki (`wiki.multimedia.cx`, "Bink Container") and was checked
|
||||
//! against what ffprobe reports for real files: frame count, key frames and packet sizes.
|
||||
//!
|
||||
//! [`open`] reads the 44-byte header, the audio track headers and the frame index, and builds a
|
||||
//! table of [`Frame`]s. A frame holds one packet per audio track and then one video packet;
|
||||
//! [`BinkFile::read_frame`] reads a frame and [`split_frame`] separates its packets.
|
||||
//!
|
||||
//! Every size and count comes from the file and is treated as hostile: the frame table is bounded
|
||||
//! by the number of index entries the file could hold, and every frame lies inside the file. A
|
||||
//! truncated file opens with the frames that are complete.
|
||||
//!
|
||||
//! 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;
|
||||
|
||||
/// Size of the main header in bytes.
|
||||
const HEADER_LEN: usize = 44;
|
||||
/// The most audio tracks a file may declare.
|
||||
const MAX_AUDIO_TRACKS: u32 = 256;
|
||||
/// The largest width or height a file may declare.
|
||||
const MAX_DIMENSION: u32 = 32767;
|
||||
/// Index entries read at a time: 64 KiB.
|
||||
const INDEX_PIECE_ENTRIES: u64 = 16384;
|
||||
|
||||
/// Errors from reading a Bink file.
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// Not a Bink file (no `BIK` signature).
|
||||
NotBink,
|
||||
/// A Bink 2 file (`KB2` signature), which this module does not read.
|
||||
Bink2,
|
||||
/// 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::NotBink => f.write_str("not a Bink file"),
|
||||
Error::Bink2 => f.write_str("Bink 2 files are not supported"),
|
||||
Error::Io(e) => write!(f, "I/O error: {e}"),
|
||||
Error::Invalid(e) => write!(f, "invalid Bink file: {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>;
|
||||
|
||||
fn invalid<T>(msg: impl Into<String>) -> Result<T> {
|
||||
Err(Error::Invalid(msg.into()))
|
||||
}
|
||||
|
||||
/// Whether `head` starts like a Bink 1 file: `BIK` and a lower-case revision letter.
|
||||
pub fn sniff(head: &[u8]) -> bool {
|
||||
head.get(..3) == Some(b"BIK") && head.get(3).is_some_and(u8::is_ascii_lowercase)
|
||||
}
|
||||
|
||||
/// The main header.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
/// The four signature bytes: `BIK` and the codec revision letter (`b`, `d`, `f`, `g`, `h`, `i`).
|
||||
pub signature: [u8; 4],
|
||||
/// The frame count the header declares.
|
||||
pub frames: u32,
|
||||
/// The size in bytes of the largest frame, as declared.
|
||||
pub largest_frame: u32,
|
||||
/// Picture width in pixels.
|
||||
pub width: u32,
|
||||
/// Picture height in pixels.
|
||||
pub height: u32,
|
||||
/// Frame rate numerator.
|
||||
pub fps_num: u32,
|
||||
/// Frame rate denominator.
|
||||
pub fps_den: u32,
|
||||
/// The video flags as stored; see [`Header::has_alpha`], [`Header::grayscale`] and
|
||||
/// [`Header::scaling`].
|
||||
pub video_flags: u32,
|
||||
}
|
||||
|
||||
impl Header {
|
||||
/// The codec revision letter (`b'i'` for `BIKi`).
|
||||
pub fn revision(&self) -> u8 {
|
||||
self.signature[3]
|
||||
}
|
||||
|
||||
/// Whether frames carry an alpha plane (flag bit 20).
|
||||
pub fn has_alpha(&self) -> bool {
|
||||
self.video_flags & (1 << 20) != 0
|
||||
}
|
||||
|
||||
/// Whether the video is grayscale (flag bit 17).
|
||||
pub fn grayscale(&self) -> bool {
|
||||
self.video_flags & (1 << 17) != 0
|
||||
}
|
||||
|
||||
/// The display scaling mode (flag bits 28 to 31): 1 height doubled, 2 height interlaced,
|
||||
/// 3 width doubled, 4 width and height doubled, 5 width and height interlaced.
|
||||
pub fn scaling(&self) -> u8 {
|
||||
(self.video_flags >> 28) as u8
|
||||
}
|
||||
}
|
||||
|
||||
/// An audio track header.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AudioTrack {
|
||||
/// Samples per second.
|
||||
pub sample_rate: u16,
|
||||
/// The track flags as stored; see [`AudioTrack::stereo`] and [`AudioTrack::dct`].
|
||||
pub flags: u16,
|
||||
/// The track ID.
|
||||
pub id: u32,
|
||||
}
|
||||
|
||||
impl AudioTrack {
|
||||
/// Whether the track is stereo (flag bit 13).
|
||||
pub fn stereo(&self) -> bool {
|
||||
self.flags & (1 << 13) != 0
|
||||
}
|
||||
|
||||
/// Whether the track uses the DCT form of Bink Audio (flag bit 12); otherwise the RDFT form.
|
||||
pub fn dct(&self) -> bool {
|
||||
self.flags & (1 << 12) != 0
|
||||
}
|
||||
|
||||
/// Codec parameters for a decoder: the codec, sample rate and channel count.
|
||||
pub fn codec_params(&self) -> crate::CodecParams {
|
||||
let id = if self.dct() { crate::CodecId::BinkAudioDct } else { crate::CodecId::BinkAudioRdft };
|
||||
crate::CodecParams::new(id).with_sample_rate(u32::from(self.sample_rate)).with_channels(if self.stereo() { 2 } else { 1 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Where one frame lies in the file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Frame {
|
||||
/// Absolute file offset of the frame.
|
||||
pub offset: u64,
|
||||
/// Size of the frame in bytes: its audio packets and its video packet.
|
||||
pub size: u32,
|
||||
/// Whether the index marks the frame as a key frame.
|
||||
pub key: bool,
|
||||
}
|
||||
|
||||
/// An opened Bink file: header, audio tracks and frame table.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BinkFile {
|
||||
/// The main header.
|
||||
pub header: Header,
|
||||
/// The audio tracks, in file order.
|
||||
pub audio: Vec<AudioTrack>,
|
||||
/// The frames that lie completely inside the file, in order. Shorter than
|
||||
/// [`Header::frames`] when the file is truncated.
|
||||
pub frames: Vec<Frame>,
|
||||
}
|
||||
|
||||
/// One audio track's packet in a frame.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AudioPacket<'a> {
|
||||
/// The count stored before the packet: the size in bytes of the PCM the packet decodes to.
|
||||
pub decoded_len: u32,
|
||||
/// The Bink Audio packet.
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
/// The packets of one frame, borrowed from the frame's bytes.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FramePackets<'a> {
|
||||
/// One entry per audio track; `None` when the track has no audio in this frame.
|
||||
pub audio: Vec<Option<AudioPacket<'a>>>,
|
||||
/// The Bink Video packet.
|
||||
pub video: &'a [u8],
|
||||
}
|
||||
|
||||
fn le32(b: &[u8], at: usize) -> u32 {
|
||||
match b.get(at..at + 4) {
|
||||
Some(&[a, b, c, d]) => u32::from_le_bytes([a, b, c, d]),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn le16(b: &[u8], at: usize) -> u16 {
|
||||
match b.get(at..at + 2) {
|
||||
Some(&[a, b]) => u16::from_le_bytes([a, b]),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the headers and the frame index of a Bink 1 file.
|
||||
pub fn open<S: ByteSource + ?Sized>(src: &S) -> Result<BinkFile> {
|
||||
let len = src.len();
|
||||
let mut head = [0u8; HEADER_LEN];
|
||||
if len < HEADER_LEN as u64 {
|
||||
// long enough to tell the signature apart, too short to be a file
|
||||
let mut sig = [0u8; 4];
|
||||
if len >= 4 {
|
||||
src.read_at(0, &mut sig)?;
|
||||
}
|
||||
return match sig {
|
||||
_ if sig.starts_with(b"KB2") => Err(Error::Bink2),
|
||||
_ if sniff(&sig) => invalid("file shorter than the header"),
|
||||
_ => Err(Error::NotBink),
|
||||
};
|
||||
}
|
||||
src.read_at(0, &mut head)?;
|
||||
if head.starts_with(b"KB2") {
|
||||
return Err(Error::Bink2);
|
||||
}
|
||||
if !sniff(&head) {
|
||||
return Err(Error::NotBink);
|
||||
}
|
||||
let header = Header {
|
||||
signature: [head[0], head[1], head[2], head[3]],
|
||||
frames: le32(&head, 8),
|
||||
largest_frame: le32(&head, 12),
|
||||
width: le32(&head, 20),
|
||||
height: le32(&head, 24),
|
||||
fps_num: le32(&head, 28),
|
||||
fps_den: le32(&head, 32),
|
||||
video_flags: le32(&head, 36),
|
||||
};
|
||||
let tracks = le32(&head, 40);
|
||||
if header.width == 0 || header.height == 0 || header.width > MAX_DIMENSION || header.height > MAX_DIMENSION {
|
||||
return invalid(format!("picture size {}x{}", header.width, header.height));
|
||||
}
|
||||
if header.fps_num == 0 || header.fps_den == 0 {
|
||||
return invalid("zero frame rate");
|
||||
}
|
||||
if tracks > MAX_AUDIO_TRACKS {
|
||||
return invalid(format!("{tracks} audio tracks"));
|
||||
}
|
||||
let tracks = tracks as usize;
|
||||
|
||||
// three tables of 4 bytes per track: (unknown, channels), (sample rate, flags), ID
|
||||
let mut audio_head = vec![0u8; tracks * 12];
|
||||
src.read_at(HEADER_LEN as u64, &mut audio_head).map_err(|_| Error::Invalid("audio track headers cut off".into()))?;
|
||||
let audio = (0..tracks)
|
||||
.map(|t| AudioTrack {
|
||||
sample_rate: le16(&audio_head, tracks * 4 + t * 4),
|
||||
flags: le16(&audio_head, tracks * 4 + t * 4 + 2),
|
||||
id: le32(&audio_head, tracks * 8 + t * 4),
|
||||
})
|
||||
.collect();
|
||||
|
||||
// the index: one absolute offset per frame and one for the end of the last frame
|
||||
let index_at = (HEADER_LEN + tracks * 12) as u64;
|
||||
// `len` was taken before the reads above: a source that reports less than it serves (a file
|
||||
// still being written) must not make this wrap
|
||||
let Some(room) = len.checked_sub(index_at) else { return invalid("audio track headers cut off") };
|
||||
if header.frames == 0 {
|
||||
return invalid("no frames");
|
||||
}
|
||||
// as many entries as the file declares and could hold
|
||||
let mut left = (u64::from(header.frames) + 1).min(room / 4);
|
||||
let data_start = index_at + (u64::from(header.frames) + 1) * 4;
|
||||
// The index is read in pieces and each entry checked as it arrives, so a hostile frame
|
||||
// count costs one piece, not the index it claims. The table grows as entries prove valid.
|
||||
let mut frames = Vec::new();
|
||||
let mut at = index_at;
|
||||
let mut previous: Option<u32> = None;
|
||||
let mut piece = Vec::new();
|
||||
'index: while left > 0 {
|
||||
let entries = left.min(INDEX_PIECE_ENTRIES) as usize;
|
||||
piece.resize(entries * 4, 0);
|
||||
src.read_at(at, &mut piece)?;
|
||||
for bytes in piece.as_chunks::<4>().0 {
|
||||
let entry = u32::from_le_bytes(*bytes);
|
||||
if let Some(start) = previous {
|
||||
let (offset, end) = (u64::from(start & !1), u64::from(entry & !1));
|
||||
if end > len {
|
||||
break 'index; // truncated file: keep the frames that are whole
|
||||
}
|
||||
if offset < data_start || end < offset {
|
||||
return invalid(format!("frame {} at {offset}..{end}", frames.len()));
|
||||
}
|
||||
frames.push(Frame { offset, size: (end - offset) as u32, key: start & 1 != 0 });
|
||||
}
|
||||
previous = Some(entry);
|
||||
}
|
||||
at += (entries * 4) as u64;
|
||||
left -= entries as u64;
|
||||
}
|
||||
Ok(BinkFile { header, audio, frames })
|
||||
}
|
||||
|
||||
impl BinkFile {
|
||||
/// Codec parameters of the video: [`CodecId::BinkVideo`], the picture size, the signature as
|
||||
/// `tag` (its fourth byte is the codec revision) and the video flags, little-endian, as
|
||||
/// `extradata`.
|
||||
///
|
||||
/// [`CodecId::BinkVideo`]: crate::CodecId::BinkVideo
|
||||
pub fn video_params(&self) -> crate::CodecParams {
|
||||
crate::CodecParams::new(crate::CodecId::BinkVideo)
|
||||
.with_tag(self.header.signature)
|
||||
.with_size(self.header.width, self.header.height)
|
||||
.with_extradata(self.header.video_flags.to_le_bytes())
|
||||
}
|
||||
|
||||
/// Reads frame `i`: its audio packets and its video packet, as stored. [`split_frame`]
|
||||
/// separates them.
|
||||
pub fn read_frame<S: ByteSource + ?Sized>(&self, src: &S, i: usize) -> Result<Vec<u8>> {
|
||||
let Some(f) = self.frames.get(i) else { return invalid(format!("no frame {i}")) };
|
||||
// `open` checked the frame against the length the source had then
|
||||
if f.offset.checked_add(u64::from(f.size)).is_none_or(|e| e > src.len()) {
|
||||
return invalid(format!("frame {i} past the end of the file"));
|
||||
}
|
||||
// A frame can be up to 4 GiB. Reserving it can fail, and on a 32-bit target a size past
|
||||
// `isize::MAX` cannot be asked for at all: that is an error, not a panic.
|
||||
let mut data = Vec::new();
|
||||
let reserved = usize::try_from(f.size).ok().and_then(|size| data.try_reserve_exact(size).ok().map(|()| size));
|
||||
let Some(size) = reserved else { return invalid(format!("frame {i} of {} bytes is too large to read", f.size)) };
|
||||
data.resize(size, 0);
|
||||
src.read_at(f.offset, &mut data)?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// Separates the packets of a frame read with [`BinkFile::read_frame`].
|
||||
pub fn split_frame<'a>(&self, frame: &'a [u8]) -> Result<FramePackets<'a>> {
|
||||
split_frame(frame, self.audio.len())
|
||||
}
|
||||
}
|
||||
|
||||
/// Separates the packets of a frame of a file with `tracks` audio tracks.
|
||||
///
|
||||
/// Each track has a 32-bit length; when it is not zero, a 32-bit decoded size and the packet
|
||||
/// follow, and the length covers both. The video packet is what remains.
|
||||
pub fn split_frame(frame: &[u8], tracks: usize) -> Result<FramePackets<'_>> {
|
||||
let mut rest = frame;
|
||||
// a track takes at least its 4-byte length, which bounds the table
|
||||
let mut audio = Vec::with_capacity(tracks.min(frame.len() / 4));
|
||||
for t in 0..tracks {
|
||||
let Some((len, after)) = rest.split_first_chunk::<4>() else { return invalid(format!("audio track {t}: length cut off")) };
|
||||
let len = u32::from_le_bytes(*len) as usize;
|
||||
if len == 0 {
|
||||
audio.push(None);
|
||||
rest = after;
|
||||
continue;
|
||||
}
|
||||
let Some((packet, after)) = after.split_at_checked(len) else { return invalid(format!("audio track {t}: packet of {len} bytes cut off")) };
|
||||
let Some((decoded_len, data)) = packet.split_first_chunk::<4>() else { return invalid(format!("audio track {t}: packet of {len} bytes")) };
|
||||
audio.push(Some(AudioPacket { decoded_len: u32::from_le_bytes(*decoded_len), data }));
|
||||
rest = after;
|
||||
}
|
||||
Ok(FramePackets { audio, video: rest })
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
use super::*;
|
||||
|
||||
/// One frame of a hand-built file: its audio packets (decoded size and data) and video packet.
|
||||
struct TestFrame {
|
||||
key: bool,
|
||||
audio: Vec<Option<(u32, Vec<u8>)>>,
|
||||
video: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Builds a Bink file with one `(sample rate, flags)` pair per audio track.
|
||||
fn bink(signature: &[u8; 4], tracks: &[(u16, u16)], frames: &[TestFrame]) -> Vec<u8> {
|
||||
let bodies: Vec<Vec<u8>> = frames
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let mut b = Vec::new();
|
||||
for a in &f.audio {
|
||||
match a {
|
||||
None => b.extend_from_slice(&0u32.to_le_bytes()),
|
||||
Some((decoded, data)) => {
|
||||
b.extend_from_slice(&(data.len() as u32 + 4).to_le_bytes());
|
||||
b.extend_from_slice(&decoded.to_le_bytes());
|
||||
b.extend_from_slice(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
b.extend_from_slice(&f.video);
|
||||
// bit 0 of an index entry is the key frame flag, so a frame starts at an even offset
|
||||
assert_eq!(b.len() % 4, 0, "frames are built in whole 32-bit words");
|
||||
b
|
||||
})
|
||||
.collect();
|
||||
let data_start = HEADER_LEN + tracks.len() * 12 + (frames.len() + 1) * 4;
|
||||
let total = data_start + bodies.iter().map(Vec::len).sum::<usize>();
|
||||
let largest = bodies.iter().map(Vec::len).max().unwrap_or(0);
|
||||
let mut d = signature.to_vec();
|
||||
for v in [total - 8, frames.len(), largest, frames.len(), 320, 240, 2997, 100, 1 << 20, tracks.len()] {
|
||||
d.extend_from_slice(&(v as u32).to_le_bytes());
|
||||
}
|
||||
for &(_, flags) in tracks {
|
||||
d.extend_from_slice(&0x0e00u16.to_le_bytes());
|
||||
d.extend_from_slice(&(if flags & (1 << 13) != 0 { 2u16 } else { 1 }).to_le_bytes());
|
||||
}
|
||||
for &(rate, flags) in tracks {
|
||||
d.extend_from_slice(&rate.to_le_bytes());
|
||||
d.extend_from_slice(&flags.to_le_bytes());
|
||||
}
|
||||
for t in 0..tracks.len() {
|
||||
d.extend_from_slice(&(t as u32 + 7).to_le_bytes());
|
||||
}
|
||||
let mut at = data_start;
|
||||
for (f, b) in frames.iter().zip(&bodies) {
|
||||
d.extend_from_slice(&(at as u32 | u32::from(f.key)).to_le_bytes());
|
||||
at += b.len();
|
||||
}
|
||||
d.extend_from_slice(&(at as u32).to_le_bytes());
|
||||
for b in &bodies {
|
||||
d.extend_from_slice(b);
|
||||
}
|
||||
assert_eq!(d.len(), total);
|
||||
d
|
||||
}
|
||||
|
||||
fn sample() -> Vec<u8> {
|
||||
bink(
|
||||
b"BIKi",
|
||||
&[(22050, 0x7000), (44100, 0x4000)],
|
||||
&[
|
||||
TestFrame { key: true, audio: vec![Some((1024, vec![1, 2, 3, 4])), Some((512, vec![9; 8]))], video: vec![0xAA; 16] },
|
||||
TestFrame { key: false, audio: vec![None, Some((512, vec![8; 4]))], video: vec![0xBB; 12] },
|
||||
TestFrame { key: false, audio: vec![None, None], video: vec![0xCC; 20] },
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_header_tracks_and_frames() {
|
||||
let d = sample();
|
||||
assert!(sniff(&d));
|
||||
let f = open(&d).unwrap();
|
||||
assert_eq!(f.header.signature, *b"BIKi");
|
||||
assert_eq!(f.header.revision(), b'i');
|
||||
assert_eq!((f.header.frames, f.header.width, f.header.height), (3, 320, 240));
|
||||
assert_eq!((f.header.fps_num, f.header.fps_den), (2997, 100));
|
||||
assert!(f.header.has_alpha());
|
||||
assert!(!f.header.grayscale());
|
||||
assert_eq!(f.header.scaling(), 0);
|
||||
assert_eq!(f.header.largest_frame, 8 + 4 + 8 + 8 + 16);
|
||||
|
||||
assert_eq!(f.audio.len(), 2);
|
||||
assert_eq!((f.audio[0].sample_rate, f.audio[0].stereo(), f.audio[0].dct(), f.audio[0].id), (22050, true, true, 7));
|
||||
assert_eq!((f.audio[1].sample_rate, f.audio[1].stereo(), f.audio[1].dct(), f.audio[1].id), (44100, false, false, 8));
|
||||
let a = f.audio[0].codec_params();
|
||||
assert_eq!((a.codec, a.sample_rate, a.channels), (crate::CodecId::BinkAudioDct, Some(22050), Some(2)));
|
||||
let a = f.audio[1].codec_params();
|
||||
assert_eq!((a.codec, a.sample_rate, a.channels), (crate::CodecId::BinkAudioRdft, Some(44100), Some(1)));
|
||||
|
||||
let v = f.video_params();
|
||||
assert_eq!((v.codec, v.tag, v.width, v.height), (crate::CodecId::BinkVideo, Some(*b"BIKi"), Some(320), Some(240)));
|
||||
assert_eq!(v.extradata, (1u32 << 20).to_le_bytes());
|
||||
|
||||
assert_eq!(f.frames.iter().map(|f| f.key).collect::<Vec<_>>(), [true, false, false]);
|
||||
assert_eq!(f.frames.iter().map(|f| f.size).collect::<Vec<_>>(), [44, 28, 28]);
|
||||
assert_eq!(f.frames.last().map(|f| f.offset + u64::from(f.size)), Some(d.len() as u64));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_a_frame_into_its_packets() {
|
||||
let d = sample();
|
||||
let f = open(&d).unwrap();
|
||||
let frame = f.read_frame(&d, 0).unwrap();
|
||||
let p = f.split_frame(&frame).unwrap();
|
||||
assert_eq!(p.audio[0], Some(AudioPacket { decoded_len: 1024, data: &[1, 2, 3, 4] }));
|
||||
assert_eq!(p.audio[1], Some(AudioPacket { decoded_len: 512, data: &[9; 8] }));
|
||||
assert_eq!(p.video, [0xAA; 16]);
|
||||
|
||||
let frame = f.read_frame(&d, 1).unwrap();
|
||||
let p = f.split_frame(&frame).unwrap();
|
||||
assert_eq!(p.audio, [None, Some(AudioPacket { decoded_len: 512, data: &[8; 4] })]);
|
||||
assert_eq!(p.video, [0xBB; 12]);
|
||||
|
||||
let frame = f.read_frame(&d, 2).unwrap();
|
||||
let p = f.split_frame(&frame).unwrap();
|
||||
assert_eq!(p.audio, [None, None]);
|
||||
assert_eq!(p.video, [0xCC; 20]);
|
||||
|
||||
assert!(matches!(f.read_frame(&d, 3), Err(Error::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_without_audio_has_only_video_packets() {
|
||||
let d = bink(b"BIKf", &[], &[TestFrame { key: true, audio: vec![], video: vec![1, 2, 3, 4] }]);
|
||||
let f = open(&d).unwrap();
|
||||
assert!(f.audio.is_empty());
|
||||
let frame = f.read_frame(&d, 0).unwrap();
|
||||
assert_eq!(f.split_frame(&frame).unwrap(), FramePackets { audio: vec![], video: &[1, 2, 3, 4] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_file_opens_with_its_whole_frames() {
|
||||
let d = sample();
|
||||
let f = open(&d[..d.len() - 1]).unwrap();
|
||||
assert_eq!(f.frames.len(), 2);
|
||||
assert_eq!(f.header.frames, 3);
|
||||
// cut inside the index: no frame is known to be whole
|
||||
let index_at = HEADER_LEN + 24;
|
||||
assert_eq!(open(&d[..index_at + 6]).unwrap().frames.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_what_is_not_a_bink_1_file() {
|
||||
assert!(matches!(open(&b"RIFF"[..]), Err(Error::NotBink)));
|
||||
assert!(matches!(open(&[][..]), Err(Error::NotBink)));
|
||||
assert!(matches!(open(&[0u8; 64][..]), Err(Error::NotBink)));
|
||||
assert!(matches!(open(&b"BIKi"[..]), Err(Error::Invalid(_))));
|
||||
let mut d = sample();
|
||||
d[..4].copy_from_slice(b"KB2g");
|
||||
assert!(matches!(open(&d), Err(Error::Bink2)));
|
||||
assert!(!sniff(b"KB2g"));
|
||||
assert!(!sniff(b"BIK"));
|
||||
assert!(!sniff(b"BIK1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_invalid_headers() {
|
||||
let set = |at: usize, v: u32| {
|
||||
let mut d = sample();
|
||||
d[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||||
open(&d).map(|_| ())
|
||||
};
|
||||
assert!(matches!(set(8, 0), Err(Error::Invalid(_))), "no frames");
|
||||
assert!(matches!(set(20, 0), Err(Error::Invalid(_))), "zero width");
|
||||
assert!(matches!(set(24, 32768), Err(Error::Invalid(_))), "height past the limit");
|
||||
assert!(matches!(set(28, 0), Err(Error::Invalid(_))), "zero frame rate");
|
||||
assert!(matches!(set(32, 0), Err(Error::Invalid(_))), "zero frame rate divider");
|
||||
assert!(matches!(set(40, 257), Err(Error::Invalid(_))), "too many audio tracks");
|
||||
assert!(matches!(set(40, 200), Err(Error::Invalid(_))), "audio headers past the end");
|
||||
// a frame that starts inside the index, and one that ends before it starts
|
||||
let index_at = HEADER_LEN + 24;
|
||||
assert!(matches!(set(index_at, 8), Err(Error::Invalid(_))));
|
||||
assert!(matches!(set(index_at + 4, 0), Err(Error::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_count_past_what_the_file_holds_is_refused() {
|
||||
let mut d = sample();
|
||||
d[8..12].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
// the index now claims to run far past the file, so every offset lies inside it
|
||||
assert!(matches!(open(&d), Err(Error::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_frame_refuses_cut_off_packets() {
|
||||
assert!(matches!(split_frame(&[1, 0, 0], 1), Err(Error::Invalid(_))));
|
||||
assert!(matches!(split_frame(&[9, 0, 0, 0, 1, 2], 1), Err(Error::Invalid(_))));
|
||||
// a length too short to hold the decoded size
|
||||
assert!(matches!(split_frame(&[2, 0, 0, 0, 1, 2], 1), Err(Error::Invalid(_))));
|
||||
assert!(matches!(split_frame(&[], usize::MAX), Err(Error::Invalid(_))));
|
||||
assert_eq!(split_frame(&[], 0).unwrap().video, [0u8; 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_never_panics() {
|
||||
let seeds = [sample(), bink(b"BIKf", &[], &[TestFrame { key: true, audio: vec![], video: vec![1, 2, 3, 4] }])];
|
||||
for (i, s) in seeds.iter().enumerate() {
|
||||
craft_media_testkit::hostile::hammer(&format!("bink seed {i}"), s, 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] {
|
||||
if let Ok(frame) = f.read_frame(d, k) {
|
||||
let _ = f.split_frame(&frame);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A source that reports a shorter length than it serves, like a file growing while it is opened.
|
||||
struct Understating<'a> {
|
||||
data: &'a [u8],
|
||||
reported: u64,
|
||||
}
|
||||
|
||||
impl ByteSource for Understating<'_> {
|
||||
fn len(&self) -> u64 {
|
||||
self.reported
|
||||
}
|
||||
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
|
||||
self.data.read_at(offset, buf)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_that_understates_its_length_is_an_error_not_a_panic() {
|
||||
let mut d = sample();
|
||||
d[8..12].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
// the header and both track headers can be read, but the reported length ends before them
|
||||
for reported in [44, 50, 67] {
|
||||
let src = Understating { data: &d, reported };
|
||||
assert!(matches!(open(&src), Err(Error::Invalid(_))), "reported length {reported}");
|
||||
}
|
||||
// at the end of the track headers there is room for no index entry: no frames, no error
|
||||
let src = Understating { data: &d, reported: 68 };
|
||||
assert_eq!(open(&src).unwrap().frames.len(), 0);
|
||||
}
|
||||
|
||||
/// A source of zeros of any length that counts the bytes read from it, with `head` at its start.
|
||||
struct Zeros {
|
||||
head: Vec<u8>,
|
||||
len: u64,
|
||||
read: std::cell::Cell<u64>,
|
||||
}
|
||||
|
||||
impl ByteSource for Zeros {
|
||||
fn len(&self) -> u64 {
|
||||
self.len
|
||||
}
|
||||
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> {
|
||||
if offset.checked_add(buf.len() as u64).is_none_or(|end| end > self.len) {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "past the end"));
|
||||
}
|
||||
self.read.set(self.read.get() + buf.len() as u64);
|
||||
for (k, b) in buf.iter_mut().enumerate() {
|
||||
*b = usize::try_from(offset).ok().and_then(|o| self.head.get(o + k)).copied().unwrap_or(0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_frame_count_is_refused_after_one_piece_of_the_index() {
|
||||
// 2^28 frames declared in a 4 GiB source of zeros: the first entries are invalid, and the
|
||||
// gigabyte of index the count claims is never read
|
||||
let mut head = sample()[..HEADER_LEN].to_vec();
|
||||
head[8..12].copy_from_slice(&(1u32 << 28).to_le_bytes());
|
||||
head[40..44].copy_from_slice(&0u32.to_le_bytes());
|
||||
let src = Zeros { head, len: 4 << 30, read: std::cell::Cell::new(0) };
|
||||
assert!(matches!(open(&src), Err(Error::Invalid(_))));
|
||||
assert!(src.read.get() <= HEADER_LEN as u64 + INDEX_PIECE_ENTRIES * 4, "read {} bytes", src.read.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_longer_than_one_piece_reads_like_a_short_one() {
|
||||
// enough frames of four bytes each to span three pieces of the index
|
||||
let n = INDEX_PIECE_ENTRIES as usize * 2 + 100;
|
||||
let frames: Vec<TestFrame> = (0..n).map(|i| TestFrame { key: i % 1000 == 0, audio: vec![], video: (i as u32).to_le_bytes().to_vec() }).collect();
|
||||
let d = bink(b"BIKi", &[], &frames);
|
||||
let f = open(&d).unwrap();
|
||||
assert_eq!(f.frames.len(), n);
|
||||
for i in [0, 1, INDEX_PIECE_ENTRIES as usize - 1, INDEX_PIECE_ENTRIES as usize, INDEX_PIECE_ENTRIES as usize + 1, n - 1] {
|
||||
assert_eq!(f.read_frame(&d, i).unwrap(), (i as u32).to_le_bytes(), "frame {i}");
|
||||
assert_eq!(f.frames[i].key, i % 1000 == 0, "frame {i}");
|
||||
}
|
||||
// cut inside the third piece: the frames before the cut are kept
|
||||
let cut = f.frames[n - 50].offset as usize;
|
||||
assert_eq!(open(&d[..cut]).unwrap().frames.len(), n - 50);
|
||||
|
||||
// an invalid entry at the start of the second piece is named by its frame
|
||||
let piece = INDEX_PIECE_ENTRIES as usize;
|
||||
let entry_at = |k: usize| HEADER_LEN + 4 * k;
|
||||
let mut bad = d.clone();
|
||||
bad[entry_at(piece)..entry_at(piece) + 4].copy_from_slice(&0u32.to_le_bytes());
|
||||
match open(&bad) {
|
||||
Err(Error::Invalid(message)) => assert!(message.starts_with(&format!("frame {} at ", piece - 1)), "{message}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// an entry past the end of the file ends the table there, whatever follows it
|
||||
let mut cut_off = d.clone();
|
||||
cut_off[entry_at(10)..entry_at(10) + 4].copy_from_slice(&0xffff_fff0u32.to_le_bytes());
|
||||
assert_eq!(open(&cut_off).unwrap().frames.len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_bink_2_file_is_named_as_such() {
|
||||
assert!(matches!(open(&b"KB2g\0\0\0\0"[..]), Err(Error::Bink2)));
|
||||
assert!(matches!(open(&b"KB2"[..]), Err(Error::NotBink)));
|
||||
}
|
||||
@@ -46,6 +46,8 @@ pub enum Container {
|
||||
MpegPs,
|
||||
/// Sierra VMD (Video and Music Data).
|
||||
Vmd,
|
||||
/// Bink (BIK).
|
||||
Bink,
|
||||
}
|
||||
|
||||
impl Container {
|
||||
@@ -69,6 +71,7 @@ impl Container {
|
||||
Container::MpegTs => "MPEG-TS",
|
||||
Container::MpegPs => "MPEG-PS",
|
||||
Container::Vmd => "VMD",
|
||||
Container::Bink => "Bink",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,6 +114,10 @@ pub enum CodecId {
|
||||
Vorbis,
|
||||
/// Speex.
|
||||
Speex,
|
||||
/// Bink Audio, RDFT form.
|
||||
BinkAudioRdft,
|
||||
/// Bink Audio, DCT form.
|
||||
BinkAudioDct,
|
||||
/// H.264 / AVC.
|
||||
H264,
|
||||
/// H.265 / HEVC.
|
||||
@@ -141,6 +148,8 @@ pub enum CodecId {
|
||||
VmdVideo,
|
||||
/// Sierra VMD audio (8-bit PCM or 16-bit DPCM).
|
||||
VmdAudio,
|
||||
/// Bink Video (Bink 1).
|
||||
BinkVideo,
|
||||
/// A codec this crate has no identifier for.
|
||||
Unknown,
|
||||
}
|
||||
@@ -165,6 +174,8 @@ impl CodecId {
|
||||
CodecId::Opus => "Opus",
|
||||
CodecId::Vorbis => "Vorbis",
|
||||
CodecId::Speex => "Speex",
|
||||
CodecId::BinkAudioRdft => "Bink Audio (RDFT)",
|
||||
CodecId::BinkAudioDct => "Bink Audio (DCT)",
|
||||
CodecId::H264 => "H.264",
|
||||
CodecId::Hevc => "HEVC",
|
||||
CodecId::Av1 => "AV1",
|
||||
@@ -180,6 +191,7 @@ impl CodecId {
|
||||
CodecId::Apv => "APV",
|
||||
CodecId::VmdVideo => "VMD video",
|
||||
CodecId::VmdAudio => "VMD audio",
|
||||
CodecId::BinkVideo => "Bink Video",
|
||||
CodecId::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
@@ -205,6 +217,8 @@ impl CodecId {
|
||||
| CodecId::Vorbis
|
||||
| CodecId::Speex
|
||||
| CodecId::VmdAudio
|
||||
| CodecId::BinkAudioRdft
|
||||
| CodecId::BinkAudioDct
|
||||
)
|
||||
}
|
||||
|
||||
@@ -226,6 +240,7 @@ impl CodecId {
|
||||
| CodecId::Dnxhd
|
||||
| CodecId::Apv
|
||||
| CodecId::VmdVideo
|
||||
| CodecId::BinkVideo
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! - `matroska` (feature `matroska`): a clean-room Matroska (MKV) and WebM demuxer and muxer.
|
||||
//! - `ogg` (feature `ogg`): a clean-room Ogg demuxer with Ogg Opus and Ogg Vorbis stream mapping.
|
||||
//! - `avi` (feature `avi`): a clean-room AVI (RIFF) and OpenDML demuxer.
|
||||
//! - `bink` (feature `bink`): a clean-room Bink 1 (BIK) demuxer.
|
||||
//! - `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) and transport stream writer.
|
||||
@@ -20,11 +21,13 @@
|
||||
//! - `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`, `mpegts` and `vmd` are opt-in. A crate that needs
|
||||
//! `bitstream` and `isobmff` are on by default; `matroska`, `ogg`, `avi`, `bink`, `mxf`, `mpegts` and `vmd` are opt-in. A crate that needs
|
||||
//! only bit I/O uses `default-features = false, features = ["bitstream"]`.
|
||||
|
||||
#[cfg(feature = "avi")]
|
||||
pub mod avi;
|
||||
#[cfg(feature = "bink")]
|
||||
pub mod bink;
|
||||
#[cfg(feature = "bitstream")]
|
||||
pub mod bitstream;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -16,6 +16,8 @@ mod mpegts_mux_readback;
|
||||
mod oracle_avi;
|
||||
#[cfg(feature = "avi")]
|
||||
mod oracle_avi_mux;
|
||||
#[cfg(feature = "bink")]
|
||||
mod oracle_bink;
|
||||
#[cfg(feature = "isobmff")]
|
||||
mod oracle_demux;
|
||||
#[cfg(feature = "matroska")]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Real Bink files against ffprobe: every frame is read, and the stream, size and key flag of
|
||||
//! each packet match the packets ffprobe reads. Packet contents are not compared.
|
||||
//!
|
||||
//! No tool here can write a Bink file, and existing files are not ours to commit, so the test
|
||||
//! reads `*.bik` files from the directory named by `CRAFT_BINK_SAMPLES` (searched
|
||||
//! recursively) and is skipped when that is not set.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use craft_media::bink::open;
|
||||
|
||||
fn samples(dir: &Path, out: &mut Vec<PathBuf>, depth: usize) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() && depth < 8 {
|
||||
samples(&p, out, depth + 1);
|
||||
} else if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("bik")) {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `(stream index, size, key)` of every packet ffprobe reads, in file order.
|
||||
fn ffprobe_packets(ffprobe: &Path, path: &Path) -> Vec<(usize, usize, bool)> {
|
||||
let out =
|
||||
Command::new(ffprobe).args(["-v", "error", "-show_entries", "packet=stream_index,size,flags", "-of", "csv=p=0"]).arg(path).output().unwrap();
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.lines()
|
||||
.filter_map(|l| {
|
||||
let mut f = l.trim().split(',');
|
||||
Some((f.next()?.parse().ok()?, f.next()?.parse().ok()?, f.next()?.starts_with('K')))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_files_match_ffprobe() {
|
||||
let Some(dir) = std::env::var_os("CRAFT_BINK_SAMPLES").filter(|d| !d.is_empty()) else {
|
||||
return craft_media_testkit::skip_test("bink oracle", "CRAFT_BINK_SAMPLES is not set");
|
||||
};
|
||||
let Some(ffprobe) = craft_media_testkit::ffprobe() else { return };
|
||||
let mut files = Vec::new();
|
||||
samples(Path::new(&dir), &mut files, 0);
|
||||
files.sort();
|
||||
assert!(!files.is_empty(), "no .bik files under {}", Path::new(&dir).display());
|
||||
for path in files {
|
||||
let file = std::fs::File::open(&path).unwrap();
|
||||
let bink = open(&file).unwrap();
|
||||
assert_eq!(bink.frames.len(), bink.header.frames as usize, "{}", path.display());
|
||||
|
||||
// ffprobe numbers the video stream 0 and audio track `t` 1 + t, and its audio packets
|
||||
// start at the decoded size
|
||||
let mut ours = Vec::new();
|
||||
for (i, f) in bink.frames.iter().enumerate() {
|
||||
let frame = bink.read_frame(&file, i).unwrap();
|
||||
let packets = bink.split_frame(&frame).unwrap();
|
||||
for (t, a) in packets.audio.iter().enumerate() {
|
||||
if let Some(a) = a {
|
||||
ours.push((1 + t, a.data.len() + 4, true));
|
||||
}
|
||||
}
|
||||
ours.push((0, packets.video.len(), f.key));
|
||||
}
|
||||
let theirs = ffprobe_packets(&ffprobe, &path);
|
||||
assert_eq!(ours.len(), theirs.len(), "{}: packet count", path.display());
|
||||
if let Some(at) = ours.iter().zip(&theirs).position(|(a, b)| a != b) {
|
||||
panic!("{}: packet {at} is {:?}, ffprobe has {:?}", path.display(), ours[at], theirs[at]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ use bytes::Bytes;
|
||||
use canvas::Raw;
|
||||
pub use eof::ends_early;
|
||||
use geom::{Op, P};
|
||||
pub use pict::{is_pict, parse as parse_pict};
|
||||
pub use pict::{TruncationReason, is_pict, parse as parse_pict};
|
||||
pub use place::{MAX_BITMAP_SIDE, PlacedClip, PlacedItem, bez_path, crop_window};
|
||||
pub use size::size;
|
||||
pub use text::{Font, HAlign, SYMBOL_CHARSET, Text, VAlign};
|
||||
@@ -86,6 +86,8 @@ pub struct Picture {
|
||||
/// the picture holds what came before. The limits that cut one path, string, region or dash
|
||||
/// pattern short do not set it.
|
||||
pub truncated: bool,
|
||||
/// Granular reason why decoding halted early, distinguishing premature EOF from safety budget exhaustion.
|
||||
pub truncation_reason: Option<TruncationReason>,
|
||||
/// Images the file asks to draw that the reader did not read: bitmaps past a size, item, byte or
|
||||
/// decode limit or in a form the reader cannot decode, EMF+ metafile images that do not parse or
|
||||
/// are nested deeper than 3 levels, and pattern or texture brushes whose bitmap was not read, a
|
||||
|
||||
Loaded 100 of 219 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user