bcpack.rs 56 KB

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