bcpack.rs 55 KB

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