Merge pull request #1631 from storytold/codex/tga-dpx-rgba-writers

tga dpx: share uncompressed RGBA8 export
This commit is contained in:
FredApps authored and GitHub committed 2026-11-16 02:12:20 +01:00
commit d4009b4c95
4 files changed
+182

No files matched your search

+3
View File
@@ -34,6 +34,9 @@
//! Input is treated as hostile: every header read is bounds-checked, the picture size is capped
//! by [`Limits`] and the image data must be present in full before anything is allocated.
/// RGBA8-to-10-bit DPX encoding.
pub mod rgba8_dpx10;
#[cfg(test)]
mod tests;
+110
View File
@@ -0,0 +1,110 @@
//! Uncompressed RGB(A) output from top-down RGBA8 pixels.
/// Why the supplied frame cannot be encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rgba8EncodeError {
/// Empty, overflowing, or mismatched dimensions.
FrameSize,
/// A dimension cannot fit the output format.
TooLarge,
/// The output buffer could not be allocated.
OutOfMemory,
}
fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result<usize, Rgba8EncodeError> {
let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Rgba8EncodeError::FrameSize)?;
if w == 0 || h == 0 || rgba.len() != n {
return Err(Rgba8EncodeError::FrameSize);
}
Ok(n)
}
/// Header size of the DPX files we write (file + image + orientation + film + TV headers).
const DPX_HEADER: usize = 2048;
/// A DPX file: 10-bit RGB (8-bit values widened by bit replication, so 0 → 0 and 255 → 1023).
pub fn encode_rgba8_dpx10(rgba: &[u8], w: u32, h: u32, creator: &str) -> std::result::Result<Vec<u8>, Rgba8EncodeError> {
let n = checked_len(rgba, w, h)?;
// one 32-bit word per pixel; `n` is already `w * h * 4`
let size = n.checked_add(DPX_HEADER).ok_or(Rgba8EncodeError::FrameSize)?;
let file_size = u32::try_from(size).map_err(|_| Rgba8EncodeError::TooLarge)?;
// SMPTE ST 268: undefined numeric fields are all ones, undefined text fields are NUL
let mut hd = vec![0xFF_u8; DPX_HEADER];
for (a, b) in [
(36, 660), // file name, creation time, creator, project, copyright
(664, 768), // reserved
(1356, 1408), // reserved
(1432, 1620), // source file name, time, input device, serial number
(1644, 1664), // reserved
(1664, 1712), // film manufacturer, type, offset, prefix, count, format
(1732, 1920), // frame id, slate, reserved
(1972, 2048), // reserved
] {
hd[a..b].fill(0);
}
for e in 0..8 {
let d = 780 + e * 72 + 40;
hd[d..d + 32].fill(0); // element descriptions
}
let put32 = |hd: &mut Vec<u8>, at: usize, v: u32| hd[at..at + 4].copy_from_slice(&v.to_be_bytes());
let put16 = |hd: &mut Vec<u8>, at: usize, v: u16| hd[at..at + 2].copy_from_slice(&v.to_be_bytes());
// file information header
hd[0..4].copy_from_slice(b"SDPX");
put32(&mut hd, 4, DPX_HEADER as u32); // offset to the image data
hd[8..16].copy_from_slice(b"V2.0\0\0\0\0");
put32(&mut hd, 16, file_size);
put32(&mut hd, 20, 1); // ditto key: new frame
put32(&mut hd, 24, 1664); // generic header length
put32(&mut hd, 28, 384); // industry header length
put32(&mut hd, 32, 0); // user data length
let creator = creator.as_bytes();
let n = creator.len().min(100);
hd[160..160 + n].copy_from_slice(&creator[..n]);
// image information header
put16(&mut hd, 768, 0); // orientation: left to right, top to bottom
put16(&mut hd, 770, 1); // one image element
put32(&mut hd, 772, w);
put32(&mut hd, 776, h);
let el = 780;
put32(&mut hd, el, 0); // unsigned
put32(&mut hd, el + 4, 0); // reference low data code
put32(&mut hd, el + 12, 1023); // reference high data code
hd[el + 20] = 50; // descriptor: RGB
hd[el + 21] = 6; // transfer: ITU-R BT.709
hd[el + 22] = 6; // colorimetric: ITU-R BT.709
hd[el + 23] = 10; // bit depth
put16(&mut hd, el + 24, 1); // packing: filled to 32-bit words, method A
put16(&mut hd, el + 26, 0); // no encoding (uncompressed)
put32(&mut hd, el + 28, DPX_HEADER as u32); // offset to the element's data
put32(&mut hd, el + 32, 0); // end-of-line padding
put32(&mut hd, el + 36, 0); // end-of-image padding
// image orientation header: no offset, square pixels
put32(&mut hd, 1408, 0);
put32(&mut hd, 1412, 0);
put32(&mut hd, 1424, w);
put32(&mut hd, 1428, h);
put32(&mut hd, 1628, 1);
put32(&mut hd, 1632, 1);
// television header: progressive
hd[1928] = 0;
// The caller already holds the frame; reserve the output fallibly so a large export reports
// an error instead of aborting the process.
let mut out = Vec::new();
out.try_reserve_exact(size).map_err(|_| Rgba8EncodeError::OutOfMemory)?;
out.extend_from_slice(&hd);
let ten = |v: u8| (u32::from(v) << 2) | (u32::from(v) >> 6);
for &[r, g, b, _] in rgba.as_chunks::<4>().0 {
out.extend_from_slice(&((ten(r) << 22) | (ten(g) << 12) | (ten(b) << 2)).to_be_bytes());
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn packed_rgb_and_creator() {
let bytes = encode_rgba8_dpx10(&[255, 0, 128, 255], 1, 1, "FilmCraft").unwrap();
assert_eq!(&bytes[..4], b"SDPX");
assert_eq!(&bytes[160..169], b"FilmCraft");
assert_eq!(&bytes[2048..], &((1023u32 << 22) | (514u32 << 2)).to_be_bytes());
assert_eq!(encode_rgba8_dpx10(&[], 0, 1, ""), Err(Rgba8EncodeError::FrameSize));
}
}
+3
View File
@@ -18,6 +18,9 @@
//! Input is treated as hostile: the picture size is capped by [`Limits`], and a run-length file
//! must be long enough to hold the pixels its header declares before anything is allocated.
/// Uncompressed RGBA8-to-Targa encoding.
pub mod rgba8_raw;
#[cfg(test)]
mod tests;
+66
View File
@@ -0,0 +1,66 @@
//! Uncompressed RGB(A) output from top-down RGBA8 pixels.
/// Why the supplied frame cannot be encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rgba8EncodeError {
/// Empty, overflowing, or mismatched dimensions.
FrameSize,
/// A dimension cannot fit the 16-bit Targa header.
Dimensions,
/// The output buffer could not be allocated.
OutOfMemory,
}
fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result<usize, Rgba8EncodeError> {
let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Rgba8EncodeError::FrameSize)?;
if w == 0 || h == 0 || rgba.len() != n {
return Err(Rgba8EncodeError::FrameSize);
}
Ok(n)
}
/// An uncompressed Targa file: 24-bit BGR, or 32-bit BGRA with `alpha` (straight alpha, as the
/// frame carries it).
pub fn encode_rgba8_raw(rgba: &[u8], w: u32, h: u32, alpha: bool) -> std::result::Result<Vec<u8>, Rgba8EncodeError> {
checked_len(rgba, w, h)?;
let (tw, th) = match (u16::try_from(w), u16::try_from(h)) {
(Ok(tw), Ok(th)) => (tw, th),
_ => return Err(Rgba8EncodeError::Dimensions),
};
let bpp: usize = if alpha { 4 } else { 3 };
let row = w as usize * 4;
// The caller already holds the frame; reserve the second, output-sized buffer fallibly so a
// large export reports an error instead of aborting the process.
let len = (w as usize * h as usize).checked_mul(bpp).and_then(|n| n.checked_add(18 + 26)).ok_or(Rgba8EncodeError::FrameSize)?;
let mut out = Vec::new();
out.try_reserve_exact(len).map_err(|_| Rgba8EncodeError::OutOfMemory)?;
out.extend_from_slice(&[0, 0, 2]); // no ID, no colour map, uncompressed true-colour
out.extend_from_slice(&[0; 5]); // colour map specification (unused)
out.extend_from_slice(&[0, 0, 0, 0]); // x / y origin
out.extend_from_slice(&tw.to_le_bytes());
out.extend_from_slice(&th.to_le_bytes());
out.push(if alpha { 32 } else { 24 });
out.push(if alpha { 8 } else { 0 }); // attribute bits; bottom-left origin
// bottom-left origin: the last frame row comes first
for line in rgba.chunks_exact(row).rev() {
for &[r, g, b, a] in line.as_chunks::<4>().0 {
out.extend_from_slice(&[b, g, r]);
if alpha {
out.push(a);
}
}
}
// TGA 2.0 footer without extension or developer areas
out.extend_from_slice(&[0; 8]);
out.extend_from_slice(b"TRUEVISION-XFILE.\0");
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn raw_round_trip() {
let bytes = encode_rgba8_raw(&[1, 2, 3, 4], 1, 1, true).unwrap();
assert_eq!(&bytes[18..22], &[3, 2, 1, 4]);
assert_eq!(&bytes[bytes.len() - 18..], b"TRUEVISION-XFILE.\0");
assert_eq!(encode_rgba8_raw(&[], 0, 1, false), Err(Rgba8EncodeError::FrameSize));
}
}