bcpack.rs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. //! BCPack: lossless packing of BC1-BC7 block streams, as the console's
  2. //! DirectStorage hardware unpacks them. Decode only; BC2 is left out (no
  3. //! title data uses it).
  4. //!
  5. //! A packed stream has no header. It is 12 or 16 interleaved rANS *lanes*;
  6. //! each lane is a run of fragments (header byte, length, payload) coded with
  7. //! one of 128 static models, and a fixed schedule decides which lane takes
  8. //! the next input byte. The lanes' symbols form one record per block: two
  9. //! back references (to one of the last 256 blocks, or to a per-format
  10. //! dictionary that stands in for blocks -1 to -255) and the residuals of the
  11. //! endpoints and indices against them. The models, the index rank tables,
  12. //! the BC7 control codes and the dictionaries are constants of the format,
  13. //! kept in `bcpack-tables.bin` beside this file ([`Tables::builtin`]).
  14. use std::fmt;
  15. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  16. pub struct Error(pub &'static str);
  17. impl fmt::Display for Error {
  18. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  19. write!(f, "BCPack: {}", self.0)
  20. }
  21. }
  22. impl std::error::Error for Error {}
  23. const MODELS: usize = 128;
  24. const BUCKETS: usize = 9;
  25. const HISTORY: usize = 256;
  26. const DICTIONARY: usize = 255;
  27. /// rANS: decode while the state is above this, read while below.
  28. const LOW: u32 = 1 << 24;
  29. /// Input bytes per schedule round.
  30. const ROUND_BYTES: usize = 8;
  31. /// Bytes of the table file (see [`Tables::parse`]).
  32. pub const TABLES_SIZE: usize = MODELS * BUCKETS * 2
  33. + 256
  34. + 64
  35. + 256
  36. + 64
  37. + 64
  38. + 512 * 2
  39. + DICTIONARY * (6 + 16 + 8 + 32 + 2 + 16 + 4 + 32 + 25 + 33 + 50 + 66);
  40. /// Endpoints and indices of BC1, BC3, BC4 and BC5: small unsigned values,
  41. /// summed per element modulo the element's width.
  42. #[derive(Clone, Copy, Default)]
  43. struct Plain {
  44. ep: [u8; 8],
  45. ix: [u8; 32],
  46. }
  47. #[derive(Clone, Copy, Default)]
  48. struct Bc6Ep {
  49. /// Endpoint 0 R G B, then endpoints 1-3, left-aligned and biased.
  50. e: [[u16; 3]; 4],
  51. }
  52. #[derive(Clone, Copy, Default)]
  53. struct Bc6Ix {
  54. mode: u8,
  55. ix: [i16; 16],
  56. }
  57. #[derive(Clone, Copy, Default)]
  58. struct Bc7Ep {
  59. ctrl: u16,
  60. /// Per subset: R0 R1 G0 G1 B0 B1 A0 A1, left-aligned.
  61. rows: [[u16; 8]; 3],
  62. }
  63. #[derive(Clone, Copy, Default)]
  64. struct Bc7Ix {
  65. bits: [u8; 2],
  66. ix: [[i16; 16]; 2],
  67. }
  68. /// The format's constant tables.
  69. pub struct Tables {
  70. freq: [[u32; BUCKETS]; MODELS],
  71. start: [[u32; BUCKETS]; MODELS],
  72. /// ceil(2^32 / freq): exact division for the offsets inside a bucket.
  73. recip: [[u64; BUCKETS]; MODELS],
  74. rank1: [u8; 256],
  75. rank3a: [u8; 64],
  76. rank3c: [u8; 256],
  77. rank4: [u8; 64],
  78. rank5: [u8; 64],
  79. ctrl7: [u16; 512],
  80. bc1: Vec<Plain>,
  81. bc3: Vec<Plain>,
  82. bc4: Vec<Plain>,
  83. bc5: Vec<Plain>,
  84. bc6: Vec<(Bc6Ep, Bc6Ix)>,
  85. bc7: Vec<(Bc7Ep, Bc7Ix)>,
  86. }
  87. struct Reader<'a>(&'a [u8]);
  88. impl Reader<'_> {
  89. fn bytes<const N: usize>(&mut self) -> [u8; N] {
  90. let (head, rest) = self.0.split_at(N);
  91. self.0 = rest;
  92. head.try_into().unwrap_or([0; N])
  93. }
  94. fn u8(&mut self) -> u8 {
  95. self.bytes::<1>()[0]
  96. }
  97. fn u16(&mut self) -> u16 {
  98. u16::from_le_bytes(self.bytes())
  99. }
  100. }
  101. impl Tables {
  102. /// The tables VIctory ships with.
  103. pub fn builtin() -> Result<Tables, Error> {
  104. Tables::parse(include_bytes!("bcpack-tables.bin"))
  105. }
  106. /// Reads the table file: 128 x 9 u16 model frequencies (per bucket, the
  107. /// frequency of each of its symbols), the rank tables (BC1 256 B, BC3
  108. /// alpha 64 B and colour 256 B, BC4 64 B, BC5 64 B), 512 u16 BC7 control
  109. /// words, then 255 dictionary entries per format in format order: BC1
  110. /// 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H (u8 mode,
  111. /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 32 i16).
  112. /// Little-endian, no padding. Every model must tile 65536.
  113. pub fn parse(bytes: &[u8]) -> Result<Tables, Error> {
  114. if bytes.len() != TABLES_SIZE {
  115. return Err(Error("table file has the wrong size"));
  116. }
  117. let mut r = Reader(bytes);
  118. let mut freq = [[0u32; BUCKETS]; MODELS];
  119. let mut start = [[0u32; BUCKETS]; MODELS];
  120. let mut recip = [[0u64; BUCKETS]; MODELS];
  121. for m in 0..MODELS {
  122. for f in &mut freq[m] {
  123. *f = u32::from(r.u16());
  124. }
  125. // Model 16 g + shape has g + 2 buckets; bucket b > 0 holds 2^(b-1) symbols.
  126. let used = m / 16 + 2;
  127. let mut at = 0u32;
  128. for b in 0..used {
  129. if freq[m][b] == 0 {
  130. return Err(Error("a model has an empty bucket"));
  131. }
  132. start[m][b] = at;
  133. recip[m][b] = (1u64 << 32).div_ceil(u64::from(freq[m][b]));
  134. at += freq[m][b] << b.saturating_sub(1);
  135. }
  136. if at != 1 << 16 {
  137. return Err(Error("a model does not tile 65536"));
  138. }
  139. start[m][used..].fill(1 << 16);
  140. }
  141. let rank1 = r.bytes();
  142. let rank3a = r.bytes();
  143. let rank3c = r.bytes();
  144. let rank4 = r.bytes();
  145. let rank5 = r.bytes();
  146. let mut ctrl7 = [0u16; 512];
  147. for c in &mut ctrl7 {
  148. *c = r.u16();
  149. }
  150. let mut plain = |ep: usize, ix: usize| {
  151. (0..DICTIONARY)
  152. .map(|_| {
  153. let mut p = Plain::default();
  154. for v in &mut p.ep[..ep] {
  155. *v = r.u8();
  156. }
  157. for v in &mut p.ix[..ix] {
  158. *v = r.u8();
  159. }
  160. p
  161. })
  162. .collect::<Vec<_>>()
  163. };
  164. let bc1 = plain(6, 16);
  165. let bc3 = plain(8, 32);
  166. let bc4 = plain(2, 16);
  167. let bc5 = plain(4, 32);
  168. let bc6 = (0..DICTIONARY)
  169. .map(|_| {
  170. // The endpoint entry's mode byte plays no part in decoding.
  171. r.u8();
  172. let mut ep = Bc6Ep::default();
  173. for v in ep.e.as_flattened_mut() {
  174. *v = r.u16();
  175. }
  176. let mut ix = Bc6Ix {
  177. mode: r.u8(),
  178. ..Default::default()
  179. };
  180. for v in &mut ix.ix {
  181. *v = r.u16() as i16;
  182. }
  183. (ep, ix)
  184. })
  185. .collect();
  186. let bc7 = (0..DICTIONARY)
  187. .map(|_| {
  188. let mut ep = Bc7Ep {
  189. ctrl: r.u16(),
  190. ..Default::default()
  191. };
  192. for v in ep.rows.as_flattened_mut() {
  193. *v = r.u16();
  194. }
  195. let mut ix = Bc7Ix {
  196. bits: [r.u8(), r.u8()],
  197. ..Default::default()
  198. };
  199. for v in ix.ix.as_flattened_mut() {
  200. *v = r.u16() as i16;
  201. }
  202. (ep, ix)
  203. })
  204. .collect();
  205. Ok(Tables {
  206. freq,
  207. start,
  208. recip,
  209. rank1,
  210. rank3a,
  211. rank3c,
  212. rank4,
  213. rank5,
  214. ctrl7,
  215. bc1,
  216. bc3,
  217. bc4,
  218. bc5,
  219. bc6,
  220. bc7,
  221. })
  222. }
  223. }
  224. /// Unpacks `src` (BC number `bc`, 1 and 3-7) into `dst`, whose length gives
  225. /// the block count. The stream carries no size: bytes after the last one the
  226. /// lanes need are ignored, a stream that runs out is an error.
  227. pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), Error> {
  228. let block = match bc {
  229. 1 | 4 => 8,
  230. 3 | 5 | 6 | 7 => 16,
  231. _ => return Err(Error("unsupported BC format")),
  232. };
  233. if dst.is_empty() || !dst.len().is_multiple_of(block) {
  234. return Err(Error("destination is not a whole number of blocks"));
  235. }
  236. let blocks = dst.len() / block;
  237. let (widths, per): (&[u8], usize) = match bc {
  238. 1 => (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1),
  239. 3 => (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2),
  240. 4 => (&[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 1),
  241. 5 => (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2),
  242. 6 => (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2),
  243. _ => (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2),
  244. };
  245. let stride = widths.len() * per;
  246. let mut records = vec![0u8; blocks * stride];
  247. let mut next = src.iter().copied();
  248. lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?;
  249. let records = records.chunks_exact(stride);
  250. let out = dst.chunks_exact_mut(block);
  251. let t = tables;
  252. match bc {
  253. 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack),
  254. 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack),
  255. 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack),
  256. 5 => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack),
  257. 6 => bc6(records, out, &t.bc6),
  258. _ => bc7(records, out, t),
  259. }
  260. }
  261. // Lanes.
  262. #[derive(Clone, Copy, Default)]
  263. struct Lane {
  264. /// Symbol bits - 1 at the full alphabet.
  265. width: u8,
  266. /// 0 header, 1 length (low byte), 2 length high byte, 3 payload.
  267. phase: u8,
  268. long: bool,
  269. reset: bool,
  270. model: u8,
  271. need: bool,
  272. latch: Option<u8>,
  273. out: Option<u8>,
  274. stalled: bool,
  275. x: u32,
  276. left: u32,
  277. }
  278. impl Lane {
  279. /// One step: take the latched byte (header, length or payload) and
  280. /// decode at most one symbol.
  281. fn step(&mut self, t: &Tables) -> Result<(), Error> {
  282. if self.phase != 3 {
  283. let Some(b) = self.latch.take() else {
  284. return Ok(());
  285. };
  286. self.need = true;
  287. match self.phase {
  288. 0 => {
  289. // The top two bits shrink the alphabet; width >= 3.
  290. let group = self.width - (b >> 6);
  291. self.model = group * 16 + (b & 15);
  292. self.reset = b & 0x10 != 0;
  293. self.long = b & 0x20 != 0;
  294. self.left = 0;
  295. self.phase = 1;
  296. }
  297. 1 if self.long => {
  298. self.left = b.into();
  299. self.phase = 2;
  300. }
  301. 1 => {
  302. self.left = u32::from(b) + 1;
  303. self.phase = 3;
  304. }
  305. _ => {
  306. self.left = (u32::from(b) << 8 | self.left) + 257;
  307. self.phase = 3;
  308. }
  309. }
  310. return Ok(());
  311. }
  312. let mut x = self.x;
  313. if x < LOW
  314. && let Some(b) = self.latch.take()
  315. {
  316. self.left = self.left.wrapping_sub(1);
  317. x = x << 8 | u32::from(b);
  318. }
  319. self.need = self.left != 0 && self.latch.is_none();
  320. if x > LOW {
  321. let freq = &t.freq[usize::from(self.model)];
  322. let start = &t.start[usize::from(self.model)];
  323. let slot = x & 0xffff;
  324. // The bucket: starts are ascending, and 65536 past the model's last.
  325. let b = start[1..].iter().filter(|&&s| s <= slot).count();
  326. // Buckets 0 and 1 hold one symbol. Elsewhere offset and frequency
  327. // are below 2^16, where the reciprocal divides exactly.
  328. let sym = match b {
  329. 0 => 0,
  330. 1 => 1,
  331. _ => {
  332. let rec = t.recip[usize::from(self.model)][b];
  333. (1 << (b - 1)) + ((u64::from(slot - start[b]) * rec) >> 32) as u8
  334. }
  335. };
  336. // Slot 0 is never used: symbol 0 owns 1 .. f[0] - 1.
  337. let (f, c) = if sym == 0 {
  338. (freq[0] - 1, 1)
  339. } else {
  340. let k = (8 - sym.leading_zeros()) as usize;
  341. let f = freq[k];
  342. (
  343. f,
  344. (u32::from(sym) - (1 << (k - 1)))
  345. .wrapping_mul(f)
  346. .wrapping_add(start[k])
  347. & 0xffff,
  348. )
  349. };
  350. self.x = (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot);
  351. self.out = Some(sym);
  352. } else if self.left != 0 {
  353. // At exactly 2^24 the lane neither reads nor decodes again; only a
  354. // lane that has delivered its symbols may end up there.
  355. self.x = x;
  356. } else {
  357. // The fragment ends; a byte read in this step does not reach the carried state.
  358. self.phase = 0;
  359. self.need = self.latch.is_none();
  360. if self.reset {
  361. self.x = 0;
  362. }
  363. }
  364. Ok(())
  365. }
  366. }
  367. /// Decodes `per` symbols per block on every lane into `records` (one record
  368. /// of `widths.len() * per` symbols per block), taking input from `fetch`
  369. /// (given the lane that takes the byte) in the order of the schedule: each
  370. /// round the lanes step in order and take at most 8 bytes between them.
  371. // shortcut: one lane step at a time (BC1 roughly 30-60 MB/s, BC7 15-20 MB/s
  372. // on one core); if texture streaming needs more, run the schedule only to
  373. // split the input per lane and decode the lanes apart.
  374. fn lanes(
  375. t: &Tables,
  376. widths: &[u8],
  377. per: usize,
  378. blocks: usize,
  379. mut fetch: impl FnMut(usize) -> Option<u8>,
  380. records: &mut [u8],
  381. ) -> Result<(), Error> {
  382. let mut lanes = [Lane::default(); 16];
  383. let lanes = &mut lanes[..widths.len()];
  384. for (lane, &width) in lanes.iter_mut().zip(widths) {
  385. lane.width = width;
  386. lane.need = true;
  387. }
  388. let stride = widths.len() * per;
  389. let full = (1u32 << widths.len()) - 1;
  390. let (mut pos, mut done, mut idle) = (0, 0u32, 0);
  391. while pos < blocks * per {
  392. let (mut taken, mut moved) = (0, false);
  393. for (j, lane) in lanes.iter_mut().enumerate() {
  394. let bit = 1 << j;
  395. let before = taken;
  396. if !lane.stalled {
  397. lane.step(t)?;
  398. }
  399. let waiting = lane.out.is_some() && done & bit != 0;
  400. if lane.need && !waiting && taken < ROUND_BYTES {
  401. // Past the end nothing arrives; in a valid stream only finished lanes ask there.
  402. if let Some(b) = fetch(j) {
  403. lane.latch = Some(b);
  404. taken += 1;
  405. }
  406. }
  407. lane.stalled = (lane.need && before >= ROUND_BYTES) || waiting;
  408. if !lane.stalled
  409. && let Some(sym) = lane.out.take()
  410. {
  411. records[pos / per * stride + j * per + pos % per] = sym;
  412. done |= bit;
  413. moved = true;
  414. }
  415. }
  416. if done == full {
  417. pos += 1;
  418. done = 0;
  419. moved = true;
  420. }
  421. // Nothing read and nothing delivered for a few rounds: no lane can go on.
  422. idle = if taken > 0 || moved { 0 } else { idle + 1 };
  423. if idle > 3 {
  424. return Err(Error("the stream ends early or is corrupt"));
  425. }
  426. }
  427. Ok(())
  428. }
  429. // Blocks.
  430. /// The record's endpoint and index references.
  431. fn references(s: &[u8], paired: bool) -> (usize, usize) {
  432. let (d, ix) = if paired {
  433. (interleave(s[0], s[1]), interleave(s[2], s[3]))
  434. } else {
  435. (s[0], s[1])
  436. };
  437. let delta = (d >> 1) ^ (d & 1).wrapping_neg();
  438. (usize::from(ix.wrapping_add(delta)), usize::from(ix))
  439. }
  440. /// Two 4-bit symbols, the first on the even bits.
  441. fn interleave(a: u8, b: u8) -> u8 {
  442. let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k));
  443. spread(a) | spread(b) << 1
  444. }
  445. /// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first
  446. /// block into the dictionary.
  447. fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: &'a T) -> &'a T {
  448. match r {
  449. 0 => zero,
  450. r if r <= i => &history[(i - r) % HISTORY],
  451. r => &dictionary[r - i - 1],
  452. }
  453. }
  454. /// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits.
  455. fn zz(v: u8, bits: u32) -> u8 {
  456. let mask = ((1u32 << bits) - 1) as u8;
  457. ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask
  458. }
  459. /// Element widths of the plain formats' endpoints and indices.
  460. struct Widths {
  461. ep: [u8; 8],
  462. ix: [u8; 32],
  463. paired: bool,
  464. }
  465. const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths {
  466. let mut ix = [0; 32];
  467. let mut k = 0;
  468. while k < ix3 + ix2 {
  469. ix[k] = if k < ix3 { 3 } else { 2 };
  470. k += 1;
  471. }
  472. Widths { ep, ix, paired }
  473. }
  474. const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false);
  475. const BC3: Widths = widths([5, 6, 5, 5, 6, 5, 8, 8], 16, 16, true);
  476. const BC4: Widths = widths([8, 8, 0, 0, 0, 0, 0, 0], 16, 0, false);
  477. const BC5: Widths = widths([8, 8, 8, 8, 0, 0, 0, 0], 32, 0, true);
  478. fn plain<'a>(
  479. records: impl Iterator<Item = &'a [u8]>,
  480. out: impl Iterator<Item = &'a mut [u8]>,
  481. dictionary: &[Plain],
  482. w: &Widths,
  483. residual: impl Fn(&[u8]) -> Plain,
  484. pack: fn(&Plain, &mut [u8]),
  485. ) -> Result<(), Error> {
  486. let mut history = vec![Plain::default(); HISTORY];
  487. let zero = Plain::default();
  488. for (i, (s, block)) in records.zip(out).enumerate() {
  489. let (ep_ref, ix_ref) = references(s, w.paired);
  490. let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep;
  491. let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix;
  492. let mut v = residual(s);
  493. for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) {
  494. *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8;
  495. }
  496. for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) {
  497. *v = v.wrapping_add(*r) & ((1u8 << bits) - 1);
  498. }
  499. history[i % HISTORY] = v;
  500. pack(&v, block);
  501. }
  502. Ok(())
  503. }
  504. /// 2-bit index residuals: one symbol per 2x2 quad.
  505. fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) {
  506. for (q, &sym) in s.iter().enumerate() {
  507. let v = rank[usize::from(sym)];
  508. let base = (q >> 1) * 8 + (q & 1) * 2;
  509. for (k, p) in [0, 1, 4, 5].into_iter().enumerate() {
  510. ix[base + p] = v >> (2 * k) & 3;
  511. }
  512. }
  513. }
  514. /// 3-bit index residuals: one symbol per two pixels in raster order.
  515. fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) {
  516. for (k, &sym) in s.iter().enumerate() {
  517. let v = rank[usize::from(sym & 63)];
  518. ix[2 * k] = v & 7;
  519. ix[2 * k + 1] = v >> 4 & 7;
  520. }
  521. }
  522. fn bc1_residual(t: &Tables, s: &[u8]) -> Plain {
  523. let mut v = Plain::default();
  524. for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() {
  525. v.ep[k] = zz(s[2 + k], bits);
  526. }
  527. quads(&t.rank1, &s[8..12], &mut v.ix);
  528. v
  529. }
  530. fn bc3_residual(t: &Tables, s: &[u8]) -> Plain {
  531. // Colour lanes carry each channel's two endpoints together.
  532. let mut v = Plain {
  533. ep: [
  534. zz(s[14], 5),
  535. zz(s[16], 6),
  536. zz(s[18], 5),
  537. zz(s[15], 5),
  538. zz(s[17], 6),
  539. zz(s[19], 5),
  540. zz(s[4], 8),
  541. zz(s[5], 8),
  542. ],
  543. ..Default::default()
  544. };
  545. pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]);
  546. quads(&t.rank3c, &s[20..24], &mut v.ix[16..]);
  547. v
  548. }
  549. fn bc4_residual(t: &Tables, s: &[u8]) -> Plain {
  550. let mut v = Plain::default();
  551. v.ep[..2].copy_from_slice(&[zz(s[2], 8), zz(s[3], 8)]);
  552. pairs(&t.rank4, &s[4..12], &mut v.ix[..16]);
  553. v
  554. }
  555. fn bc5_residual(t: &Tables, s: &[u8]) -> Plain {
  556. let mut v = Plain::default();
  557. for k in 0..4 {
  558. v.ep[k] = zz(s[4 + k], 8);
  559. }
  560. pairs(&t.rank5, &s[8..24], &mut v.ix);
  561. v
  562. }
  563. /// Indices along the endpoint line -> BC1 and BC4 codes.
  564. const BC1_CODE: [u32; 4] = [0, 2, 3, 1];
  565. const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1];
  566. fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) {
  567. let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]);
  568. let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]);
  569. let bits = (0..16).fold(0, |acc, p| {
  570. acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p)
  571. });
  572. out[..2].copy_from_slice(&c0.to_le_bytes());
  573. out[2..4].copy_from_slice(&c1.to_le_bytes());
  574. out[4..8].copy_from_slice(&bits.to_le_bytes());
  575. }
  576. /// BC4 half: endpoints are kept 128 below their stored value.
  577. fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) {
  578. let bits = (0..16).fold(0u64, |acc, p| {
  579. acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p)
  580. });
  581. let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits;
  582. out[..8].copy_from_slice(&v.to_le_bytes());
  583. }
  584. fn bc1_pack(v: &Plain, out: &mut [u8]) {
  585. bc1_color(&v.ep, &v.ix, out);
  586. }
  587. fn bc3_pack(v: &Plain, out: &mut [u8]) {
  588. bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]);
  589. bc1_color(&v.ep, &v.ix[16..], &mut out[8..]);
  590. }
  591. fn bc4_pack(v: &Plain, out: &mut [u8]) {
  592. bc4_alpha(v.ep[0], v.ep[1], &v.ix, out);
  593. }
  594. fn bc5_pack(v: &Plain, out: &mut [u8]) {
  595. bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]);
  596. bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]);
  597. }
  598. /// A byte's even and odd bits as two zigzag-coded 4-bit residuals.
  599. fn nibbles(b: u8, odd_first: bool) -> [i16; 2] {
  600. let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k);
  601. let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1);
  602. let (even, odd) = (z(half(b)), z(half(b >> 1)));
  603. if odd_first { [odd, even] } else { [even, odd] }
  604. }
  605. /// Index residual plus reference, both left-aligned to 16 bits at their own
  606. /// widths, back to `bits` bits (signed).
  607. fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 {
  608. let up = |v: i16, b: u8| {
  609. if b == 0 || b > 16 {
  610. 0
  611. } else {
  612. (v as u16) << (16 - b)
  613. }
  614. };
  615. let sum = up(cur, bits).wrapping_add(up(refv, ref_bits)) as i16;
  616. if bits == 0 { 0 } else { sum >> (16 - bits) }
  617. }
  618. /// Little-endian bit writer for one 128-bit block.
  619. #[derive(Default)]
  620. struct Bits {
  621. v: u128,
  622. at: u32,
  623. }
  624. impl Bits {
  625. fn put(&mut self, value: u64, n: u32) {
  626. if n > 0 && self.at < 128 {
  627. self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at;
  628. }
  629. self.at += n;
  630. }
  631. }
  632. // BC7.
  633. /// Public BC7 anchor indices: second subset of two; second and third of three.
  634. const ANCHOR2: [u8; 64] = [
  635. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8,
  636. 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2,
  637. 2, 15, 15, 15, 15, 15, 2, 2, 15,
  638. ];
  639. const ANCHOR3A: [u8; 64] = [
  640. 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5,
  641. 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5,
  642. 10, 8, 13, 15, 12, 3, 3,
  643. ];
  644. const ANCHOR3B: [u8; 64] = [
  645. 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6,
  646. 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15,
  647. 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8,
  648. ];
  649. /// Endpoint bits of R G B A per mode (public), before p-bits and rotation.
  650. const BC7_BITS: [[u8; 4]; 8] = [
  651. [4, 4, 4, 0],
  652. [6, 6, 6, 0],
  653. [5, 5, 5, 0],
  654. [7, 7, 7, 0],
  655. [5, 5, 5, 6],
  656. [7, 7, 7, 8],
  657. [7, 7, 7, 7],
  658. [5, 5, 5, 5],
  659. ];
  660. /// Index bits of the primary and secondary sets per mode.
  661. const BC7_INDEX: [[u8; 2]; 8] = [
  662. [3, 0],
  663. [3, 0],
  664. [2, 0],
  665. [2, 0],
  666. [3, 2],
  667. [2, 2],
  668. [4, 0],
  669. [2, 0],
  670. ];
  671. fn pbits(mode: u16) -> bool {
  672. matches!(mode, 0 | 1 | 3 | 6 | 7)
  673. }
  674. /// Channel precisions: the p-bit is red's lowest bit; rotation swaps alpha
  675. /// with the rotated channel.
  676. fn bc7_precision(ctrl: u16) -> [u8; 4] {
  677. let (mode, rot) = (ctrl & 7, usize::from(ctrl >> 3 & 3));
  678. let mut p = BC7_BITS[usize::from(mode)];
  679. if rot != 0 {
  680. p.swap(3, rot - 1);
  681. } else if pbits(mode) {
  682. p[0] += 1;
  683. }
  684. p
  685. }
  686. fn bc7<'a>(
  687. records: impl Iterator<Item = &'a [u8]>,
  688. out: impl Iterator<Item = &'a mut [u8]>,
  689. t: &Tables,
  690. ) -> Result<(), Error> {
  691. let mut history = vec![(Bc7Ep::default(), Bc7Ix::default()); HISTORY];
  692. let zero = (Bc7Ep::default(), Bc7Ix::default());
  693. for (i, (s, block)) in records.zip(out).enumerate() {
  694. let (ep_ref, ix_ref) = references(s, true);
  695. let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)];
  696. if ctrl == 0 {
  697. return Err(Error("unused BC7 control code"));
  698. }
  699. let mode = usize::from(ctrl & 7);
  700. let subsets = usize::from((ctrl & 0xff) >> 6);
  701. let prec = bc7_precision(ctrl);
  702. let three = subsets == 3;
  703. let or0 = |v: u8| if three { 0 } else { v };
  704. let if3 = |v: u8| if three { v } else { 0 };
  705. let stored = [
  706. [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])],
  707. [
  708. s[12],
  709. s[13],
  710. s[14],
  711. s[15],
  712. s[16],
  713. s[17],
  714. or0(s[18]),
  715. or0(s[19]),
  716. ],
  717. [
  718. s[20],
  719. s[21],
  720. if3(s[10]),
  721. if3(s[11]),
  722. if3(s[18]),
  723. if3(s[19]),
  724. 0,
  725. 0,
  726. ],
  727. ];
  728. let r = &pick(i, ep_ref, &history, &t.bc7, &zero).0;
  729. let mut ep = Bc7Ep {
  730. ctrl,
  731. ..Default::default()
  732. };
  733. // Rows the reference lacks build on its first row.
  734. let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6));
  735. let columns = if prec[3] > 0 { 8 } else { 6 };
  736. for c in 0..columns {
  737. let p = prec[c / 2];
  738. if p == 0 {
  739. continue;
  740. }
  741. let mask = 0xffffu16 << (16 - p);
  742. for (row, st) in stored.iter().enumerate().take(subsets) {
  743. let v = st[c];
  744. let residual =
  745. (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p);
  746. let base = r.rows[if row < common { row } else { 0 }][c] & mask;
  747. ep.rows[row][c] = base.wrapping_add(residual);
  748. }
  749. }
  750. let bits = BC7_INDEX[mode];
  751. let rx = &pick(i, ix_ref, &history, &t.bc7, &zero).1;
  752. let mut ix = Bc7Ix {
  753. bits,
  754. ..Default::default()
  755. };
  756. for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() {
  757. if bits[set] == 0 {
  758. continue;
  759. }
  760. for (k, o) in offsets.into_iter().enumerate() {
  761. for (b, &byte) in s[o..o + 2].iter().enumerate() {
  762. let pair = nibbles(byte, k < 3);
  763. for (h, &v) in pair.iter().enumerate() {
  764. let p = 4 * k + 2 * b + h;
  765. ix.ix[set][p] = add_index(v, bits[set], rx.ix[set][p], rx.bits[set]);
  766. }
  767. }
  768. }
  769. }
  770. history[i % HISTORY] = (ep, ix);
  771. bc7_pack(&ep, &ix, prec, block);
  772. }
  773. Ok(())
  774. }
  775. fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) {
  776. let ctrl = ep.ctrl;
  777. let mode = ctrl & 7;
  778. let subsets = usize::from((ctrl & 0xff) >> 6);
  779. let part = usize::from(ctrl >> 8 & 63);
  780. let rot = usize::from(ctrl >> 3 & 3);
  781. let mut w = Bits::default();
  782. w.put(1 << mode, u32::from(mode) + 1);
  783. match mode {
  784. 0 => w.put(part as u64, 4),
  785. 1 | 2 | 3 | 7 => w.put(part as u64, 6),
  786. 4 => {
  787. w.put(rot as u64, 2);
  788. w.put(u64::from(ctrl >> 5 & 1), 1);
  789. }
  790. 5 => w.put(rot as u64, 2),
  791. _ => {}
  792. }
  793. let ends = 2 * subsets;
  794. let field = |row: usize, col: usize, p: u8| u64::from(ep.rows[row][col] >> (16 - p));
  795. let mut order = [0, 1, 2, 3];
  796. if rot != 0 {
  797. order.swap(3, rot - 1);
  798. }
  799. for ch in order {
  800. let p = prec[ch];
  801. if p == 0 {
  802. continue;
  803. }
  804. let drop = u32::from(ch == 0 && pbits(mode));
  805. for e in 0..ends {
  806. w.put(field(e / 2, 2 * ch + e % 2, p) >> drop, u32::from(p) - drop);
  807. }
  808. }
  809. match mode {
  810. 1 => (0..subsets).for_each(|row| w.put(field(row, 0, prec[0]) & 1, 1)),
  811. m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)),
  812. _ => {}
  813. }
  814. let anchors: &[u8] = match subsets {
  815. 2 => &[0, ANCHOR2[part]],
  816. 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]],
  817. _ => &[0],
  818. };
  819. let mut indices = |set: usize| {
  820. let bits = ix.bits[set];
  821. for (p, &v) in ix.ix[set].iter().enumerate() {
  822. let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8)));
  823. w.put(u64::from(v as u16), n);
  824. }
  825. };
  826. match mode {
  827. 4 => {
  828. indices(1);
  829. indices(0);
  830. }
  831. 5 => {
  832. indices(0);
  833. indices(1);
  834. }
  835. _ => indices(0),
  836. }
  837. out.copy_from_slice(&w.v.to_le_bytes());
  838. }
  839. // BC6H.
  840. /// Bits of endpoint 0, then of the other endpoints' R, G, B, per mode 1-14.
  841. const BC6_BITS: [[u8; 4]; 15] = [
  842. [0; 4],
  843. [10, 5, 5, 5],
  844. [7, 6, 6, 6],
  845. [11, 5, 4, 4],
  846. [11, 4, 5, 4],
  847. [11, 4, 4, 5],
  848. [9, 5, 5, 5],
  849. [8, 6, 5, 5],
  850. [8, 5, 6, 5],
  851. [8, 5, 5, 6],
  852. [6, 6, 6, 6],
  853. [10, 10, 10, 10],
  854. [11, 9, 9, 9],
  855. [12, 8, 8, 8],
  856. [16, 4, 4, 4],
  857. ];
  858. /// Mode code and its width, modes 1-14.
  859. const BC6_CODE: [(u64, u32); 15] = [
  860. (0, 0),
  861. (0, 2),
  862. (1, 2),
  863. (2, 5),
  864. (6, 5),
  865. (10, 5),
  866. (14, 5),
  867. (18, 5),
  868. (22, 5),
  869. (26, 5),
  870. (30, 5),
  871. (3, 5),
  872. (7, 5),
  873. (11, 5),
  874. (15, 5),
  875. ];
  876. /// A run of the public BC6H layout: `len` bits of channel `ch` (0-2; 3 is
  877. /// the partition) of endpoint `ep`, from bit `first` up.
  878. #[derive(Clone, Copy)]
  879. struct Run {
  880. ch: u8,
  881. ep: u8,
  882. first: u8,
  883. len: u8,
  884. }
  885. const fn r(ch: u8, ep: u8, first: u8, len: u8) -> Run {
  886. Run { ch, ep, first, len }
  887. }
  888. const R: u8 = 0;
  889. const G: u8 = 1;
  890. const B: u8 = 2;
  891. const D: Run = r(3, 0, 0, 5);
  892. /// The header after the mode bits, per mode 1-14. Modes 13 and 14 write the
  893. /// high base bits in ascending order (what the console's packer does).
  894. #[rustfmt::skip]
  895. const BC6_LAYOUT: [&[Run]; 15] = [
  896. &[],
  897. &[
  898. r(G, 2, 4, 1), r(B, 2, 4, 1), r(B, 3, 4, 1), r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10),
  899. r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4),
  900. r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5),
  901. r(B, 3, 3, 1), D,
  902. ],
  903. &[
  904. r(G, 2, 5, 1), r(G, 3, 4, 1), r(G, 3, 5, 1), r(R, 0, 0, 7), r(B, 3, 0, 1), r(B, 3, 1, 1),
  905. r(B, 2, 4, 1), r(G, 0, 0, 7), r(B, 2, 5, 1), r(B, 3, 2, 1), r(G, 2, 4, 1), r(B, 0, 0, 7),
  906. r(B, 3, 3, 1), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 6),
  907. r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 6), r(R, 3, 0, 6), D,
  908. ],
  909. &[
  910. r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 5), r(R, 0, 10, 1), r(G, 2, 0, 4),
  911. r(G, 1, 0, 4), r(G, 0, 10, 1), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 4), r(B, 0, 10, 1),
  912. r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D,
  913. ],
  914. &[
  915. r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 1), r(G, 3, 4, 1),
  916. r(G, 2, 0, 4), r(G, 1, 0, 5), r(G, 0, 10, 1), r(G, 3, 0, 4), r(B, 1, 0, 4), r(B, 0, 10, 1),
  917. r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 4), r(B, 3, 0, 1), r(B, 3, 2, 1), r(R, 3, 0, 4),
  918. r(G, 2, 4, 1), r(B, 3, 3, 1), D,
  919. ],
  920. &[
  921. r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 1), r(B, 2, 4, 1),
  922. r(G, 2, 0, 4), r(G, 1, 0, 4), r(G, 0, 10, 1), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 5),
  923. r(B, 0, 10, 1), r(B, 2, 0, 4), r(R, 2, 0, 4), r(B, 3, 1, 1), r(B, 3, 2, 1), r(R, 3, 0, 4),
  924. r(B, 3, 4, 1), r(B, 3, 3, 1), D,
  925. ],
  926. &[
  927. r(R, 0, 0, 9), r(B, 2, 4, 1), r(G, 0, 0, 9), r(G, 2, 4, 1), r(B, 0, 0, 9), r(B, 3, 4, 1),
  928. r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4),
  929. r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5),
  930. r(B, 3, 3, 1), D,
  931. ],
  932. &[
  933. r(R, 0, 0, 8), r(G, 3, 4, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(B, 3, 2, 1), r(G, 2, 4, 1),
  934. r(B, 0, 0, 8), r(B, 3, 3, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 5),
  935. r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 6),
  936. r(R, 3, 0, 6), D,
  937. ],
  938. &[
  939. r(R, 0, 0, 8), r(B, 3, 0, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(G, 2, 5, 1), r(G, 2, 4, 1),
  940. r(B, 0, 0, 8), r(G, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4),
  941. r(G, 1, 0, 6), r(G, 3, 0, 4), r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5),
  942. r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D,
  943. ],
  944. &[
  945. r(R, 0, 0, 8), r(B, 3, 1, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(B, 2, 5, 1), r(G, 2, 4, 1),
  946. r(B, 0, 0, 8), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4),
  947. r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 5),
  948. r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D,
  949. ],
  950. &[
  951. r(R, 0, 0, 6), r(G, 3, 4, 1), r(B, 3, 0, 1), r(B, 3, 1, 1), r(B, 2, 4, 1), r(G, 0, 0, 6),
  952. r(G, 2, 5, 1), r(B, 2, 5, 1), r(B, 3, 2, 1), r(G, 2, 4, 1), r(B, 0, 0, 6), r(G, 3, 5, 1),
  953. r(B, 3, 3, 1), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 6),
  954. r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 6), r(R, 3, 0, 6), D,
  955. ],
  956. &[r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 10), r(G, 1, 0, 10), r(B, 1, 0, 10)],
  957. &[
  958. r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 9), r(R, 0, 10, 1), r(G, 1, 0, 9),
  959. r(G, 0, 10, 1), r(B, 1, 0, 9), r(B, 0, 10, 1),
  960. ],
  961. &[
  962. r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 8), r(R, 0, 10, 2), r(G, 1, 0, 8),
  963. r(G, 0, 10, 2), r(B, 1, 0, 8), r(B, 0, 10, 2),
  964. ],
  965. &[
  966. r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 6), r(G, 1, 0, 4),
  967. r(G, 0, 10, 6), r(B, 1, 0, 4), r(B, 0, 10, 6),
  968. ],
  969. ];
  970. fn bc6_index_bits(mode: u8) -> u8 {
  971. match mode {
  972. 1..=10 => 3,
  973. 11..=14 => 4,
  974. _ => 0,
  975. }
  976. }
  977. fn bc6<'a>(
  978. records: impl Iterator<Item = &'a [u8]>,
  979. out: impl Iterator<Item = &'a mut [u8]>,
  980. dictionary: &[(Bc6Ep, Bc6Ix)],
  981. ) -> Result<(), Error> {
  982. let mut history = vec![(Bc6Ep::default(), Bc6Ix::default()); HISTORY];
  983. let zero = (
  984. Bc6Ep::default(),
  985. Bc6Ix {
  986. mode: 11,
  987. ..Default::default()
  988. },
  989. );
  990. let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg();
  991. let wide = |a: u8, b: u8| {
  992. (0..8).fold(0u16, |acc, k| {
  993. acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1)
  994. })
  995. };
  996. for (i, (s, block)) in records.zip(out).enumerate() {
  997. let (ep_ref, ix_ref) = references(s, true);
  998. let mode = s[30].wrapping_add(1);
  999. if !(1..=14).contains(&mode) {
  1000. return Err(Error("BC6H mode out of range"));
  1001. }
  1002. let two = mode < 11;
  1003. let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b));
  1004. let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z);
  1005. let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z);
  1006. let (e2, e3) = if two {
  1007. (
  1008. [s[16], s[18], s[20]].map(|v| z(v.into())),
  1009. [s[17], s[19], s[21]].map(|v| z(v.into())),
  1010. )
  1011. } else {
  1012. (e0, e1)
  1013. };
  1014. let r = &pick(i, ep_ref, &history, dictionary, &zero).0;
  1015. let mut ep = Bc6Ep::default();
  1016. // Endpoint 0 at the base precision, the others per channel; the
  1017. // reference is cut by the mask after the sum.
  1018. let mask = |sh: u32| 0xffffu16 << sh;
  1019. for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) {
  1020. *e = r.wrapping_add(res << shift[0]) & mask(shift[0]);
  1021. }
  1022. for (k, res) in [e1, e2, e3]
  1023. .iter()
  1024. .enumerate()
  1025. .take(if two { 3 } else { 1 })
  1026. {
  1027. for c in 0..3 {
  1028. ep.e[k + 1][c] =
  1029. r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]);
  1030. }
  1031. }
  1032. if !two {
  1033. for c in 0..3 {
  1034. ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1];
  1035. }
  1036. ep.e[3] = ep.e[1];
  1037. }
  1038. let rx = &pick(i, ix_ref, &history, dictionary, &zero).1;
  1039. let bits = bc6_index_bits(mode);
  1040. let mut ix = Bc6Ix {
  1041. mode,
  1042. ..Default::default()
  1043. };
  1044. for k in 0..8 {
  1045. for (h, v) in nibbles(s[22 + k], k < 6).into_iter().enumerate() {
  1046. let p = 2 * k + h;
  1047. ix.ix[p] = add_index(v, bits, rx.ix[p], bc6_index_bits(rx.mode));
  1048. }
  1049. }
  1050. history[i % HISTORY] = (ep, ix);
  1051. // Fields: the working value has its top bit flipped.
  1052. let field = |k: usize, c: usize| {
  1053. let sh = if k == 0 { shift[0] } else { shift[1 + c] };
  1054. u64::from((ep.e[k][c] ^ 0x8000) >> sh)
  1055. };
  1056. let mut w = Bits::default();
  1057. let (code, n) = BC6_CODE[usize::from(mode)];
  1058. w.put(code, n);
  1059. let part = s[31] & 31;
  1060. for run in BC6_LAYOUT[usize::from(mode)] {
  1061. if run.ch == 3 {
  1062. w.put(part.into(), 5);
  1063. } else {
  1064. w.put(
  1065. field(run.ep.into(), run.ch.into()) >> run.first,
  1066. run.len.into(),
  1067. );
  1068. }
  1069. }
  1070. let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 };
  1071. for (p, &v) in ix.ix.iter().enumerate() {
  1072. let short = p == 0 || p == usize::from(anchor);
  1073. let v = (v as u16).wrapping_add(1 << (bits - 1));
  1074. w.put(v.into(), u32::from(bits) - u32::from(short));
  1075. }
  1076. block.copy_from_slice(&w.v.to_le_bytes());
  1077. }
  1078. Ok(())
  1079. }
  1080. #[cfg(test)]
  1081. mod tests {
  1082. #[test]
  1083. fn the_shipped_tables_parse() {
  1084. assert!(super::Tables::builtin().is_ok());
  1085. }
  1086. use super::*;
  1087. /// Tables we made: uniform models, identity ranks, a BC7 code per mode,
  1088. /// empty dictionaries.
  1089. fn tables() -> Vec<u8> {
  1090. let mut t = Vec::new();
  1091. for m in 0..MODELS {
  1092. let g = m / 16;
  1093. for b in 0..BUCKETS {
  1094. let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 };
  1095. t.extend_from_slice(&f.to_le_bytes());
  1096. }
  1097. }
  1098. t.extend((0..=255u8).map(|v| v & 0x77)); // rank1 (unused by the tests beyond 2-bit fields)
  1099. t.extend(0..64u8); // rank3a
  1100. t.extend(0..=255u8); // rank3c
  1101. t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4)); // rank4: low 3 bits, next 3 bits
  1102. t.extend(0..64u8); // rank5
  1103. for code in 0..512u16 {
  1104. // Code c: mode 6 (one subset), the only one the tests use.
  1105. let ctrl: u16 = if code == 0 { 0x46 } else { 0 };
  1106. t.extend_from_slice(&ctrl.to_le_bytes());
  1107. }
  1108. t.resize(TABLES_SIZE, 0);
  1109. t
  1110. }
  1111. /// A lane's symbols as one fragment: uniform model, rANS from 2^24, no
  1112. /// reset, so the lane keeps 2^24 when it ends.
  1113. fn fragment(width: u8, symbols: &[u8]) -> Vec<u8> {
  1114. let f = 1u32 << (15 - width);
  1115. let mut x = LOW;
  1116. let mut bytes = Vec::new();
  1117. for &s in symbols.iter().rev() {
  1118. let (freq, start) = if s == 0 {
  1119. (f - 1, 1)
  1120. } else {
  1121. (f, u32::from(s) * f)
  1122. };
  1123. while x >= (freq << 16) {
  1124. bytes.push(x as u8);
  1125. x >>= 8;
  1126. }
  1127. x = ((x / freq) << 16) + x % freq + start;
  1128. }
  1129. bytes.extend_from_slice(&x.to_le_bytes());
  1130. bytes.reverse();
  1131. let mut out = vec![0];
  1132. if bytes.len() > 256 {
  1133. out[0] |= 0x20;
  1134. let n = bytes.len() - 257;
  1135. out.extend_from_slice(&[n as u8, (n >> 8) as u8]);
  1136. } else {
  1137. out.push((bytes.len() - 1) as u8);
  1138. }
  1139. out.extend(bytes);
  1140. out
  1141. }
  1142. /// Interleaves per-lane fragments the way the decoder takes bytes. A lane
  1143. /// that has finished still asks: a filler fragment (two payload bytes)
  1144. /// brings its state to 2^24 with a byte latched, which parks it for good.
  1145. fn stream(t: &Tables, widths: &[u8], per: usize, records: &[Vec<u8>]) -> Vec<u8> {
  1146. let stride = widths.len() * per;
  1147. let mut queues: Vec<std::collections::VecDeque<u8>> = (0..widths.len())
  1148. .map(|j| {
  1149. let syms: Vec<u8> = records
  1150. .iter()
  1151. .flat_map(|r| r[j * per..j * per + per].to_vec())
  1152. .collect();
  1153. let mut bytes = fragment(widths[j], &syms);
  1154. bytes.extend([0, 1, 0, 0]);
  1155. bytes.into()
  1156. })
  1157. .collect();
  1158. let mut out = Vec::new();
  1159. let mut check = vec![0; records.len() * stride];
  1160. let fetch = |j: usize| {
  1161. let b = queues[j]
  1162. .pop_front()
  1163. .expect("a parked lane asked for input");
  1164. out.push(b);
  1165. Some(b)
  1166. };
  1167. lanes(t, widths, per, records.len(), fetch, &mut check).unwrap();
  1168. assert_eq!(check, records.concat());
  1169. out
  1170. }
  1171. const BC4_LANES: [u8; 12] = [7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5];
  1172. fn zigzag(v: i32) -> u8 {
  1173. if v >= 0 {
  1174. (2 * v) as u8
  1175. } else {
  1176. (-2 * v - 1) as u8
  1177. }
  1178. }
  1179. #[test]
  1180. fn bc4_blocks_with_and_without_references() {
  1181. let t = Tables::parse(&tables()).unwrap();
  1182. // Block 0: endpoints 10, -3 (+128 stored), indices p -> p & 7.
  1183. let mut b0 = vec![0, 0, zigzag(10), zigzag(-3)];
  1184. b0.extend((0..8).map(|k| ((2 * k) & 7) | ((2 * k + 1) & 7) << 3));
  1185. // Block 1 refers to block 0 for both: residual endpoints +1, +1; indices +1.
  1186. let mut b1 = vec![0, 1, zigzag(1), zigzag(1)];
  1187. b1.extend((0..8).map(|_| 1 | 1 << 3));
  1188. let src = stream(&t, &BC4_LANES, 1, &[b0, b1]);
  1189. let mut dst = [0u8; 16];
  1190. decode(4, &src, &mut dst, &t).unwrap();
  1191. let block = |e0: u8, e1: u8, ix: &dyn Fn(usize) -> usize| {
  1192. let bits = (0..16).fold(0u64, |a, p| a | BC4_CODE[ix(p)] << (16 + 3 * p));
  1193. (u64::from(e0) | u64::from(e1) << 8 | bits).to_le_bytes()
  1194. };
  1195. assert_eq!(dst[..8], block(138, 125, &|p| p & 7));
  1196. assert_eq!(dst[8..], block(139, 126, &|p| (p + 1) & 7));
  1197. }
  1198. #[test]
  1199. fn lanes_take_bytes_in_schedule_order_and_long_fragments() {
  1200. let t = Tables::parse(&tables()).unwrap();
  1201. // Many blocks: long fragments (over 256 payload bytes) on the wide lanes.
  1202. let records: Vec<Vec<u8>> = (0..400u32)
  1203. .map(|i| {
  1204. let mut r = vec![0, 0, (i * 7) as u8, (i * 13) as u8];
  1205. r.extend((0..8).map(|k| ((i + k) * 5 % 64) as u8));
  1206. r
  1207. })
  1208. .collect();
  1209. let src = stream(&t, &BC4_LANES, 1, &records);
  1210. let mut got = vec![0u8; records.len() * 12];
  1211. let mut next = src.iter().copied();
  1212. lanes(&t, &BC4_LANES, 1, records.len(), |_| next.next(), &mut got).unwrap();
  1213. assert_eq!(got, records.concat());
  1214. }
  1215. #[test]
  1216. fn bc7_mode6_block() {
  1217. let t = Tables::parse(&tables()).unwrap();
  1218. // Control code 0 -> mode 6; endpoints R 8 bits (p-bit low), G B A 7 bits.
  1219. let mut s = vec![0u8; 32];
  1220. s[4] = zigzag(0x55); // R0 = 0x55: field 0x2a, p-bit 1
  1221. s[5] = zigzag(-1); // R1 = 0xff (8 bits)
  1222. s[6] = zigzag(3);
  1223. s[10] = zigzag(0x7f >> 1);
  1224. let src = stream(
  1225. &t,
  1226. &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4],
  1227. 2,
  1228. &[s],
  1229. );
  1230. let mut dst = [0u8; 16];
  1231. decode(7, &src, &mut dst, &t).unwrap();
  1232. let mut w = Bits::default();
  1233. w.put(1 << 6, 7);
  1234. for (v, n) in [
  1235. (0x2a, 7),
  1236. (0x7f, 7),
  1237. (3, 7),
  1238. (0, 7),
  1239. (0, 7),
  1240. (0, 7),
  1241. (0x3f, 7),
  1242. (0, 7),
  1243. ] {
  1244. w.put(v, n);
  1245. }
  1246. w.put(1, 1);
  1247. w.put(1, 1);
  1248. assert_eq!(dst, w.v.to_le_bytes());
  1249. }
  1250. #[test]
  1251. fn malformed_input_is_an_error() {
  1252. let t = Tables::parse(&tables()).unwrap();
  1253. let records: Vec<Vec<u8>> = (0..64u8)
  1254. .map(|i| vec![0, 0, i, i, 1, 2, 3, 4, 5, 6, 7, 8])
  1255. .collect();
  1256. let src = stream(&t, &BC4_LANES, 1, &records);
  1257. let mut dst = vec![0u8; 64 * 8];
  1258. decode(4, &src, &mut dst, &t).unwrap();
  1259. // Truncated.
  1260. assert!(decode(4, &src[..src.len() / 2], &mut dst, &t).is_err());
  1261. // Headers promising more payload than the stream holds. (Other corrupt
  1262. // headers decode to garbage: the format has no redundancy.)
  1263. let headers = [[0x30; 8], [0xff; 8]].concat();
  1264. assert!(decode(4, &headers, &mut dst[..8], &t).is_err());
  1265. assert!(decode(4, &[], &mut dst, &t).is_err());
  1266. // Destination not a whole number of blocks, empty, more blocks than coded.
  1267. assert!(decode(4, &src, &mut dst[..12], &t).is_err());
  1268. assert!(decode(4, &src, &mut [], &t).is_err());
  1269. assert!(decode(4, &src, &mut vec![0u8; 65 * 8], &t).is_err());
  1270. // Unsupported formats, bad tables.
  1271. assert!(decode(2, &src, &mut dst, &t).is_err());
  1272. assert!(Tables::parse(&[0; 16]).is_err());
  1273. let mut no_tiling = tables();
  1274. no_tiling[0] = 1;
  1275. assert!(Tables::parse(&no_tiling).is_err());
  1276. }
  1277. #[test]
  1278. fn noise_never_panics() {
  1279. let t = Tables::parse(&tables()).unwrap();
  1280. let mut seed = 0x2545_f491_4f6c_dd1du64;
  1281. for round in 0..300 {
  1282. let len = round * 7 % 900;
  1283. let src: Vec<u8> = (0..len)
  1284. .map(|_| {
  1285. seed ^= seed << 13;
  1286. seed ^= seed >> 7;
  1287. seed ^= seed << 17;
  1288. seed as u8
  1289. })
  1290. .collect();
  1291. for bc in [1, 3, 4, 5, 6, 7] {
  1292. let mut dst = vec![0u8; 16 * (1 + round % 40)];
  1293. let _ = decode(bc, &src, &mut dst, &t);
  1294. }
  1295. }
  1296. }
  1297. /// Compares with reference outputs made outside the repository:
  1298. /// `VICTORY_BCPACK_TABLES` (the table file) and `VICTORY_BCPACK_CASES`, a
  1299. /// directory of `<name>.bc<n>` packed chunks with `<name>.out` beside them.
  1300. #[test]
  1301. #[ignore = "needs the format tables and reference chunks"]
  1302. fn reference_chunks() {
  1303. let tables = std::env::var_os("VICTORY_BCPACK_TABLES").expect("VICTORY_BCPACK_TABLES");
  1304. let cases = std::env::var_os("VICTORY_BCPACK_CASES").expect("VICTORY_BCPACK_CASES");
  1305. let t = Tables::parse(&std::fs::read(tables).unwrap()).unwrap();
  1306. let mut n = 0;
  1307. for entry in std::fs::read_dir(cases).unwrap() {
  1308. let path = entry.unwrap().path();
  1309. let Some(bc) = path
  1310. .extension()
  1311. .and_then(|e| e.to_str()?.strip_prefix("bc")?.parse().ok())
  1312. else {
  1313. continue;
  1314. };
  1315. let want = std::fs::read(path.with_extension("out")).unwrap();
  1316. let mut got = vec![0u8; want.len()];
  1317. decode(bc, &std::fs::read(&path).unwrap(), &mut got, &t).unwrap();
  1318. assert!(got == want, "{}", path.display());
  1319. n += 1;
  1320. }
  1321. assert!(n > 0);
  1322. }
  1323. }