LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
LR-IMP-FORMATS: ARW6 tile table, tile and stream headers; synthetic ARW6 encoder for tests
dev-null-undefinedf101a0914226
diff --git a/crates/raw/src/vendor/arw6.rs b/crates/raw/src/vendor/arw6.rsnew file mode 100644index 000000000..e7615c218--- /dev/null+++ b/crates/raw/src/vendor/arw6.rs@@ -0,0 +1,331 @@+//! Sony ARW6 ("Compressed RAW 2" / HQ, TIFF Compression 32766): container parsing.+//!+//! Clean-room. The layout comes from SMPTE RDD 34 (Picture_info in word 0) and from Phase 0 black-box+//! inspection of real ILCE-7RM6 files (tile table, group size words, stream headers and index entries), each rule+//! checked by re-serialising parsed tiles byte-for-byte; see `docs/superpowers/specs/2026-10-09-sony-arw6-decoder-design.md`+//! (*Container (Sony)*). No other raw decoder's source was consulted.++// Consumed by the geometry and `decode` tasks that follow.+#![allow(dead_code)]++use crate::{RawError, Result};++fn corrupt(why: &str) -> RawError {+ RawError::Corrupt(format!("ARW6: {why}"))+}++fn unsupported(why: &str) -> RawError {+ RawError::Unsupported(format!("ARW6 {why}"))+}++fn u16_be(b: &[u8], at: usize) -> Option<usize> {+ let s = b.get(at..at.checked_add(2)?)?;+ Some(usize::from(u16::from_be_bytes([*s.first()?, *s.get(1)?])))+}++fn u24_be(b: &[u8], at: usize) -> Option<usize> {+ let s = b.get(at..at.checked_add(3)?)?;+ Some(s.iter().fold(0usize, |a, &v| (a << 8) | usize::from(v)))+}++fn u32_le(b: &[u8], at: usize) -> Option<usize> {+ let s = b.get(at..at.checked_add(4)?)?;+ Some(u32::from_le_bytes(s.try_into().ok()?) as usize)+}++/// One tile of the strip: its bytes run from `offset` to the next tile's offset (the last: the strip end).+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct TileEntry {+ pub offset: usize,+ pub x: usize,+ pub y: usize,+ pub width: usize,+ pub height: usize,+}++/// Most tiles a strip may hold (real files have 1 or 4).+const MAX_TILES: usize = 16;++/// Parse the tile table at the start of the strip (file structure, spec *Container*): `u32` count, `u32` 0, then+/// 24-byte entries `u64` offset (relative to the strip), `u32` x, y, width, height, all little-endian.+pub(crate) fn parse_tile_table(strip: &[u8], width: usize, height: usize) -> Result<Vec<TileEntry>> {+ let count = u32_le(strip, 0).ok_or_else(|| corrupt("truncated tile table"))?;+ if count == 0 || count > MAX_TILES {+ return Err(unsupported("tile count outside 1..=16"));+ }+ let mut tiles: Vec<TileEntry> = Vec::with_capacity(count);+ let mut area = 0usize;+ for i in 0..count {+ let at = 8 + 24 * i;+ let e = strip.get(at..at + 24).ok_or_else(|| corrupt("truncated tile table"))?;+ let offset = e.get(..8).and_then(|b| <[u8; 8]>::try_from(b).ok()).map(u64::from_le_bytes).and_then(|o| usize::try_from(o).ok());+ let offset = offset.filter(|&o| o < strip.len()).ok_or_else(|| corrupt("tile offset outside the strip"))?;+ if tiles.last().is_some_and(|p| offset <= p.offset) {+ return Err(corrupt("tile offsets do not increase"));+ }+ let (x, y, w, h) = (u32_le(e, 8), u32_le(e, 12), u32_le(e, 16), u32_le(e, 20));+ let (Some(x), Some(y), Some(w), Some(h)) = (x, y, w, h) else { return Err(corrupt("truncated tile table")) };+ // Even geometry; the level-3 band width w / 16 must be whole (w/2 a multiple of 8).+ if w == 0 || h == 0 || x % 2 != 0 || y % 2 != 0 || w % 2 != 0 || h % 2 != 0 || (w / 2) % 8 != 0 {+ return Err(unsupported("tile geometry"));+ }+ let fits = x.checked_add(w).is_some_and(|r| r <= width) && y.checked_add(h).is_some_and(|b| b <= height);+ if !fits {+ return Err(corrupt("tile outside the image"));+ }+ let a = w.checked_mul(h).filter(|&a| a <= crate::MAX_SAMPLES).ok_or(RawError::Limit("ARW6 tile too large"))?;+ area = area.checked_add(a).ok_or(RawError::Limit("ARW6 tiles too large"))?;+ tiles.push(TileEntry { offset, x, y, width: w, height: h });+ }+ for (i, a) in tiles.iter().enumerate() {+ for b in tiles.iter().skip(i + 1) {+ if a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height {+ return Err(corrupt("tiles overlap"));+ }+ }+ }+ // In-image, disjoint tiles cover the image exactly when their areas sum to it.+ if width.checked_mul(height) != Some(area) {+ return Err(corrupt("tiles do not cover the image"));+ }+ Ok(tiles)+}++/// One of a tile's 13 streams (positions in 16-byte words from the tile start).+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct StreamRef {+ pub group: u8,+ pub comp: u8,+ pub word: usize,+ pub size_words: usize,+ pub index_words: usize,+ pub data_words: usize,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct TileHeader {+ pub hs: usize,+ pub vs: usize,+ pub ntu: usize,+ /// File order: g0 c0..2, g1 c0..2, g2 c0..2, g3 c0..2, g4 c0.+ pub streams: Vec<StreamRef>,+}++/// `n` bits at bit position `pos` (MSB-first) of a tile's word 0.+fn field(w: &[u8], pos: usize, n: usize) -> Option<u32> {+ let mut v = 0u32;+ for i in pos..pos.checked_add(n)? {+ let byte = *w.get(i / 8)?;+ v = (v << 1) | u32::from((byte >> (7 - i % 8)) & 1);+ }+ Some(v)+}++/// Streams per group: g0..g3 one per colour component, g4 the green residual.+const GROUP_STREAMS: [usize; 5] = [3, 3, 3, 3, 1];++/// Parse word 0 (RDD 34 `Picture_info`; every real file has HS = tile width, VS = tile height / 2, BBD 16, NC 3, NW 3,+/// NP 1000000000b), the group size words 3..=7 and each stream's header word (spec *Container*, Phase 0).+pub(crate) fn parse_tile_header(tile: &[u8], tw: usize, th: usize) -> Result<TileHeader> {+ let w0 = tile.get(..16).ok_or_else(|| corrupt("tile shorter than its picture header"))?;+ let f = |pos, n| field(w0, pos, n).map(|v| v as usize);+ let (hs, vs, bbd, nc, nw, np) = (f(64, 16), f(80, 16), f(102, 6), f(112, 3), f(115, 3), f(118, 10));+ let (Some(hs), Some(vs), Some(bbd), Some(nc), Some(nw), Some(np)) = (hs, vs, bbd, nc, nw, np) else {+ return Err(corrupt("picture header"));+ };+ if hs != tw || vs * 2 != th || bbd != 16 || nc != 3 || nw != 3 || np != 0b10_0000_0000 {+ return Err(unsupported(&format!("picture header variant (HS {hs}, VS {vs}, BBD {bbd}, NC {nc}, NW {nw}, NP {np:#b})")));+ }+ let mut streams = Vec::with_capacity(13);+ let mut word = 8usize;+ for (group, &n) in GROUP_STREAMS.iter().enumerate() {+ let table = tile.get((3 + group) * 16..(4 + group) * 16).ok_or_else(|| corrupt("truncated group table"))?;+ if usize::from(table.first().copied().unwrap_or(0)) != n {+ return Err(unsupported("group stream count"));+ }+ for comp in 0..n {+ let size_words = u24_be(table, 1 + 3 * comp).ok_or_else(|| corrupt("group table"))?;+ let end = word.checked_add(size_words).filter(|e| e.checked_mul(16).is_some_and(|b| b <= tile.len()));+ let end = end.ok_or_else(|| corrupt("stream outside the tile"))?;+ let hdr = tile.get(word * 16..word * 16 + 16).ok_or_else(|| corrupt("stream outside the tile"))?;+ let (index_words, data_words) =+ (u16_be(hdr, 0).ok_or_else(|| corrupt("stream header"))?, u24_be(hdr, 2).ok_or_else(|| corrupt("stream header"))?);+ if index_words.checked_add(data_words).and_then(|s| s.checked_add(1)).is_none_or(|s| s > size_words) {+ return Err(corrupt("stream header sizes exceed the stream"));+ }+ streams.push(StreamRef { group: group as u8, comp: comp as u8, word, size_words, index_words, data_words });+ word = end;+ }+ }+ Ok(TileHeader { hs, vs, ntu: vs.div_ceil(16), streams })+}++/// One half-TU of a stream: `len` bytes at byte `start` of the tile, quantiser index per band+/// (g0/g4: the single nibble repeated).+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct Half {+ pub start: usize,+ pub len: usize,+ pub qi: [u32; 3],+}++fn nibbles(b: &[u8], from: usize, n: usize) -> Option<u32> {+ (from..from + n).try_fold(0u32, |a, i| Some((a << 4) | u32::from((*b.get(i / 2)? >> (4 * (1 - i % 2))) & 15)))+}++/// The `2 * ntu` halves of a stream. Index entry per TU (file structure): `A:16 X B:16 X` with A / B the byte+/// lengths of half 0 / 1 and X the QI nibble (g0, g4: 1 nibble) or three nibbles HL, LH, HH (g1..g3); the data area+/// holds each TU's A bytes then B bytes, consecutive TUs contiguous.+pub(crate) fn stream_halves(tile: &[u8], s: &StreamRef, ntu: usize) -> Result<Vec<Half>> {+ let nx = if s.group == 0 || s.group == 4 { 1 } else { 3 };+ let esz = 4 + nx; // bytes: (16 + 4nx + 16 + 4nx) / 8+ let idx_start = s.word.checked_add(1).and_then(|w| w.checked_mul(16)).ok_or_else(|| corrupt("stream position"))?;+ let idx_len = s.index_words.checked_mul(16).ok_or_else(|| corrupt("stream position"))?;+ if ntu.checked_mul(esz).is_none_or(|n| n > idx_len) {+ return Err(corrupt("index table too small for the tile's TUs"));+ }+ let data_start = idx_start.checked_add(idx_len).ok_or_else(|| corrupt("stream position"))?;+ let index = tile.get(idx_start..data_start).ok_or_else(|| corrupt("index table outside the tile"))?;+ let data_end = s.data_words.checked_mul(16).and_then(|d| d.checked_add(data_start)).ok_or_else(|| corrupt("stream position"))?;+ if data_end > tile.len() {+ return Err(corrupt("stream data outside the tile"));+ }+ let mut halves = Vec::with_capacity(2 * ntu);+ let mut pos = data_start;+ for k in 0..ntu {+ let e = index.get(k * esz..(k + 1) * esz).ok_or_else(|| corrupt("index table"))?;+ let bad = || corrupt("index entry");+ let (a, x1) = (nibbles(e, 0, 4).ok_or_else(bad)? as usize, nibbles(e, 4, nx).ok_or_else(bad)?);+ let (b, x2) = (nibbles(e, 4 + nx, 4).ok_or_else(bad)? as usize, nibbles(e, 8 + nx, nx).ok_or_else(bad)?);+ for (len, x) in [(a, x1), (b, x2)] {+ let end = pos.checked_add(len).filter(|&e| e <= data_end).ok_or_else(|| corrupt("half outside its stream's data"))?;+ let qi = if nx == 1 { [x; 3] } else { [(x >> 8) & 15, (x >> 4) & 15, x & 15] };+ halves.push(Half { start: pos, len, qi });+ pos = end;+ }+ }+ Ok(halves)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::llvc::Plane;+ use crate::vendor::arw6_testenc::*;+ use crate::vendor::pef::Bits;+ use lightcraft_tiff::Tiff;+ use lightcraft_tiff::image::chunk_bytes;+ use lightcraft_tiff::tags as t;++ fn planes(w2: usize, h2: usize, seed: u64) -> (Plane, Plane, Plane, Plane) {+ let mut x = seed.max(1);+ let mut next = |span: i32| -> i32 {+ x ^= x << 13;+ x ^= x >> 7;+ x ^= x << 17;+ (x % (2 * span as u64 + 1)) as i32 - span+ };+ let mut mk = |centre: i32, span: i32| Plane { width: w2, height: h2, data: (0..w2 * h2).map(|_| centre + next(span)).collect() };+ (mk(2048, 200), mk(0, 60), mk(0, 60), mk(0, 24))+ }++ fn one_tile(w: usize, h: usize, s: u8, qi: Qis) -> (Vec<u8>, TileSpec) {+ let (m, c1, c2, res) = planes(w / 2, h / 2, 7);+ let t = TileSpec { s, qi, m, c1, c2, res };+ (encode_tile(&t), t)+ }++ /// The raw strip bytes of the compression-32766 IFD, as `arw.rs` locates them.+ fn strip_of(file: &[u8]) -> &[u8] {+ let tiff = Tiff::parse(file).unwrap();+ let raw = tiff.all_ifds().into_iter().find(|i| i.u16(t::COMPRESSION) == Some(32766)).unwrap();+ let info = raw.image().unwrap();+ let chunks = info.chunks(file.len() as u64);+ chunk_bytes(file, &chunks[0]).unwrap()+ }++ #[test]+ fn tile_table_round_trips() {+ let (tile, _) = one_tile(64, 48, 0, Qis::ZERO);+ let file = arw6_file(&[(0, 0, 64, 48, tile.clone())], 64, 48);+ let strip = strip_of(&file);+ let t = parse_tile_table(strip, 64, 48).unwrap();+ assert_eq!(t.len(), 1);+ assert_eq!((t[0].x, t[0].y, t[0].width, t[0].height, t[0].offset), (0, 0, 64, 48, 512));+ }++ #[test]+ fn tile_table_rejects_bad_layouts() {+ let (tile, _) = one_tile(64, 48, 0, Qis::ZERO);+ let strip = strip_of(&arw6_file(&[(0, 0, 64, 48, tile.clone())], 64, 48)).to_vec();+ let mut zero = strip.clone();+ zero[0] = 0;+ assert!(parse_tile_table(&zero, 64, 48).is_err());+ let mut far = strip.clone();+ far[8..16].copy_from_slice(&u64::MAX.to_le_bytes());+ assert!(parse_tile_table(&far, 64, 48).is_err());+ let mut odd = strip.clone();+ odd[20..24].copy_from_slice(&63u32.to_le_bytes()); // the first tile's y: odd, and no longer covering+ assert!(parse_tile_table(&odd, 64, 48).is_err());+ assert!(parse_tile_table(&strip, 64, 64).is_err()); // does not cover the image+ let two = arw6_file(&[(0, 0, 64, 48, tile.clone()), (0, 0, 64, 48, tile.clone())], 128, 48);+ assert!(parse_tile_table(strip_of(&two), 128, 48).is_err()); // overlapping+ assert!(parse_tile_table(&strip[..7], 64, 48).is_err()); // truncated table+ }++ #[test]+ fn tile_header_and_streams() {+ let (tile, _) = one_tile(64, 48, 3, Qis::REAL);+ let h = parse_tile_header(&tile, 64, 48).unwrap();+ assert_eq!((h.hs, h.vs, h.ntu, h.streams.len()), (64, 24, 2, 13));+ assert_eq!(+ h.streams.iter().map(|s| (s.group, s.comp)).collect::<Vec<_>>(),+ [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0)]+ );+ let g3 = stream_halves(&tile, &h.streams[9], h.ntu).unwrap();+ assert_eq!(g3.len(), 4);+ assert_eq!(g3[0].qi, [1, 1, 2]);+ let g4 = stream_halves(&tile, &h.streams[12], h.ntu).unwrap();+ assert_eq!(g4[1].qi, [2, 2, 2]);+ assert!(g4[3].start + g4[3].len <= tile.len());+ let mut bad = tile.clone();+ bad[13] = 0xff; // corrupts word 0's BBD bits: any picture-header deviation is Unsupported+ assert!(matches!(parse_tile_header(&bad, 64, 48), Err(RawError::Unsupported(_))));+ assert!(parse_tile_header(&tile, 64, 50).is_err()); // VS != th / 2+ }++ #[test]+ fn every_stream_of_an_encoded_tile_parses() {+ for s in [0u8, 3] {+ let (tile, spec) = one_tile(64, 48, s, Qis::REAL);+ assert_eq!(tile.len() % 4096, 0);+ let h = parse_tile_header(&tile, 64, 48).unwrap();+ for st in &h.streams {+ assert_eq!(stream_halves(&tile, st, h.ntu).unwrap().len(), 2 * h.ntu);+ }+ // the residual stream's halves decode to the clipped, quantised rows 8n-6+s ..= 8n+1+s+ let g4 = stream_halves(&tile, &h.streams[12], h.ntu).unwrap();+ for (n, half) in g4.iter().enumerate() {+ let bytes = &tile[half.start..half.start + half.len];+ let mut bits = Bits::new(bytes);+ for r in (8 * n as i32 - 6 + s as i32..8 * n as i32 + 2 + s as i32).filter(|&r| (0..24).contains(&r)) {+ let line = crate::llvc::vld_decode_line(&mut bits, bytes.len() * 8, 32).unwrap();+ let want: Vec<i32> = spec.res.row(r as usize).unwrap().iter().map(|&v| quantize(v, 2)).collect();+ assert_eq!(line, want, "s {s} half {n} row {r}");+ }+ }+ // a stream that claims more halves than its index holds is rejected+ assert!(stream_halves(&tile, &h.streams[0], 1000).is_err());+ }+ }++ #[test]+ fn encoder_decodes_its_own_lines() {+ let vals: Vec<i32> = (0..100).map(|i| (i * 37) % 23 - 11).collect();+ let mut w = BitWriter::default();+ vld_encode_line(&vals, 100, &mut w);+ let bytes = w.finish();+ let mut b = Bits::new(&bytes);+ assert_eq!(crate::llvc::vld_decode_line(&mut b, bytes.len() * 8, 100).unwrap(), vals);+ }+}diff --git a/crates/raw/src/vendor/arw6_testenc.rs b/crates/raw/src/vendor/arw6_testenc.rsindex 1bb6015ab..f0f781c75 100644--- a/crates/raw/src/vendor/arw6_testenc.rs+++ b/crates/raw/src/vendor/arw6_testenc.rs@@ -1,6 +1,8 @@//! Test-only ARW6 synthetic encoder pieces: forward 5/3 transforms (exact inverse of `llvc::inverse_*`) and `quantize`.use crate::llvc::{Bands3, Plane, band_rows};+use lightcraft_tiff::tags as t;+use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};/// Exact inverse of `dequant` on representable values: `sign(v) * (|v| >> qi)`.pub(crate) fn quantize(v: i32, qi: u32) -> i32 {@@ -77,3 +79,335 @@ pub(crate) fn forward3(x: &Plane, phases: [u8; 3]) -> Bands3 {let (ll3, lh3, hl3, hh3) = forward_53_2d(&ll2, phases[2]);Bands3 { ll3, hl3, lh3, hh3, hl2, lh2, hh2, hl1, lh1, hh1 }}++// ---- RDD 34 line encoder (mirror of `llvc::vld_decode_line`; `plan/arw6/scratch/tilewrite.py::vld_encode`) ----++/// MSB-first bit sink; one `0`/`1` per element until `finish`.+#[derive(Default)]+pub(crate) struct BitWriter {+ bits: Vec<u8>,+}++impl BitWriter {+ pub(crate) fn put(&mut self, bit: bool) {+ self.bits.push(u8::from(bit));+ }+ pub(crate) fn put_n(&mut self, v: u32, n: u32) {+ for i in (0..n).rev() {+ self.put((v >> i) & 1 == 1);+ }+ }+ fn zeros(&mut self, n: u32) {+ for _ in 0..n {+ self.put(false);+ }+ }+ /// Zero-padded to a whole byte.+ pub(crate) fn finish(self) -> Vec<u8> {+ self.bits.chunks(8).map(|c| c.iter().enumerate().fold(0u8, |a, (i, &b)| a | (b << (7 - i)))).collect()+ }+}++/// Encode one line (`width` coefficients, padded with zeros to whole sets of 4), with Sony's two deviations.+pub(crate) fn vld_encode_line(values: &[i32], width: usize, out: &mut BitWriter) {+ let sets_n = width.div_ceil(4);+ let mut vals = values[..width.min(values.len())].to_vec();+ vals.resize(4 * sets_n, 0);+ let sets: Vec<&[i32]> = vals.chunks(4).collect();+ let dpts: Vec<u32> = sets.iter().map(|s| 32 - s.iter().map(|v| v.unsigned_abs()).max().unwrap_or(0).leading_zeros()).collect();+ let (mut dpt, mut dpts_state, mut cnt, mut zr) = (0u32, 0u8, sets_n, 0usize);+ let mut prev: Option<&[i32]> = None;+ let mut k = 0usize;+ loop {+ let dpt_v = cnt != 0;+ cnt = cnt.saturating_sub(1);+ zr = zr.saturating_sub(1);+ if dpt_v {+ let d = dpts[k];+ match dpts_state {+ 0 if d == dpt => {+ out.put(false);+ if dpt == 0 {+ dpts_state = 1;+ }+ }+ 0 if d > dpt => {+ out.put(true);+ out.put(false);+ out.zeros(d - dpt - 1);+ out.put(true);+ dpt = d;+ }+ 0 => {+ out.put(true);+ out.put(true);+ if d >= 1 {+ out.zeros(dpt - d - 1);+ out.put(true);+ dpt = d;+ } else {+ out.zeros(dpt - 1);+ dpt = 0;+ dpts_state = 1;+ }+ }+ 1 if d > 0 => {+ out.put(true);+ out.zeros(d - 1);+ out.put(true);+ dpt = d;+ dpts_state = 0;+ }+ 1 => {+ let r = dpts[k..].iter().take_while(|&&x| x == 0).count();+ let lim = (cnt as u64 + 2).next_power_of_two().trailing_zeros();+ if k + r >= sets_n {+ out.zeros(lim); // the rest of the line is zero+ zr = cnt + 2;+ } else {+ let v = (r + 1) as u32;+ let m = 31 - v.leading_zeros();+ assert!(m < lim);+ out.zeros(m);+ out.put(true);+ out.put_n(v - (1 << m), m);+ zr = r + 1;+ }+ dpts_state = 2;+ }+ _ if zr == 1 => {+ out.zeros(d - 1);+ out.put(true);+ dpt = d;+ dpts_state = 0;+ }+ _ => assert_eq!(d, 0),+ }+ }+ if let Some(p) = prev {+ for &v in p {+ if v != 0 {+ out.put(v < 0);+ }+ }+ }+ if k >= sets_n {+ return;+ }+ if dpt_v {+ for &v in sets[k] {+ out.put_n(v.unsigned_abs(), dpt);+ }+ prev = Some(sets[k]);+ }+ k += 1;+ }+}++// ---- tile / file serialiser (`tilewrite.py::TileModel.serialize`, `arw6dump.py`) ----++/// Per-band quantiser indices: `l1`/`l2`/`l3` per component, bands in HL, LH, HH order.+#[derive(Clone)]+pub(crate) struct Qis {+ pub l1: [[u32; 3]; 3],+ pub l2: [[u32; 3]; 3],+ pub l3: [[u32; 3]; 3],+ pub res: u32,+}++impl Qis {+ pub(crate) const ZERO: Qis = Qis { l1: [[0; 3]; 3], l2: [[0; 3]; 3], l3: [[0; 3]; 3], res: 0 };+ /// The values seen in every real file (spec *Container*).+ pub(crate) const REAL: Qis = Qis { l1: [[1, 1, 2], [2, 2, 3], [2, 2, 3]], l2: [[0, 0, 1]; 3], l3: [[0; 3]; 3], res: 2 };+}++/// One tile to encode: `s` is the anchor offset (spec *Frame geometry*), planes are W/2 x H/2.+pub(crate) struct TileSpec {+ pub s: u8,+ pub qi: Qis,+ pub m: Plane,+ pub c1: Plane,+ pub c2: Plane,+ pub res: Plane,+}++/// Band row indices of the plane rows `rows` (low: `t % 2 == p`, row `(t-p)/2`; high: row `(t-(1-p))/2`).+fn split_rows(rows: &[usize], p: usize) -> (Vec<usize>, Vec<usize>) {+ let (mut lo, mut hi) = (Vec::new(), Vec::new());+ for &t in rows {+ if t % 2 == p {+ lo.push((t - p) / 2);+ } else {+ hi.push((t - (1 - p)) / 2);+ }+ }+ (lo, hi)+}++fn quantised_rows(plane: &Plane, rows: &[usize], qi: u32) -> Vec<Vec<i32>> {+ rows.iter().map(|&r| plane.row(r).unwrap().iter().map(|&v| quantize(v, qi)).collect()).collect()+}++fn encode_lines(lines: &[Vec<i32>]) -> Vec<u8> {+ let mut w = BitWriter::default();+ for l in lines {+ vld_encode_line(l, l.len(), &mut w);+ }+ w.finish()+}++fn pad16(v: &mut Vec<u8>) {+ v.resize(v.len().next_multiple_of(16), 0);+}++fn u24(v: usize) -> [u8; 3] {+ [(v >> 16) as u8, (v >> 8) as u8, v as u8]+}++/// One stream: header word, index table, data area. `halves[i]` = (bytes, qi nibbles of the TU).+fn build_stream(halves: &[(Vec<u8>, Vec<u32>)]) -> Vec<u8> {+ let (mut idx, mut data) = (Vec::new(), Vec::new());+ for pair in halves.chunks(2) {+ let mut nib: Vec<u32> = Vec::new();+ for (bytes, qi) in pair {+ nib.extend((0..4).rev().map(|i| (bytes.len() as u32 >> (4 * i)) & 15));+ nib.extend(qi);+ data.extend_from_slice(bytes);+ }+ idx.extend(nib.chunks(2).map(|c| (c[0] << 4 | c[1]) as u8));+ }+ pad16(&mut idx);+ pad16(&mut data);+ let mut out = (idx.len() as u16 / 16).to_be_bytes().to_vec();+ out.extend(u24(data.len() / 16));+ out.extend([0x40, 0x40, 0x01, 0x12, 0x10, 0, 0, 0, 0, 0, 0]);+ out.extend(idx);+ out.extend(data);+ out+}++/// Encode one tile: forward 3-level 5/3 per component with the phases of `s`, quantise, pack every half in natural+/// clipped order (spec *Frame geometry*), then add index tables, stream headers and the tile header.+pub(crate) fn encode_tile(t: &TileSpec) -> Vec<u8> {+ let (vs, s) = (t.m.height, i32::from(t.s));+ let ntu = vs.div_ceil(16);+ let p1 = s % 2;+ let p2 = ((2 + s - p1) / 2) % 2;+ let k3 = ((6 + s) % 8 - p1) / 2;+ let p3 = ((k3 - p2) / 2).rem_euclid(2);+ let (up1, up2, up3) = (p1 as usize, p2 as usize, p3 as usize);+ let comps = [&t.m, &t.c1, &t.c2];+ let bands: Vec<_> = comps.iter().map(|p| forward3(p, [p1 as u8, p2 as u8, p3 as u8])).collect();+ let qi = &t.qi;+ // streams[group][comp] -> halves+ let mut streams: Vec<Vec<Vec<(Vec<u8>, Vec<u32>)>>> =+ vec![vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new()]];+ for n in 0..2 * ntu as i32 {+ let rows: Vec<usize> = (8 * n - 6 + s..8 * n + 2 + s).filter(|&r| r >= 0 && (r as usize) < vs).map(|r| r as usize).collect();+ let (low1, high1) = split_rows(&rows, up1);+ let (low2, high2) = split_rows(&low1, up2);+ let (low3, high3) = split_rows(&low2, up3);+ for (c, b) in bands.iter().enumerate() {+ let cat = |parts: [Vec<Vec<i32>>; 3]| parts.into_iter().flatten().collect::<Vec<_>>();+ let dpcm = {+ let mut ll = quantised_rows(&b.ll3, &low3, 0);+ for l in &mut ll {+ let mut prev = 2048;+ for v in l.iter_mut() {+ (*v, prev) = (*v - prev, *v);+ }+ }+ ll+ };+ let sets: [(usize, Vec<Vec<i32>>, Vec<u32>); 4] = [+ (0, dpcm, vec![0]),+ (+ 1,+ cat([+ quantised_rows(&b.hl3, &low3, qi.l3[c][0]),+ quantised_rows(&b.lh3, &high3, qi.l3[c][1]),+ quantised_rows(&b.hh3, &high3, qi.l3[c][2]),+ ]),+ qi.l3[c].to_vec(),+ ),+ (+ 2,+ cat([+ quantised_rows(&b.hl2, &low2, qi.l2[c][0]),+ quantised_rows(&b.lh2, &high2, qi.l2[c][1]),+ quantised_rows(&b.hh2, &high2, qi.l2[c][2]),+ ]),+ qi.l2[c].to_vec(),+ ),+ (+ 3,+ cat([+ quantised_rows(&b.hl1, &low1, qi.l1[c][0]),+ quantised_rows(&b.lh1, &high1, qi.l1[c][1]),+ quantised_rows(&b.hh1, &high1, qi.l1[c][2]),+ ]),+ qi.l1[c].to_vec(),+ ),+ ];+ for (g, lines, q) in sets {+ streams[g][c].push((encode_lines(&lines), q));+ }+ }+ streams[4][0].push((encode_lines(&quantised_rows(&t.res, &rows, qi.res)), vec![qi.res]));+ }+ let blobs: Vec<Vec<Vec<u8>>> = streams.iter().map(|g| g.iter().map(|s| build_stream(s)).collect()).collect();+ let mut head = vec![0u8; 8 * 16];+ head[..4].copy_from_slice(b"0000"); // bytes 4..8: tile index, 0+ let tw = 2 * t.m.width;+ let w0: u64 = (tw as u64) << 48 | (vs as u64) << 32 | 16 << 20 | 3 << 13 | 3 << 10 | 0b10_0000_0000;+ head[8..16].copy_from_slice(&w0.to_be_bytes());+ for (g, group) in blobs.iter().enumerate() {+ let words: Vec<usize> = group.iter().map(|b| b.len() / 16).collect();+ head[(3 + g) * 16] = words.len() as u8;+ for (i, w) in words.iter().enumerate() {+ head[(3 + g) * 16 + 1 + 3 * i..][..3].copy_from_slice(&u24(*w));+ }+ head[16 + 3 * g..][..3].copy_from_slice(&u24(words.iter().sum()));+ }+ let mut out = head;+ out.extend(blobs.into_iter().flatten().flatten());+ out.resize(out.len().next_multiple_of(4096), 0);+ out+}++/// A little-endian ARW6 TIFF: IFD0 (Sony, ILCE-7RM6) + a SubIFD with the strip = tile table, zero padding to 512,+/// then the tiles `(x, y, w, h, bytes)` back to back.+pub(crate) fn arw6_file(tiles: &[(usize, usize, usize, usize, Vec<u8>)], width: usize, height: usize) -> Vec<u8> {+ let mut strip = (tiles.len() as u32).to_le_bytes().to_vec();+ strip.extend([0; 4]);+ let mut offset = 512u64;+ for (x, y, w, h, bytes) in tiles {+ strip.extend(offset.to_le_bytes());+ for v in [x, y, w, h] {+ strip.extend((*v as u32).to_le_bytes());+ }+ offset += bytes.len() as u64;+ }+ strip.resize(512, 0);+ for (.., bytes) in tiles {+ strip.extend_from_slice(bytes);+ }+ let mut raw = IfdBuilder::new();+ raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0]));+ raw.set(t::IMAGE_WIDTH, Value::Long(vec![width as u32]));+ raw.set(t::IMAGE_LENGTH, Value::Long(vec![height as u32]));+ raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![14]));+ raw.set(t::COMPRESSION, Value::Short(vec![32766]));+ raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA]));+ raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2]));+ raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2]));+ raw.set(0x7310, Value::Short(vec![512; 4]));+ raw.set(t::WHITE_LEVEL, Value::Long(vec![15360]));+ raw.set_image(ImageData::Strips { rows_per_strip: height as u32, strips: vec![strip] });+ let mut ifd0 = IfdBuilder::new();+ ifd0.set(t::MAKE, Value::Ascii("SONY".into()));+ ifd0.set(t::MODEL, Value::Ascii("ILCE-7RM6".into()));+ ifd0.set(t::ORIENTATION, Value::Short(vec![1]));+ ifd0.add_sub_ifd(raw);+ TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()+}diff --git a/crates/raw/src/vendor/mod.rs b/crates/raw/src/vendor/mod.rsindex 25f52cb5e..0e4ca4143 100644--- a/crates/raw/src/vendor/mod.rs+++ b/crates/raw/src/vendor/mod.rs@@ -1,6 +1,7 @@//! Vendor raw formats (TIFF-based) and helpers shared by them.pub mod arw;+pub mod arw6;#[cfg(test)]pub(crate) mod arw6_testenc;mod arw_lens;