Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

Thumbnail probe: DC-only JPEG decoding, parallel without restart markers

gelenmedyaf409ce0623a8
diff --git a/Cargo.lock b/Cargo.lock
index acef8c07..874e865c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6377,13 +6377,16 @@ dependencies = [
"dirs 6.0.0",
"embed-resource",
"env_logger",
+ "flate2",
"futures",
"gpui-kit",
"gpui-pre-windows",
"image",
"log",
"mail-parser",
+ "memchr",
"parking_lot",
+ "png 0.18.1",
"raw-window-handle",
"resvg 0.46.0",
"rf-archive",
diff --git a/crates/rf-app/Cargo.toml b/crates/rf-app/Cargo.toml
index 2c732449..1f1127dc 100644
--- a/crates/rf-app/Cargo.toml
+++ b/crates/rf-app/Cargo.toml
@@ -55,5 +55,10 @@ windows.workspace = true
unicode-bidi = "0.3"
unicode-segmentation = "1"
+[dev-dependencies]
+png = "0.18"
+flate2.workspace = true
+memchr = "2"
+
[build-dependencies]
embed-resource = "3"
diff --git a/crates/rf-app/examples/thumb_probe/dcjpeg.rs b/crates/rf-app/examples/thumb_probe/dcjpeg.rs
new file mode 100644
index 00000000..c337e3ed
--- /dev/null
+++ b/crates/rf-app/examples/thumb_probe/dcjpeg.rs
@@ -0,0 +1,676 @@
+// A JPEG's thumbnail from the average of each 8x8 block (its DC coefficient) alone: no inverse DCT, the AC coefficients
+// only skipped over. Baseline (SOF0/SOF1) Huffman files; the restart intervals (DRI), when the file has them, are decoded
+// on several threads, and those holding no row the thumbnail needs are not decoded at all.
+// Included by thumb_probe.rs.
+
+pub struct DcJpeg {
+ /// RGB at one pixel per 8x8 block of the largest sampling (the picture at 1/8 of its size, or 1/16 with 2x2 sampling)
+ pub rgb: Vec<u8>,
+ pub bw: usize,
+ pub bh: usize,
+ /// the thumbnail's size; each of its rows is taken from one block row (`sample_row`)
+ pub ow: usize,
+ pub oh: usize,
+ pub segments_total: usize,
+ pub segments_decoded: usize,
+}
+
+/// The block row output row `j` (of `oh`) is taken from.
+pub fn sample_row(j: usize, oh: usize, block_rows: usize) -> usize {
+ ((j * 2 + 1) * block_rows) / (oh * 2)
+}
+
+struct Huff {
+ lut: Vec<u16>,
+ /// for AC tables: what one code means for skipping, read from AC_BITS bits at once (see `ac_entry`)
+ aclut: Vec<u32>,
+ maxcode: [i32; 18],
+ valptr: [i32; 17],
+ mincode: [i32; 17],
+ vals: Vec<u8>,
+}
+
+const LUT_BITS: u32 = 9;
+const AC_BITS: u32 = 11;
+
+/// An AC skipping entry: bits 0-4 the bits to consume, 5-11 how far k moves (64: end of block), 12-16 extra bits still to
+/// skip after that, bit 31 set when the entry is valid (codes longer than AC_BITS have none and go the slow way).
+fn ac_entry(consume: u32, adv: u32, extra: u32) -> u32 {
+ (1 << 31) | consume | (adv << 5) | (extra << 12)
+}
+
+fn build(counts: &[u8], vals: &[u8]) -> Huff {
+ let mut h = Huff { lut: vec![0; 1 << LUT_BITS], aclut: vec![0; 1 << AC_BITS], maxcode: [-1; 18], valptr: [0; 17], mincode: [0; 17], vals: vals.to_vec() };
+ let mut code: i32 = 0;
+ let mut k: i32 = 0;
+ for len in 1..=16usize {
+ let n = counts[len - 1] as i32;
+ if n > 0 {
+ h.valptr[len] = k;
+ h.mincode[len] = code;
+ for i in 0..n {
+ let c = code + i;
+ if len as u32 <= AC_BITS {
+ let rs = vals[(k + i) as usize] as u32;
+ let (r, sz, l) = (rs >> 4, rs & 15, len as u32);
+ let e = if sz == 0 {
+ if r == 15 { ac_entry(l, 16, 0) } else { ac_entry(l, 64, 0) }
+ } else if l + sz <= AC_BITS {
+ ac_entry(l + sz, r + 1, 0)
+ } else {
+ ac_entry(l, r + 1, sz)
+ };
+ let shift = AC_BITS - l;
+ let base = (c as usize) << shift;
+ for j in 0..(1usize << shift) {
+ h.aclut[base + j] = e;
+ }
+ }
+ if len as u32 <= LUT_BITS {
+ let shift = LUT_BITS - len as u32;
+ let base = (c as usize) << shift;
+ for j in 0..(1usize << shift) {
+ h.lut[base + j] = ((len as u16) << 8) | vals[(k + i) as usize] as u16;
+ }
+ }
+ }
+ code += n;
+ k += n;
+ h.maxcode[len] = code - 1;
+ }
+ code <<= 1;
+ }
+ h.maxcode[17] = i32::MAX;
+ h
+}
+
+struct Bits<'a> {
+ d: &'a [u8],
+ pos: usize,
+ buf: u64,
+ n: u32,
+}
+
+impl<'a> Bits<'a> {
+ #[inline(always)]
+ fn fill(&mut self) {
+ if self.pos + 8 <= self.d.len() {
+ let w = u64::from_be_bytes(self.d[self.pos..self.pos + 8].try_into().unwrap());
+ let x = !w;
+ let has_ff = (x.wrapping_sub(0x0101_0101_0101_0101) & !x & 0x8080_8080_8080_8080) != 0;
+ if !has_ff {
+ let take = ((64 - self.n) / 8).min(7);
+ self.buf |= (w >> (64 - take * 8)) << (64 - take * 8 - self.n);
+ self.pos += take as usize;
+ self.n += take * 8;
+ return;
+ }
+ }
+ while self.n <= 56 {
+ let mut b = 0u8;
+ if self.pos < self.d.len() {
+ b = self.d[self.pos];
+ if b == 0xFF {
+ if self.d.get(self.pos + 1) == Some(&0) {
+ self.pos += 2;
+ } else {
+ b = 0; // a marker: zeros from here on
+ }
+ } else {
+ self.pos += 1;
+ }
+ }
+ self.buf |= (b as u64) << (56 - self.n);
+ self.n += 8;
+ }
+ }
+ #[inline(always)]
+ fn consume(&mut self, k: u32) {
+ self.buf <<= k;
+ self.n -= k;
+ }
+ #[inline(always)]
+ fn decode(&mut self, h: &Huff) -> u8 {
+ if self.n < 16 {
+ self.fill();
+ }
+ let e = h.lut[(self.buf >> (64 - LUT_BITS)) as usize];
+ if e != 0 {
+ self.consume((e >> 8) as u32);
+ return e as u8;
+ }
+ for len in (LUT_BITS as usize + 1)..=16 {
+ let code = (self.buf >> (64 - len)) as i32;
+ if code <= h.maxcode[len] {
+ self.consume(len as u32);
+ return h.vals[(h.valptr[len] + code - h.mincode[len]) as usize];
+ }
+ }
+ self.consume(16);
+ 0
+ }
+ #[inline(always)]
+ fn receive_extend(&mut self, s: u32) -> i32 {
+ if s == 0 {
+ return 0;
+ }
+ if self.n < s {
+ self.fill();
+ }
+ let v = (self.buf >> (64 - s)) as i32;
+ self.consume(s);
+ if v < (1 << (s - 1)) { v - (1 << s) + 1 } else { v }
+ }
+}
+
+struct Comp {
+ h: usize,
+ v: usize,
+ q: i32,
+ dc: usize,
+ ac: usize,
+}
+
+pub fn decode(bytes: &[u8], size: u32, threads: usize, skip_rows: bool) -> Option<DcJpeg> {
+ if !bytes.starts_with(&[0xFF, 0xD8]) {
+ return None;
+ }
+ let mut qt = [[0i32; 1]; 4];
+ let mut dc_tables: Vec<Option<Huff>> = (0..4).map(|_| None).collect();
+ let mut ac_tables: Vec<Option<Huff>> = (0..4).map(|_| None).collect();
+ let mut comps: Vec<(u8, Comp)> = Vec::new();
+ let (mut w, mut h) = (0usize, 0usize);
+ let mut dri = 0usize;
+ let mut i = 2;
+ let data_start;
+ loop {
+ if i + 4 > bytes.len() || bytes[i] != 0xFF {
+ return None;
+ }
+ let m = bytes[i + 1];
+ if m == 0xFF {
+ i += 1;
+ continue;
+ }
+ let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
+ let seg = bytes.get(i + 4..i + 2 + len)?;
+ match m {
+ 0xDB => {
+ let mut j = 0;
+ while j < seg.len() {
+ let (pq, tq) = (seg[j] >> 4, (seg[j] & 15) as usize);
+ let first = if pq == 0 { seg[j + 1] as i32 } else { u16::from_be_bytes([seg[j + 1], seg[j + 2]]) as i32 };
+ qt[tq & 3][0] = first;
+ j += 1 + if pq == 0 { 64 } else { 128 };
+ }
+ }
+ 0xC4 => {
+ let mut j = 0;
+ while j < seg.len() {
+ let (tc, th) = (seg[j] >> 4, (seg[j] & 15) as usize);
+ let counts = &seg[j + 1..j + 17];
+ let total: usize = counts.iter().map(|&c| c as usize).sum();
+ let vals = &seg[j + 17..j + 17 + total];
+ let t = build(counts, vals);
+ if tc == 0 { dc_tables[th & 3] = Some(t) } else { ac_tables[th & 3] = Some(t) }
+ j += 17 + total;
+ }
+ }
+ 0xC0 | 0xC1 => {
+ h = u16::from_be_bytes([seg[1], seg[2]]) as usize;
+ w = u16::from_be_bytes([seg[3], seg[4]]) as usize;
+ let n = seg[5] as usize;
+ for c in 0..n {
+ let b = &seg[6 + c * 3..9 + c * 3];
+ comps.push((b[0], Comp { h: (b[1] >> 4) as usize, v: (b[1] & 15) as usize, q: b[2] as i32, dc: 0, ac: 0 }));
+ }
+ }
+ 0xC2 | 0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF => return None, // progressive, lossless, arithmetic
+ 0xDD => dri = u16::from_be_bytes([seg[0], seg[1]]) as usize,
+ 0xDA => {
+ let n = seg[0] as usize;
+ if n != comps.len() {
+ return None; // not one interleaved scan
+ }
+ for c in 0..n {
+ let (id, t) = (seg[1 + c * 2], seg[2 + c * 2]);
+ let comp = comps.iter_mut().find(|(cid, _)| *cid == id)?;
+ comp.1.dc = (t >> 4) as usize & 3;
+ comp.1.ac = (t & 15) as usize & 3;
+ }
+ data_start = i + 2 + len;
+ break;
+ }
+ _ => {}
+ }
+ i += 2 + len;
+ }
+ if w == 0 || h == 0 || !(comps.len() == 1 || comps.len() == 3) {
+ return None;
+ }
+ let mut comps: Vec<Comp> = comps.into_iter().map(|(_, c)| c).collect();
+ if comps.len() == 1 {
+ comps[0].h = 1;
+ comps[0].v = 1;
+ }
+ for c in comps.iter_mut() {
+ c.q = qt[(c.q as usize) & 3][0];
+ }
+ let hmax = comps.iter().map(|c| c.h).max()?;
+ let vmax = comps.iter().map(|c| c.v).max()?;
+ let (mcux, mcuy) = (w.div_ceil(8 * hmax), h.div_ceil(8 * vmax));
+ let total = mcux * mcuy;
+ let per_mcu: usize = comps.iter().map(|c| c.h * c.v).sum();
+ for c in &comps {
+ dc_tables[c.dc].as_ref()?;
+ ac_tables[c.ac].as_ref()?;
+ }
+
+ let t_scan = std::time::Instant::now();
+ // the restart intervals: where each begins in the entropy-coded data
+ let data = &bytes[data_start..];
+ let mut starts = vec![0usize];
+ if dri > 0 {
+ let mut j = 0;
+ while let Some(k) = memchr::memchr(0xFF, &data[j..]) {
+ let at = j + k;
+ match data.get(at + 1) {
+ Some(&(0xD0..=0xD7)) => {
+ starts.push(at + 2);
+ j = at + 2;
+ }
+ Some(&0) | Some(&0xFF) => j = at + 1,
+ _ => break,
+ }
+ }
+ }
+ let seg_mcus = if dri > 0 { dri } else { total };
+ let nseg = if dri > 0 { total.div_ceil(dri) } else { 1 };
+ if starts.len() < nseg {
+ return None;
+ }
+
+ // which intervals hold a row the thumbnail needs (one block row per output row)
+ let (bw0, bh0) = (mcux * hmax, mcuy * vmax);
+ let long = bw0.max(bh0);
+ let (ow, oh) = ((bw0 * size as usize / long).clamp(1, bw0), (bh0 * size as usize / long).clamp(1, bh0));
+ let out_rows = oh;
+ let mut need = vec![!skip_rows; nseg];
+ // block rows wanted: `out_rows` of them, spread evenly; an MCU row holds `vmax` block rows
+ let mut wanted_mcu_rows = vec![false; mcuy];
+ let block_rows = mcuy * vmax;
+ for j in 0..out_rows {
+ wanted_mcu_rows[sample_row(j, out_rows, block_rows) / vmax] = true;
+ }
+ if skip_rows {
+ for (s, n) in need.iter_mut().enumerate() {
+ let (a, b) = (s * seg_mcus, ((s + 1) * seg_mcus).min(total));
+ *n = (a / mcux..=(b - 1) / mcux).any(|r| wanted_mcu_rows[r]);
+ }
+ }
+ let decoded = need.iter().filter(|&&n| n).count();
+
+ let scan_ms = t_scan.elapsed().as_secs_f64() * 1000.0;
+ let t_dec = std::time::Instant::now();
+ let dcs: Vec<&Huff> = comps.iter().map(|c| dc_tables[c.dc].as_ref().unwrap()).collect();
+ let acs: Vec<&Huff> = comps.iter().map(|c| ac_tables[c.ac].as_ref().unwrap()).collect();
+ let slot_comp: Vec<usize> = comps.iter().enumerate().flat_map(|(ci, c)| std::iter::repeat_n(ci, c.h * c.v)).collect();
+ let speculative = dri == 0 && threads > 1;
+ let mut out = if speculative { spec::decode(data, &slot_comp, &dcs, &acs, total * per_mcu, threads)? } else { vec![0i16; total * per_mcu] };
+ let decode_seg = |s: usize, dst: &mut [i16]| {
+ let end = if s + 1 < starts.len() { starts[s + 1] } else { data.len() };
+ let mut b = Bits { d: &data[starts[s]..end], pos: 0, buf: 0, n: 0 };
+ let mut pred = [0i32; 4];
+ let mcus = dst.len() / per_mcu;
+ let mut o = 0;
+ for _ in 0..mcus {
+ for (ci, c) in comps.iter().enumerate() {
+ for _ in 0..c.h * c.v {
+ let s = b.decode(dcs[ci]) as u32;
+ pred[ci] += b.receive_extend(s);
+ dst[o] = pred[ci] as i16;
+ o += 1;
+ let mut k = 1;
+ let ac = acs[ci];
+ while k < 64 {
+ if b.n < 16 {
+ b.fill();
+ }
+ let e = ac.aclut[(b.buf >> (64 - AC_BITS)) as usize];
+ if e != 0 {
+ b.consume(e & 31);
+ let adv = (e >> 5) & 127;
+ if adv == 64 {
+ break;
+ }
+ let extra = (e >> 12) & 31;
+ if extra != 0 {
+ if b.n < extra {
+ b.fill();
+ }
+ b.consume(extra);
+ }
+ k += adv as usize;
+ continue;
+ }
+ let rs = b.decode(ac);
+ let (r, sz) = ((rs >> 4) as usize, (rs & 15) as u32);
+ if sz == 0 {
+ if r == 15 {
+ k += 16;
+ continue;
+ }
+ break;
+ }
+ k += r;
+ if b.n < sz {
+ b.fill();
+ }
+ b.consume(sz);
+ k += 1;
+ }
+ }
+ }
+ }
+ };
+ if !speculative {
+ let mut chunks: Vec<(usize, &mut [i16])> = out.chunks_mut(seg_mcus * per_mcu).enumerate().filter(|(s, _)| need[*s]).collect();
+ let threads = threads.max(1).min(chunks.len().max(1));
+ if threads == 1 {
+ for (s, dst) in chunks.iter_mut() {
+ decode_seg(*s, dst);
+ }
+ } else {
+ let per = chunks.len().div_ceil(threads);
+ std::thread::scope(|sc| {
+ for group in chunks.chunks_mut(per) {
+ let decode_seg = &decode_seg;
+ sc.spawn(move || {
+ for (s, dst) in group.iter_mut() {
+ decode_seg(*s, dst);
+ }
+ });
+ }
+ });
+ }
+ }
+
+ if std::env::var("PROBE_PHASES").is_ok() {
+ eprintln!(" scan {scan_ms:.1} ms, decode {:.1} ms ({threads} threads, {decoded}/{nseg} intervals)", t_dec.elapsed().as_secs_f64() * 1000.0);
+ }
+ // blocks to an RGB picture at block resolution of the largest sampling
+ let (bw, bh) = (mcux * hmax, mcuy * vmax);
+ let mut rgb = vec![0u8; bw * bh * 3];
+ let avg = |v: i32, q: i32| (v * q) as f32 / 8.0 + 128.0;
+ for my in 0..mcuy {
+ if !wanted_mcu_rows[my] {
+ continue;
+ }
+ for mx in 0..mcux {
+ let m = my * mcux + mx;
+ let base = m * per_mcu;
+ let mut off = 0;
+ let mut planes: [&[i16]; 3] = [&[], &[], &[]];
+ for (ci, c) in comps.iter().enumerate() {
+ planes[ci] = &out[base + off..base + off + c.h * c.v];
+ off += c.h * c.v;
+ }
+ for by in 0..vmax {
+ for bx in 0..hmax {
+ let px = (my * vmax + by) * bw + mx * hmax + bx;
+ let pick = |ci: usize| {
+ let c = &comps[ci];
+ let (cx, cy) = (bx * c.h / hmax, by * c.v / vmax);
+ avg(planes[ci][cy * c.h + cx] as i32, c.q)
+ };
+ let (r, g, b) = if comps.len() == 1 {
+ let y = pick(0);
+ (y, y, y)
+ } else {
+ let (y, cb, cr) = (pick(0), pick(1) - 128.0, pick(2) - 128.0);
+ (y + 1.402 * cr, y - 0.344136 * cb - 0.714136 * cr, y + 1.772 * cb)
+ };
+ rgb[px * 3] = r.clamp(0.0, 255.0) as u8;
+ rgb[px * 3 + 1] = g.clamp(0.0, 255.0) as u8;
+ rgb[px * 3 + 2] = b.clamp(0.0, 255.0) as u8;
+ }
+ }
+ }
+ }
+ Some(DcJpeg { rgb, bw, bh, ow, oh, segments_total: nseg, segments_decoded: decoded })
+}
+
+/// Decoding one restart-less scan on several threads at once.
+///
+/// The entropy-coded data is cut into equal pieces; every thread but the first starts at its piece's first byte and
+/// GUESSES that a block begins there. Huffman codes resynchronise quickly: a wrong start decodes garbage for a short
+/// while and then falls into step with the true block boundaries. Each thread notes where every block it decoded began
+/// (bit position, and which block of the MCU it took it for). Then each thread goes on past its piece's end, decoding
+/// correctly (by induction from the first thread, which started right), until it reaches a block start that the next
+/// thread also noted, with the same block-of-MCU: from there on the next thread's work is right, and the pieces are
+/// joined there. The DC values are kept as differences and summed up at the end, once the order is known.
+mod spec {
+ use super::{AC_BITS, Huff, LUT_BITS};
+
+ const PAD: usize = 512;
+
+ #[derive(Clone, Copy)]
+ struct Rec {
+ bit: u64,
+ slot: u8,
+ diff: i16,
+ }
+
+ /// The data with the stuffed zero bytes (0xFF 0x00) taken out, up to the first marker, and PAD zero bytes after it (more
+ /// than one block can read past its start).
+ fn unstuff(data: &[u8]) -> Vec<u8> {
+ let mut out = Vec::with_capacity(data.len() + 16);
+ let mut j = 0;
+ while let Some(k) = memchr::memchr(0xFF, &data[j..]) {
+ out.extend_from_slice(&data[j..j + k + 1]);
+ match data.get(j + k + 1) {
+ Some(0) => j = j + k + 2,
+ _ => {
+ out.pop();
+ break;
+ }
+ }
+ }
+ if memchr::memchr(0xFF, &data[j..]).is_none() {
+ out.extend_from_slice(&data[j..]);
+ }
+ out.extend_from_slice(&[0; PAD]);
+ out
+ }
+
+ struct Reader<'a> {
+ d: &'a [u8],
+ bit: u64,
+ }
+
+ impl Reader<'_> {
+ #[inline(always)]
+ fn peek(&self) -> u64 {
+ let b = (self.bit >> 3) as usize;
+ let w = u64::from_be_bytes(self.d[b..b + 8].try_into().unwrap());
+ w << (self.bit & 7)
+ }
+ #[inline(always)]
+ fn sym(&mut self, h: &Huff) -> u8 {
+ let p = self.peek();
+ let e = h.lut[(p >> (64 - LUT_BITS)) as usize];
+ if e != 0 {
+ self.bit += (e >> 8) as u64;
+ return e as u8;
+ }
+ for len in (LUT_BITS as usize + 1)..=16 {
+ let code = (p >> (64 - len)) as i32;
+ if code <= h.maxcode[len] {
+ self.bit += len as u64;
+ return h.vals[(h.valptr[len] + code - h.mincode[len]) as usize];
+ }
+ }
+ self.bit += 16;
+ 0
+ }
+ /// One block: its DC difference, its AC coefficients skipped.
+ #[inline(always)]
+ fn block(&mut self, dc: &Huff, ac: &Huff) -> i16 {
+ let s = self.sym(dc) as u32 & 15;
+ let diff = if s == 0 {
+ 0
+ } else {
+ let v = (self.peek() >> (64 - s)) as i32;
+ self.bit += s as u64;
+ if v < (1 << (s - 1)) { v - (1 << s) + 1 } else { v }
+ };
+ let mut k = 1;
+ while k < 64 {
+ let p = self.peek();
+ let e = ac.aclut[(p >> (64 - AC_BITS)) as usize];
+ if e != 0 {
+ self.bit += (e & 31) as u64 + ((e >> 12) & 31) as u64;
+ let adv = (e >> 5) & 127;
+ if adv == 64 {
+ break;
+ }
+ k += adv as usize;
+ continue;
+ }
+ let rs = self.sym(ac);
+ let (r, sz) = ((rs >> 4) as usize, (rs & 15) as u64);
+ if sz == 0 {
+ if r == 15 {
+ k += 16;
+ continue;
+ }
+ break;
+ }
+ self.bit += sz;
+ k += r + 1;
+ }
+ diff as i16
+ }
+ }
+
+ pub fn decode(data: &[u8], slot_comp: &[usize], dcs: &[&Huff], acs: &[&Huff], blocks: usize, threads: usize) -> Option<Vec<i16>> {
+ let t0 = std::time::Instant::now();
+ let d = unstuff(data);
+ let bits = ((d.len() - PAD) * 8) as u64;
+ let unstuff_ms = t0.elapsed().as_secs_f64() * 1000.0;
+ let per_mcu = slot_comp.len();
+ let t = threads.max(1);
+ let piece = bits.div_ceil(t as u64).div_ceil(8) * 8;
+ let start = |i: usize| (i as u64 * piece).min(bits);
+
+ // pass 1: each thread its own piece, from a guessed block start
+ let t1 = std::time::Instant::now();
+ let mut own: Vec<(Vec<Rec>, u64, usize)> = Vec::new();
+ std::thread::scope(|sc| {
+ let hs: Vec<_> = (0..t)
+ .map(|i| {
+ let d = &d;
+ sc.spawn(move || {
+ let (from, to) = (start(i), start(i + 1));
+ let mut r = Reader { d, bit: from };
+ let mut slot = 0usize;
+ let mut recs = Vec::with_capacity(((to - from) / 40) as usize);
+ while r.bit < to {
+ let at = r.bit;
+ let ci = slot_comp[slot];
+ let diff = r.block(dcs[ci], acs[ci]);
+ recs.push(Rec { bit: at, slot: slot as u8, diff });
+ slot = (slot + 1) % per_mcu;
+ }
+ (recs, r.bit, slot)
+ })
+ })
+ .collect();
+ own = hs.into_iter().map(|h| h.join().unwrap()).collect();
+ });
+ let pass1_ms = t1.elapsed().as_secs_f64() * 1000.0;
+
+ // pass 2: each thread carries on until it meets a block start a later thread noted (same position, same slot)
+ let t2 = std::time::Instant::now();
+ let mut joins: Vec<(Vec<Rec>, Option<(usize, usize)>)> = Vec::new();
+ std::thread::scope(|sc| {
+ let hs: Vec<_> = (0..t)
+ .map(|i| {
+ let (d, own) = (&d, &own);
+ sc.spawn(move || {
+ let (_, end, end_slot) = &own[i];
+ let mut r = Reader { d, bit: *end };
+ let mut slot = *end_slot;
+ let mut ext = Vec::new();
+ let (mut k, mut j) = (i + 1, 0usize);
+ loop {
+ while k < t {
+ let recs = &own[k].0;
+ while j < recs.len() && recs[j].bit < r.bit {
+ j += 1;
+ }
+ if j < recs.len() {
+ break;
+ }
+ k += 1;
+ j = 0;
+ }
+ if k < t {
+ let rec = own[k].0[j];
+ if rec.bit == r.bit && rec.slot as usize == slot {
+ return (ext, Some((k, j)));
+ }
+ }
+ if r.bit >= bits {
+ return (ext, None);
+ }
+ let at = r.bit;
+ let ci = slot_comp[slot];
+ let diff = r.block(dcs[ci], acs[ci]);
+ ext.push(Rec { bit: at, slot: slot as u8, diff });
+ slot = (slot + 1) % per_mcu;
+ }
+ })
+ })
+ .collect();
+ joins = hs.into_iter().map(|h| h.join().unwrap()).collect();
+ });
+ let pass2_ms = t2.elapsed().as_secs_f64() * 1000.0;
+
+ // the chain: thread 0's blocks and its carry-on, then from where it joined the next, and so on
+ let mut out = Vec::with_capacity(blocks);
+ let mut pred = [0i32; 4];
+ let (mut i, mut from) = (0usize, 0usize);
+ let mut hops = 0;
+ let mut ext_total = 0usize;
+ loop {
+ for rec in own[i].0[from..].iter().chain(joins[i].0.iter()) {
+ if out.len() == blocks {
+ break;
+ }
+ let slot = out.len() % per_mcu;
+ if rec.slot as usize != slot {
+ return None;
+ }
+ let ci = slot_comp[slot];
+ pred[ci] += rec.diff as i32;
+ out.push(pred[ci] as i16);
+ }
+ ext_total += joins[i].0.len();
+ match joins[i].1 {
+ Some((k, j)) if out.len() < blocks => {
+ i = k;
+ from = j;
+ hops += 1;
+ }
+ _ => break,
+ }
+ }
+ if std::env::var("PROBE_PHASES").is_ok() {
+ eprintln!(
+ " speculative: unstuff {unstuff_ms:.1} ms, pass 1 {pass1_ms:.1} ms, pass 2 {pass2_ms:.1} ms, {hops} joins, {ext_total} blocks decoded twice of {blocks}"
+ );
+ }
+ (out.len() == blocks).then_some(out)
+ }
+}
diff --git a/crates/rf-app/examples/thumb_probe.rs b/crates/rf-app/examples/thumb_probe/main.rs
similarity index 58%
rename from crates/rf-app/examples/thumb_probe.rs
rename to crates/rf-app/examples/thumb_probe/main.rs
index 9763c615..cce2b6de 100644
Binary files a/crates/rf-app/examples/thumb_probe.rs and b/crates/rf-app/examples/thumb_probe/main.rs differ