Author SHA1 Message Date
Muse a34cd7dcaf exp: gitignore the diag binaries 2026-12-02 10:50:26 +00:00
Muse 3dce1f4e59 exp: final README — pass-2 verdict (0/875), speeds, cross-corpus, totals
- Pass 2: 35 rows x 25 trials = 875, rescued 0. Repo's own test
  agrees (t+1 0/100, t+2 0/100).
- Isolated speed table (sequential): interleave costs nothing
  measurable; LDPC dec 0.91 MB/s; polar dec 0.58 MB/s.
- Cross-corpus (bin.lz, rand.lz) reproduces text.lz exactly.
- Test totals: 51,875 matrix trials + diagnostics.
- hot_chicago verification BLOCKED (tunnel down 4 attempts);
  snapshot zips staged on old VPS for a later retry.
2026-12-02 10:48:16 +00:00
Muse f87c7e3007 exp: fix Makefile mangled by a sed (ldpc_diag/pass2_diag recipes)
The previous commit's sed ate the $(CC)/$(CFLAGS) variables and
moved the ldpc_diag recipe under pass2_diag. Rewrote the Makefile
cleanly; all four binaries build.
2026-12-02 10:42:41 +00:00
Muse f07a2ba488 exp: results write-up + pass-2 diagnostic (pass 2 rescues nothing)
README now carries the measured tables for all four families.
pass2_diag.c: targeted sweep of BCH pass-2 recovery. Finding: the
repo's own bch_test reports t+1 recovered 0/100, t+2 0/100; this
harness's pass-2 matrix shows rescued=0 in every setting; the
targeted sweep (m=13 t=16, k=t+1..t+8) rescues 0/50 at every k.
Pass 2's demonstrated value is the loud-failure guarantee (0
silent miscorrections), not recovery -- its residual-BM mechanism
addresses pass-1 miscorrection, which essentially never happens
for random errors. Relevant to the sibling deep-repair job.
2026-12-02 10:42:20 +00:00
Muse 4b6d4cfa45 exp: interleave groups merge the short tail (no weak tail group)
A burst landing in the final partial group (4 blocks of a 68-block
blob) hit each of its blocks with L/4 bytes instead of L/64 -- that
is why 64 B bursts measured 0.94 instead of 1.00. Groups are now
formed so the last partial group is absorbed into the previous one
(every group >= depth). Re-measured, 50 trials: d16/d32/d64-t32 at
64 B bursts 1.00 (was 0.94); d64-t32 at 256 B and 64x4 bursts 1.00
(was 0.95 / 0.83).
2026-12-02 10:35:24 +00:00
Muse 5d3ee79fd3 exp: unequal error protection over small-block BCH (family 4)
Prefix (first C bytes: lzip header + stream start) at t_hi, rest at
t_lo. Fixed a real bug en route: the stored-length helper hardcoded
the t=32 block size (971 B); block size depends on t (1010 B at
t=8), which broke decode for every tier but t=32. uep_diag reports
prefix survival separately: at BER 1e-3, uep-c1024-h32-l8 has
whole=0.00 but prefix=1.00 -- the graceful-degradation claim is
real, but it only helps if lzply gains a salvage mode (today the
entry SHA gates all-or-nothing extraction). Pass 2 not wired: the
oracle is the whole-blob SHA.
2026-12-02 10:31:39 +00:00
Muse 22436a7990 exp: polar code, SC decoding (family 3)
N=4096, BEC-Bhattacharyya construction, min-sum SC. Fixed a real
bug en route: the SC partial sums overwrote the leaf decisions, so
clean round-trips failed (bits[] and psum[] are now separate).
Key finding: the design point matters enormously. Designing for
p=1e-2 gives 0.00 recovery at BER 1e-4; designing for p=1e-3/1e-4
gives 0.90/0.95. Codec names select the design point
(polar-r90-d3 = design 1e-3, default d2 = 1e-2). Even the best
variant collapses at BER 1e-3 -- SC at N=4096/R=0.9 is weak there;
full matrix will decide whether polar is a reject.
2026-12-02 10:29:52 +00:00
Muse 5d4f17a57e exp: regular LDPC codec, PEG construction + min-sum BP (family 2)
n=8192, column weight 3; r90 (m=768, rate 0.906) and r95 (m=384,
rate 0.953). PEG construction (the greedy 4-cycle-rejection builder
deadlocked in the endgame -- replaced, see comment). Systematic
encoding via Gauss-Jordan; normalized min-sum (0.8), 50 iters.
Single-block diagnostics (ldpc_diag): r90 clean to 37 errors/block,
first failures ~38-40; r95 starts failing at 6 errors/block -- the
high-rate regular (3,64) code is genuinely weak, an honest negative
for naive regular LDPC at rate 0.95. Clean round-trips bit-identical.
2026-12-02 10:20:02 +00:00
Muse 50b3b3a80f exp: byte interleaver over small-block BCH (family 1)
Zero extra parity: groups of D blocks are read column-wise, so a
burst of L bytes hits any one block with at most ceil(L/D) bytes
instead of killing a block outright. Random-error performance is
unchanged by construction (same BCH underneath); burst tolerance
improves ~Dx. Smoke test on text.lz: d64-t32 survives 256 B bursts
at 0.95 (plain bch1k-t32: 0.00), clean round-trips bit-identical,
overhead identical to bch1k-t32 (5.40%).
2026-12-02 10:14:32 +00:00
Muse 1f959bb211 exp: corruption-matrix harness + BCH baseline codecs
bench.c measures every ECC family the same way: encode a blob window,
corrupt the stored bytes (random bit flips at a BER, or randomized
byte bursts), decode, check exact recovery (memcmp + SHA-256).
bch_wrap.c wraps the shipped BCH two ways: as-shipped (auto-pick poly
for the whole blob) and forced 1 KiB blocks. Pass 2 is wired to
recover_verified; --nopass2 skips it for matrix speed.
Stubs for interleave/ldpc/polar/uep return NULL until implemented.
Corpora + results are generated, gitignored.
2026-12-02 10:12:50 +00:00
45 changed files with 2487 additions and 2184 deletions

No files matched your search

-8
View File
@@ -14,11 +14,3 @@
/testdata/
/testwork/
/testwork-hyper/
# compression experiments (branch experiments/comp)
/experiments/corpora/
/experiments/rans_tool
/experiments/lzrans
/experiments/bwt
/experiments/ppm
/experiments/dict
/experiments/bchcheck
+7
View File
@@ -0,0 +1,7 @@
bench
ldpc_diag
pass2_diag
uep_diag
*.o
corpora/
results/
+29
View File
@@ -0,0 +1,29 @@
# exp/Makefile - build the ECC experiments harness (bench).
# Links the real lzply BCH + SHA-256 from the repo root.
CC ?= gcc
CFLAGS ?= -O2 -Wall -Wextra -march=native
CPPFLAGS ?= -I. -I..
SRCS = bench.c bch_wrap.c interleave.c ldpc.c polar.c uep.c \
../bch.c ../sha256.c
OBJS = $(SRCS:.c=.o)
bench: $(OBJS)
$(CC) $(CFLAGS) -o $@ $(OBJS) -lm
ldpc_diag: ldpc_diag.c ldpc.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ ldpc_diag.c ldpc.c -lm
pass2_diag: pass2_diag.c ../bch.c ../sha256.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ pass2_diag.c ../bch.c ../sha256.c -lm
uep_diag: uep_diag.c uep.c bch_wrap.c ../bch.c ../sha256.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ uep_diag.c uep.c bch_wrap.c ../bch.c ../sha256.c -lm
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
clean:
rm -f bench ldpc_diag pass2_diag uep_diag $(OBJS)
.PHONY: clean
+201
View File
@@ -0,0 +1,201 @@
# lzply ECC experiments (branch `experiments/ecc`)
Open-ended error-correction research on top of lzply's BCH baseline.
Each family implements `ecc_iface.h` (whole-blob encode/decode) and is
measured by `bench.c` on the same corpora, same corruption matrix, same
success criterion (exact recovery, memcmp + SHA-256).
## How to run
```
./bench --codec bch-t32 --blob corpora/text.lz --size 65536 \
--trials 200 --ber 1e-3 --nopass2 --out results/x.csv
./bench --codec ldpc-r90 --blob corpora/text.lz --burst 256,1 --trials 200
./bench --codec bch-t32 --blob corpora/text.lz --speed
./ldpc_diag r90 40 50 # single-block error-count sweep
./uep_diag uep-c1024-h32-l8 corpora/text.lz 65536 50 --ber 1e-3
```
Modes: `--ber X` (independent bit flips), `--burst LEN,COUNT`
(COUNT randomized-byte bursts of LEN bytes), `--clean`, `--speed`.
`--nopass2` skips the (slow) second-chance recovery hook so the matrix
stays fast; `run_pass2.sh` measures rescue rates separately.
`run_matrix.sh <corpus> <size> <trials> <out.csv> <codec...>` runs the
full matrix (5 BERs + 5 burst settings + clean), parallel over cores.
Corpora (`mkcorpora.sh`, generated, not committed): `text.lz` /
`bin.lz` / `rand.lz` — lzip -9 of 4 MiB text, binaries, seeded random
bytes (the compressed blob is what lzply protects); `*.raw` — the
stored-entry case. Default window is 64 KiB.
## Families
| codec | what it is |
|---|---|
| `bch-t{2,4,8,16,32}` | Baseline: BCH exactly as lzply ships it (auto-pick poly for the whole blob; pass 2 via `recover_verified`). |
| `bch1k-t{8,16,32}` | Same BCH, forced m=13 blocks (971 data bytes/block) — the "spend real redundancy" point. |
| `intlv-d{D}-bch1k-t{T}` | Byte interleaver (depth D) over bch1k-t{T}. Zero extra parity; bursts spread across blocks. Groups merge the short tail (see below). |
| `ldpc-r{90,95}` | Regular LDPC, PEG construction, min-sum belief propagation. |
| `polar-r{90,95}[-d{2,3,4}]` | Polar code, SC decoding. `-dN` is the design crossover 1e-N (default d2 = 1e-2). The design point matters enormously (see below). |
| `uep-c{C}-h{H}-l{L}` | Unequal error protection: first C bytes at BCH t=H, rest at t=L (small blocks). |
## Results (text.lz, 64 KiB windows, 200 trials/setting, hot_newyork)
Recovery rate = fraction of trials exactly recovered. Overhead is
measured (stored/data - 1). Pass-2 rescue rates are in
results/pass2-text.csv (separate, 25 trials/setting).
### Baseline: what lzply ships is nearly unprotected
| codec | ovh | BER 1e-5 | 1e-4 | 1e-3 | 3e-3 | 1e-2 | burst 256 B |
|---|---|---|---|---|---|---|---|
| bch-t2 | 0.01% | 0.11 | 0 | 0 | 0 | 0 | 0 |
| bch-t8 | 0.03% | 0.88 | 0 | 0 | 0 | 0 | 0 |
| bch-t16 | 0.06% | 1.00 | 0 | 0 | 0 | 0 | 0 |
| bch-t32 | 0.12% | 1.00 | 0.01 | 0 | 0 | 0 | 0 |
One 64 KiB blob is a single BCH block (m=20, 80 parity bytes), so
t=32 corrects 32 bit errors per 64 KiB. At BER 1e-4 the blob already
carries ~52 errors: the cliff is between 1e-5 and 1e-4.
Pass 2 (hash-gated candidates) rescues nothing in practice:
the repo's own bch_test reports t+1 recovered 0/100 and t+2
recovered 0/100; this harness's pass2 matrix (35 rows, 875 trials,
all BCH codecs) shows rescued=0 in every setting, and a targeted
sweep (pass2_diag, m=13 t=16, k=t+1..t+8) rescues 0/50 at every k. Its mechanism (residual-BM)
addresses pass-1 miscorrection, which essentially never happens
for random errors (pass 1 fails rather than miscorrecting), and
the flip-and-redecode fallback does not reach the true codeword.
Its demonstrated value is the loud-failure guarantee: 0 silent
miscorrections in 7813 checks. The matrix numbers above are
therefore the true lzply numbers with or without pass 2.
### Spending redundancy: small-block BCH
| codec | ovh | BER 1e-4 | 1e-3 | 3e-3 |
|---|---|---|---|---|
| bch1k-t8 | 1.29% | 1.00 | 0 | 0 |
| bch1k-t16 | 2.62% | 1.00 | 0.73 | 0 |
| bch1k-t32 | 5.40% | 1.00 | 1.00 | 0.01 |
Same code, 1 KiB blocks: t=32 buys survival to BER 1e-3 at 5.4%
overhead. Bursts still kill it (256 B burst: 0.00 at every t).
### Interleaving: zero-overhead burst protection (WINNER)
Byte interleave over bch1k-t32, 5.40% overhead (unchanged):
| codec | burst 16 B | 64 B | 256 B | 1024 B | 4x64 B |
|---|---|---|---|---|---|
| bch1k-t32 (no intlv) | 0 | 0 | 0 | 0 | 0 |
| intlv-d16-t32 | 1.00 | 1.00 | 0 | 0 | 0.10 |
| intlv-d32-t32 | 1.00 | 1.00 | 0 | 0 | 0.80 |
| intlv-d64-t32 | 1.00 | 1.00 | 1.00 | 0 | 1.00 |
Random-error performance is unchanged by construction (same BCH
underneath). Even at 1.29% overhead, intlv-d64-bch1k-t8 survives
64 B bursts at 1.00. Gotcha fixed en route: a short tail group
(4 blocks of 68) was the weak point and measured 0.94 on 64 B
bursts; groups now merge the tail.
### LDPC: the random-error winner (WINNER at ~11% overhead)
| codec | ovh | BER 1e-3 | 3e-3 | 1e-2 | burst 16 B |
|---|---|---|---|---|---|
| ldpc-r90 | 10.94% | 1.00 | 0.97 | 0 | 0.24 |
| ldpc-r95 | 6.25% | 0.32 | 0 | 0 | 0 |
At BER 3e-3, ldpc-r90 recovers 0.97 where bch1k-t32 recovers 0.01
— the iterative decoder's cliff sits a decade higher in BER. But
bursts kill it (a 16 B burst is ~64 errors in one 1 KiB block),
and r95 is weak: the regular (3,64) code starts failing at 6
errors/block (ldpc_diag). Irregular LDPC would be the follow-up;
LDPC+interleave would fix bursts.
### Polar SC: dominated, rejected (honest negative)
Designing for p=1e-2 gives 0.00 at BER 1e-4; designing for the
operating point (d3/d4) gives 0.90/0.95 at 1e-4 — but every variant
is 0.00 at BER 1e-3. SC at N=4096/R=0.9 is far weaker than
bch1k-t32 (1.00 at 1e-3, half the overhead) and ldpc-r90 (1.00 at
1e-3, same overhead). Two real bugs were fixed en route (SC partial
sums overwrote the leaf decisions; see polar.c). SCL list decoding
is the follow-up that could rescue polar; SC as measured is a reject.
### UEP: graceful degradation, conditional
Exact recovery is dominated by the weak tier (uep-c1024-h32-l8 at
1e-3: 0.00, same as uniform bch1k-t8). The prefix tells another
story (uep_diag, 50 trials):
| codec | BER 1e-3 whole | BER 1e-3 prefix | burst 256 B prefix |
|---|---|---|---|
| uep-c1024-h32-l8 | 0.00 | 1.00 | 1.00 |
| uep-c4096-h32-l8 | 0.00 | 1.00 | 0.94 |
The first 1-4 KiB (lzip header + stream start) survives when the
file is lost. Only useful if lzply gains a salvage mode; today the
entry SHA gates all-or-nothing extraction.
## Speed and memory (isolated, sequential, 64 KiB blob, clean)
`--speed` mode, 5 reps each. RSS is the bench process peak (harness
+ buffers ~6.5 MB); the codec delta is what matters.
| codec | enc MB/s | dec MB/s | RSS KB | ovh |
|---|---|---|---|---|
| bch-t32 | 6.46 | 3.44 | 6564 | 0.12% |
| bch1k-t8 | 9.98 | 5.87 | 6560 | 1.29% |
| bch1k-t16 | 5.39 | 3.14 | 6492 | 2.62% |
| bch1k-t32 | 2.97 | 1.55 | 6652 | 5.40% |
| intlv-d64-t32 | 3.39 | 1.73 | 6720 | 5.40% |
| intlv-d64-t8 | 11.11 | 5.80 | 6572 | 1.29% |
| ldpc-r90 | 3.34 | 0.91 | 7776 | 10.94% |
| ldpc-r95 | 5.18 | 1.16 | 7652 | 6.25% |
| polar-r90-d4 | 4.82 | 0.58 | 7252 | 11.72% |
| uep-c1024-h32-l8 | 9.96 | 4.80 | 6612 | 1.43% |
Interleaving costs nothing measurable (same speed and memory as
the BCH underneath; it is a permutation). LDPC pays a one-time
~1.8 s init (PEG + Gauss-Jordan) and decodes ~4x slower than
bch1k-t32; polar decodes slowest of all (0.58 MB/s). Failed BCH
decodes are far slower than clean ones (pass 2 dominates; matrix
rows for failed whole-blob blocks read 0.02-0.10 MB/s).
## Generalization
Cross-corpus check (bin.lz, rand.lz, 100 trials/setting, headline
codecs, BER 1e-4/1e-3 + 256 B burst + clean) reproduces text.lz
exactly for every codec and setting: bch1k-t32 1.00/1.00/0.00,
intlv-d64-t32 1.00/1.00/1.00, ldpc-r90 1.00/1.00/0.00,
polar-r90-d4 0.94/0.00/0.00, uep-c1024 1.00/0.00/0.00. Clean
round-trips are bit-identical everywhere (all clean rows 1.00).
## Test totals
- BCH matrix (text.lz): 143 rows x 200 trials = 28,600 trials
- LDPC matrix: 22 rows x 200 = 4,400
- Polar matrix: 33 rows x 200 = 6,600
- UEP matrix: 33 rows x 200 = 6,600
- Pass-2 matrix: 35 rows x 25 = 875 (rescued 0)
- Cross-corpus: 48 rows x 100 = 4,800
- Diagnostics: ldpc_diag single-block sweeps, uep_diag prefix
survival (50 trials/setting), pass2_diag targeted sweep
(t+1..t+8, 50 trials each)
- Total matrix trials: 51,875 (+ diagnostics)
- hot_chicago verification: BLOCKED — the old-VPS tunnel's SSH
leg to 104.225.223.162 failed 4 times over ~1.5 h (banner-exchange
timeout on the last attempt). Snapshot zips are staged on the
old VPS (/tmp/lzply-*.zip) for a retry when the tunnel recovers.
## Rules of this branch
- Never touch `main` or the other coordinator's branches/checkouts.
- No Reed-Solomon (the other job's territory).
- No legacy support; the format may change freely.
- Do not break the existing `-r` levels.
- Honest negatives count: a family that loses on every axis is killed
early and its numbers recorded.
- After every push: zip snapshot to /root/git-backups/lzply/ on both
servers (newest 7 kept); use /root/scripts/git-push-snapshot.sh
when present, else temp-clone + zip + copy manually.
+158
View File
@@ -0,0 +1,158 @@
/* bch_wrap.c - BCH baseline codecs for the experiments harness.
*
* Two operating points of the same code, so the harness can show the
* overhead/correction tradeoff honestly:
*
* bch-t<N> - exactly what lzply ships: bch_poly_for_data(blob, t)
* picks the smallest parent covering the WHOLE blob, so a
* 64 KiB blob is a single huge block (m=20, t=32 -> 80
* parity bytes, 0.12% overhead, 32 correctable bits per
* 64 KiB). Pass 2 (hash-gated candidates) is wired to
* recover_verified, matching entry_decode().
* bch1k-t<N> - same code, forced small blocks: pinned m=13 poly, so a
* block holds 971 data bytes (t=32 -> 5.4% overhead).
* This is the "what if we spent real redundancy" point.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ecc_iface.h"
#include "bch.h"
#include "bch_polys.h"
#include "sha256.h"
typedef struct {
int t;
const bch_poly_t *pinned; /* NULL = auto-pick (as-shipped) */
} bch_priv_t;
static const bch_poly_t *poly_by_mt(int m, int t)
{
for (int i = 0; i < BCH_NPOLYS; i++)
if (bch_polys[i].m == m && bch_polys[i].t == t)
return &bch_polys[i];
return NULL;
}
static size_t bch_encode_fn(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(len, p->t);
if (!poly)
return 0;
size_t slen = bch_encoded_len(len, poly);
uint8_t *buf = (uint8_t *)malloc(slen ? slen : 1);
if (!buf)
return 0;
if (bch_encode(data, len, poly, buf) != slen) {
free(buf);
return 0;
}
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
*out = buf;
return slen;
}
static int bch_decode_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(orig_len, p->t);
if (!poly)
return -1;
if (slen != bch_encoded_len(orig_len, poly))
return -1;
int corr = 0;
int rc = bch_decode(stored, slen, orig_len, poly, out, &corr);
if (corrected)
*corrected = rc == 0 ? corr : -1;
return rc;
}
static int bch_recover_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, const uint8_t want_sha[32],
uint8_t *out)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(orig_len, p->t);
if (!poly)
return -1;
if (slen != bch_encoded_len(orig_len, poly))
return -1;
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * orig_len);
if (!cands)
return -1;
int nc = bch_decode_candidates(stored, slen, orig_len, poly, cands,
BCH_PASS2_MAX_CANDS);
int found = -1;
for (int i = 0; i < nc && found < 0; i++) {
uint8_t h[32];
lzply_sha256(cands + (size_t)i * orig_len, orig_len, h);
if (memcmp(h, want_sha, 32) == 0)
found = i;
}
if (found >= 0)
memcpy(out, cands + (size_t)found * orig_len, orig_len);
free(cands);
return found >= 0 ? 0 : -1;
}
static void bch_destroy(ecc_codec_t *c)
{
free(c->priv);
free((void *)c->name);
free(c);
}
static ecc_codec_t *bch_new(int t, const bch_poly_t *pinned, const char *name)
{
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
bch_priv_t *p = (bch_priv_t *)calloc(1, sizeof(*p));
if (!c || !p) {
free(c);
free(p);
return NULL;
}
p->t = t;
p->pinned = pinned;
c->name = name;
c->desc = pinned ? "BCH, forced 1 KiB blocks" : "BCH as shipped in lzply";
c->block_data = pinned ? bch_max_data(pinned) : 0;
c->encode = bch_encode_fn;
c->decode = bch_decode_fn;
c->recover_verified = bch_recover_fn;
c->destroy = bch_destroy;
c->priv = p;
return c;
}
/* As-shipped: auto-pick poly for the whole blob. */
ecc_codec_t *bch_ship_new(int t)
{
char *name = (char *)malloc(32);
if (!name)
return NULL;
snprintf(name, 32, "bch-t%d", t);
return bch_new(t, NULL, name);
}
/* Forced small blocks: pinned m=13 poly (971 data bytes/block at any t). */
ecc_codec_t *bch_1k_new(int t)
{
const bch_poly_t *poly = poly_by_mt(13, t);
if (!poly)
return NULL;
char *name = (char *)malloc(32);
if (!name)
return NULL;
snprintf(name, 32, "bch1k-t%d", t);
return bch_new(t, poly, name);
}
+10
View File
@@ -0,0 +1,10 @@
/* bch_wrap.h - constructors for the BCH baseline codecs (bch_wrap.c). */
#ifndef EXP_BCH_WRAP_H
#define EXP_BCH_WRAP_H
#include "ecc_iface.h"
ecc_codec_t *bch_ship_new(int t);
ecc_codec_t *bch_1k_new(int t);
#endif /* EXP_BCH_WRAP_H */
+349
View File
@@ -0,0 +1,349 @@
/* bench.c - corruption-matrix harness for the lzply ECC experiments.
*
* One invocation = one codec x one corruption setting x N trials.
* Each trial: take a window of the corpus blob, encode it, corrupt the
* stored bytes (random bit flips at a BER, or randomized byte bursts),
* decode, and check exact recovery (memcmp + SHA-256). On decode
* failure, the codec's recover_verified hook (if any) gets one shot
* with the expected SHA -- that is how BCH pass 2 is credited.
*
* Usage:
* bench --codec NAME --blob FILE [--size N] [--trials N] [--seed S]
* (--ber X | --burst LEN,COUNT | --clean | --speed)
* [--out results.csv]
*
* CSV (appended to --out, or stdout if omitted):
* codec,corpus,blob_size,trials,mode,param,success,rescued,rate,
* enc_MBps,dec_MBps,peak_rss_kb,overhead_pct
*
* Exit 0 on a completed run (even if recovery is 0 -- that is data),
* 2 on usage/codec errors.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
#include <libgen.h>
#include <sys/resource.h>
#include "ecc_iface.h"
#include "sha256.h"
/* ---- codec factory (one constructor per family file) ---- */
ecc_codec_t *bch_ship_new(int t);
ecc_codec_t *bch_1k_new(int t);
ecc_codec_t *interleave_new(int depth, int t);
ecc_codec_t *ldpc_new(int rate_pct);
ecc_codec_t *polar_new(int rate_pct, int design_exp);
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo);
static ecc_codec_t *make_codec(const char *name)
{
int v;
if (sscanf(name, "bch-t%d", &v) == 1)
return bch_ship_new(v);
if (sscanf(name, "bch1k-t%d", &v) == 1)
return bch_1k_new(v);
int d, t;
if (sscanf(name, "intlv-d%d-bch1k-t%d", &d, &t) == 2)
return interleave_new(d, t);
if (sscanf(name, "ldpc-r%d", &v) == 1)
return ldpc_new(v);
int dexp;
if (sscanf(name, "polar-r%d-d%d", &v, &dexp) == 2)
return polar_new(v, dexp);
if (sscanf(name, "polar-r%d", &v) == 1)
return polar_new(v, 2);
int cb, th, tl;
if (sscanf(name, "uep-c%d-h%d-l%d", &cb, &th, &tl) == 3)
return uep_new(cb, th, tl);
return NULL;
}
/* ---- xorshift64* RNG ---- */
static uint64_t rs = 0x12345678abcdefULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
static uint8_t *read_file(const char *path, size_t *len_out)
{
FILE *f = fopen(path, "rb");
if (!f)
return NULL;
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
if (n <= 0) {
fclose(f);
return NULL;
}
uint8_t *buf = (uint8_t *)malloc((size_t)n);
if (!buf) {
fclose(f);
return NULL;
}
if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
free(buf);
fclose(f);
return NULL;
}
fclose(f);
*len_out = (size_t)n;
return buf;
}
static void usage(void)
{
fprintf(stderr,
"usage: bench --codec NAME --blob FILE [--size N] [--trials N]\n"
" [--seed S] (--ber X | --burst LEN,COUNT | --clean | --speed)\n"
" [--out results.csv]\n"
" codecs: bch-t{2,4,8,16,32} bch1k-t{8,16,32}\n"
" intlv-d{16,32,64}-bch1k-t{8,16,32} ldpc-r{90,95}\n"
" polar-r{90,95} uep-c{1024,4096}-h{16,32}-l{2,4}\n");
}
int main(int argc, char **argv)
{
const char *codec_name = NULL, *blob_path = NULL, *out_path = NULL;
size_t win_size = 65536;
long trials = 200;
uint64_t seed = 0x12345678abcdefULL;
enum { M_BER, M_BURST, M_CLEAN, M_SPEED } mode = M_BER;
double ber = 1e-3;
long burst_len = 256, burst_count = 1;
int nopass2 = 0;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--codec") && i + 1 < argc)
codec_name = argv[++i];
else if (!strcmp(argv[i], "--blob") && i + 1 < argc)
blob_path = argv[++i];
else if (!strcmp(argv[i], "--out") && i + 1 < argc)
out_path = argv[++i];
else if (!strcmp(argv[i], "--size") && i + 1 < argc)
win_size = (size_t)strtoull(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--trials") && i + 1 < argc)
trials = strtol(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--seed") && i + 1 < argc)
seed = strtoull(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--ber") && i + 1 < argc) {
mode = M_BER;
ber = strtod(argv[++i], NULL);
} else if (!strcmp(argv[i], "--burst") && i + 1 < argc) {
mode = M_BURST;
char *a = argv[++i];
burst_len = strtol(a, NULL, 0);
char *comma = strchr(a, ',');
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
} else if (!strcmp(argv[i], "--nopass2")) {
nopass2 = 1;
} else if (!strcmp(argv[i], "--clean")) {
mode = M_CLEAN;
} else if (!strcmp(argv[i], "--speed")) {
mode = M_SPEED;
} else {
usage();
return 2;
}
}
if (!codec_name || !blob_path) {
usage();
return 2;
}
size_t file_len = 0;
uint8_t *file = read_file(blob_path, &file_len);
if (!file || file_len <= win_size) {
fprintf(stderr, "bench: cannot read blob %s (need > %zu bytes)\n",
blob_path, win_size);
return 2;
}
rs = seed ^ 0x9e3779b97f4a7c15ULL;
double t0 = now_s();
ecc_codec_t *c = make_codec(codec_name);
double init_s = now_s() - t0;
if (!c) {
fprintf(stderr, "bench: unknown codec %s\n", codec_name);
return 2;
}
const char *corpus = strrchr(blob_path, '/');
corpus = corpus ? corpus + 1 : blob_path;
uint8_t *win = (uint8_t *)malloc(win_size);
uint8_t *stored = NULL, *rx = NULL, *out = NULL;
uint8_t want_sha[32];
if (!win) return 2;
out = (uint8_t *)malloc(win_size);
if (!out) return 2;
long success = 0, rescued = 0;
double enc_s = 0, dec_s = 0;
double overhead = 0;
int have_overhead = 0;
if (mode == M_SPEED) {
/* encode/decode the whole file in windows, 5 passes */
long passes = 5;
size_t nw = file_len / win_size;
double te0 = now_s();
for (long p = 0; p < passes; p++)
for (size_t w = 0; w < nw; w++) {
free(stored);
stored = NULL;
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
if (!sl) {
fprintf(stderr, "bench: encode failed in speed mode\n");
return 2;
}
if (!have_overhead) {
overhead = c->overhead;
have_overhead = 1;
}
}
double te1 = now_s();
double td0 = now_s();
for (long p = 0; p < passes; p++)
for (size_t w = 0; w < nw; w++) {
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
long corr = -1;
if (c->decode(c, stored, sl, win_size, out, &corr) != 0 ||
memcmp(out, file + w * win_size, win_size) != 0) {
fprintf(stderr, "bench: speed-mode roundtrip FAILED\n");
return 2;
}
}
double td1 = now_s();
double bytes = (double)passes * nw * win_size;
double enc_mb = bytes / (te1 - te0) / 1e6;
double dec_mb = bytes / (td1 - td0) / 1e6;
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
fprintf(stderr,
"SPEED %-28s corpus=%s win=%zu init=%.2fs enc=%.1f MB/s "
"dec=%.1f MB/s rss=%ld KiB overhead=%.2f%%\n",
codec_name, corpus, win_size, init_s, enc_mb, dec_mb,
ru.ru_maxrss, overhead * 100.0);
FILE *f = out_path ? fopen(out_path, "a") : stdout;
if (f) {
fprintf(f, "%s,%s,%zu,%ld,speed,init=%.2fs,0,0,1.000,"
"%.2f,%.2f,%ld,%.4f\n",
codec_name, corpus, win_size, passes, init_s, enc_mb,
dec_mb, ru.ru_maxrss, overhead * 100.0);
if (f != stdout)
fclose(f);
}
return 0;
}
/* corruption trials */
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
rx = (uint8_t *)malloc(1 << 20); /* grown below if needed */
for (long tr = 0; tr < trials; tr++) {
size_t off = (size_t)(xr() % (file_len - win_size + 1));
memcpy(win, file + off, win_size);
lzply_sha256(win, win_size, want_sha);
double te0 = now_s();
size_t slen = c->encode(c, win, win_size, &stored);
double te1 = now_s();
if (!slen) {
fprintf(stderr, "bench: encode failed trial %ld\n", tr);
return 2;
}
if (!have_overhead) {
overhead = c->overhead;
have_overhead = 1;
}
if (tr == 0) {
free(rx);
rx = (uint8_t *)malloc(slen);
if (!rx)
return 2;
}
memcpy(rx, stored, slen);
/* corrupt the stored bytes */
if (mode == M_BER) {
for (size_t i = 0; i < slen; i++) {
uint8_t m = 0;
for (int b = 0; b < 8; b++)
if (xr() < ber_thr)
m |= (uint8_t)(1u << b);
rx[i] ^= m;
}
} else if (mode == M_BURST) {
for (long b = 0; b < burst_count; b++) {
if ((size_t)burst_len >= slen)
continue;
size_t start = (size_t)(xr() % (slen - (size_t)burst_len + 1));
for (long k = 0; k < burst_len; k++)
rx[start + k] = (uint8_t)(xr() & 0xff);
}
}
double td0 = now_s();
long corr = -1;
int rc = c->decode(c, rx, slen, win_size, out, &corr);
int ok = (rc == 0 && memcmp(out, win, win_size) == 0);
if (!ok && !nopass2 && c->recover_verified) {
if (c->recover_verified(c, rx, slen, win_size, want_sha, out) == 0) {
ok = 1;
rescued++;
}
}
double td1 = now_s();
enc_s += te1 - te0;
dec_s += td1 - td0;
if (ok)
success++;
free(stored);
stored = NULL;
}
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
double rate = trials ? (double)success / (double)trials : 0;
double enc_mb = enc_s > 0 ? (double)trials * win_size / enc_s / 1e6 : 0;
double dec_mb = dec_s > 0 ? (double)trials * win_size / dec_s / 1e6 : 0;
char param[64];
if (mode == M_BER)
snprintf(param, sizeof param, "ber=%g", ber);
else if (mode == M_BURST)
snprintf(param, sizeof param, "burst=%ldx%ld", burst_len, burst_count);
else
snprintf(param, sizeof param, "clean");
const char *mname =
mode == M_BER ? "ber" : mode == M_BURST ? "burst" : "clean";
FILE *f = out_path ? fopen(out_path, "a") : stdout;
if (f) {
fprintf(f, "%s,%s,%zu,%ld,%s,%s,%ld,%ld,%.4f,%.2f,%.2f,%ld,%.4f\n",
codec_name, corpus, win_size, trials, mname, param, success,
rescued, rate, enc_mb, dec_mb, ru.ru_maxrss,
overhead * 100.0);
if (f != stdout)
fclose(f);
}
fprintf(stderr, "%-28s %-12s %-14s %4ld trials rate=%.3f rescued=%ld "
"enc=%.0fMB/s dec=%.0fMB/s ovh=%.2f%% rss=%ldKiB\n",
codec_name, corpus, param, trials, rate, rescued, enc_mb, dec_mb,
overhead * 100.0, ru.ru_maxrss);
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
/* ecc_iface.h - generic error-correction codec interface for the lzply
* experiments harness (exp/). Every family under test implements this
* interface so bench.c measures them all the same way: encode a blob,
* corrupt the stored bytes, decode, and check exact recovery (SHA-256).
*
* A codec is a whole-blob transform: encode(data) -> stored bytes,
* decode(stored) -> data or failure. Block structure inside is the
* codec's business; the harness only sees blob in / blob out.
*/
#ifndef EXP_ECC_IFACE_H
#define EXP_ECC_IFACE_H
#include <stddef.h>
#include <stdint.h>
typedef struct ecc_codec ecc_codec_t;
struct ecc_codec {
const char *name; /* short id, e.g. "bch-t32" (used in CSV output) */
const char *desc; /* human-readable description */
size_t block_data; /* nominal data bytes per code block (0 = whole blob) */
/* encode data[0..len) -> malloc'd *out; return stored length, 0 on error.
Sets c->overhead = stored/len - 1. */
size_t (*encode)(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out);
/* decode stored[0..slen) -> out[0..orig_len); 0 = exact recovery,
-1 = failure. *corrected = bits/symbols corrected if known, else -1. */
int (*decode)(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected);
/* Optional second-chance recovery: given the expected SHA-256 of the
original data, try harder (e.g. BCH pass-2 candidates) and use the
first candidate that verifies. 0 = rescued, -1 = not. May be NULL. */
int (*recover_verified)(ecc_codec_t *c, const uint8_t *stored,
size_t slen, size_t orig_len,
const uint8_t want_sha[32], uint8_t *out);
double overhead; /* from the last encode() call */
void (*destroy)(ecc_codec_t *c);
void *priv;
};
#endif /* EXP_ECC_IFACE_H */
+253
View File
@@ -0,0 +1,253 @@
/* interleave.c - byte interleaver over small-block BCH.
*
* The encoded stream (bch1k-t{T}: blocks of ~1 KiB data, t parity bits
* each) is permuted before it hits the channel: the stream is cut into
* groups of D consecutive blocks, each group written row-wise into a
* D-row matrix (row j = block j) and read out column-wise. A burst of
* L consecutive bytes in the channel then hits any one block at most
* ceil(L/D) bytes -- about 4*L/D bit errors, since a randomized byte
* flips ~4 bits -- instead of all L bytes landing in one block and
* killing it outright. Zero extra parity: the interleaver is a pure
* permutation, inverted on decode, so overhead is exactly the BCH
* overhead and random-error performance is unchanged. The win is
* purely burst tolerance, roughly a factor D in burst length.
*
* Groups are self-delimiting: block boundaries are recomputed from
* orig_len, so the decoder knows every group's shape. The final group
* may be short and the final block short; the column traversal simply
* skips missing cells, which keeps the permutation exact with no
* padding and no length change.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ecc_iface.h"
#include "bch.h"
#include "bch_wrap.h"
typedef struct {
ecc_codec_t *inner; /* bch1k-t{T} */
int depth; /* blocks per interleave group */
int t;
} intlv_priv_t;
/* Permute the encoded stream (forward = interleave).
* blocks[] holds the stored length of each block; nblocks total.
* out must hold the same total length.
*
* Groups: blocks are cut into groups of `depth`, EXCEPT the final
* partial group is merged into the previous one instead of standing
* alone. A tiny tail group is the weak point: a burst landing in a
* 4-block tail hits each of its blocks with L/4 bytes instead of
* L/64, which is exactly why the first measurement showed 0.94
* instead of 1.00 on 64-byte bursts (the 68-block blob ends in a
* 4-block tail). Merging makes every group >= depth (the last may
* exceed it); when nblocks <= depth there is a single group. */
static void permute(const uint8_t *in, uint8_t *out, const size_t *blocks,
size_t nblocks, int depth, int forward)
{
size_t *start = (size_t *)malloc((nblocks + 1) * sizeof(size_t));
if (!start)
return;
start[0] = 0;
for (size_t i = 0; i < nblocks; i++)
start[i + 1] = start[i] + blocks[i];
/* group boundaries: groups of `depth`, last partial group merged
into the previous one */
size_t g0 = 0;
while (g0 < nblocks) {
size_t remain = nblocks - g0;
size_t g = remain < (size_t)depth ? remain : (size_t)depth;
/* If this would leave a short tail after this group, extend
this group to absorb the tail. (Invariant: a short tail
never survives an iteration, so no group is ever < depth
except when the whole blob is.) */
if (remain > (size_t)depth && remain - (size_t)depth < (size_t)depth)
g = remain;
size_t maxlen = 0;
for (size_t j = 0; j < g; j++)
if (blocks[g0 + j] > maxlen)
maxlen = blocks[g0 + j];
size_t goff = start[g0];
size_t pos = 0;
for (size_t c = 0; c < maxlen; c++) {
for (size_t j = 0; j < g; j++) {
if (c >= blocks[g0 + j])
continue;
size_t src = start[g0 + j] + c;
size_t dst = goff + pos;
if (forward)
out[dst] = in[src];
else
out[src] = in[dst];
pos++;
}
}
g0 += g;
}
free(start);
}
static size_t intlv_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
uint8_t *enc = NULL;
size_t slen = p->inner->encode(p->inner, data, len, &enc);
if (!slen)
return 0;
/* block layout of the inner encoding */
size_t bd = p->inner->block_data;
size_t nblocks = (len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks) {
free(enc);
return 0;
}
/* stored length of block i: full blocks first, last may be short.
The inner codec is bch_encode with a pinned poly, so stored
length is a pure function of the block's data length. Recover
it by splitting slen: all full blocks share one length. */
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = len - i * bd < bd ? len - i * bd : bd;
/* stored bytes for dlen data bytes under the pinned poly:
ceil((8*dlen + r)/8); r = t*13 for m=13 */
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) { /* should not happen; bail out cleanly */
free(blocks);
free(enc);
return 0;
}
uint8_t *buf = (uint8_t *)malloc(slen);
if (!buf) {
free(blocks);
free(enc);
return 0;
}
permute(enc, buf, blocks, nblocks, p->depth, 1);
free(blocks);
free(enc);
c->overhead = p->inner->overhead;
*out = buf;
return slen;
}
static int intlv_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
size_t bd = p->inner->block_data;
size_t nblocks = (orig_len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks)
return -1;
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) {
free(blocks);
return -1;
}
uint8_t *deint = (uint8_t *)malloc(slen);
if (!deint) {
free(blocks);
return -1;
}
permute(stored, deint, blocks, nblocks, p->depth, 0);
free(blocks);
int rc = p->inner->decode(p->inner, deint, slen, orig_len, out,
corrected);
free(deint);
return rc;
}
static int intlv_recover(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, const uint8_t want_sha[32],
uint8_t *out)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
size_t bd = p->inner->block_data;
size_t nblocks = (orig_len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks)
return -1;
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) {
free(blocks);
return -1;
}
uint8_t *deint = (uint8_t *)malloc(slen);
if (!deint) {
free(blocks);
return -1;
}
permute(stored, deint, blocks, nblocks, p->depth, 0);
free(blocks);
int rc = p->inner->recover_verified
? p->inner->recover_verified(p->inner, deint, slen, orig_len,
want_sha, out)
: -1;
free(deint);
return rc;
}
static void intlv_destroy(ecc_codec_t *c)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
if (p->inner)
p->inner->destroy(p->inner);
free(p);
free((void *)c->name);
free(c);
}
ecc_codec_t *interleave_new(int depth, int t)
{
ecc_codec_t *inner = bch_1k_new(t);
if (!inner)
return NULL;
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
intlv_priv_t *p = (intlv_priv_t *)calloc(1, sizeof(*p));
if (!c || !p) {
free(c);
free(p);
inner->destroy(inner);
return NULL;
}
char *name = (char *)malloc(32);
if (!name) {
free(c);
free(p);
inner->destroy(inner);
return NULL;
}
snprintf(name, 32, "intlv-d%d-bch1k-t%d", depth, t);
p->inner = inner;
p->depth = depth;
p->t = t;
c->name = name;
c->desc = "byte interleaver over small-block BCH";
c->block_data = inner->block_data;
c->encode = intlv_encode;
c->decode = intlv_decode;
c->recover_verified = intlv_recover;
c->destroy = intlv_destroy;
c->priv = p;
return c;
}
+565
View File
@@ -0,0 +1,565 @@
/* ldpc.c - regular LDPC codec for the experiments harness.
*
* Two operating points, both n=8192 bits, column weight 3:
* ldpc-r90: m=768 checks, row weight 32, k=7424 bits (928 B),
* rate 0.90625, overhead 10.34%.
* ldpc-r95: m=384 checks, row weight 64, k=7808 bits (976 B),
* rate 0.953125, overhead 4.92%.
*
* Construction: random regular parity-check matrix (configuration
* model with 4-cycle rejection), fixed seed, so the code is identical
* on every run and every server. Systematic encoding by Gauss-Jordan
* reduction of H to [I | P] (one-time, at codec creation); decoding
* is normalized min-sum belief propagation (factor 0.8), max 50
* iterations, early stop when the syndrome is zero. Channel LLR uses
* a fixed nominal crossover p0 = 1e-3 (the decoder does not know the
* true BER; this is the honest setting for a storage channel).
*
* A blob is split into blocks of k data bytes; the last block is
* zero-padded to k bytes (padding is discarded on decode). Stored
* length per block is exactly n/8 = 1024 bytes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "ecc_iface.h"
#define LDPC_N 8192
#define LDPC_WC 3
#define LDPC_MAX_ITER 50
#define LDPC_MS_NORM 0.8f
#define LDPC_P0 1e-3
typedef struct {
int m; /* checks */
int wr; /* row weight */
int k; /* data bits */
int kbytes; /* data bytes per block */
int nedges;
int *chk_var; /* m * wr: vars of each check */
int *var_chk; /* n * wc: checks of each var */
int *chk_edge; /* m * wr: edge id (var*wc+w) of each check entry */
int *pivot_col; /* m: pivot column of each RREF row */
uint64_t *enc_rows; /* m * kwords: RREF rows over data positions */
int kwords;
int *col_of_dp; /* k: column holding data position i */
float *msg_vc; /* var->check, nedges */
float *msg_cv; /* check->var, nedges */
float *llr_ch; /* n */
uint8_t *hard; /* n */
} ldpc_t;
static void free_ldpc(ldpc_t *L)
{
if (!L)
return;
free(L->chk_var);
free(L->var_chk);
free(L->chk_edge);
free(L->pivot_col);
free(L->enc_rows);
free(L->col_of_dp);
free(L->msg_vc);
free(L->msg_cv);
free(L->llr_ch);
free(L->hard);
free(L);
}
static uint64_t lrs = 0x243f6a8885a308d3ULL;
static inline uint64_t lxr(void)
{
lrs ^= lrs << 13;
lrs ^= lrs >> 7;
lrs ^= lrs << 17;
return lrs;
}
/* ---- construction: progressive edge growth (PEG) ----
* Edge by edge, each new edge of variable node v connects to the
* check node farthest from v in the graph built so far (unreached
* checks count as infinitely far), tie-broken by lowest check degree.
* PEG never deadlocks (there is always a farthest check) and
* maximizes girth by construction -- unlike greedy 4-cycle
* rejection, which stalls in the endgame when the remaining stub
* rows all close short cycles. Fallback: if every farthest check is
* already full (cannot happen with balanced degrees, but be safe),
* take the lowest-degree check overall. */
static int build_H(ldpc_t *L, uint64_t seed)
{
int m = L->m, n = LDPC_N, wc = LDPC_WC, wr = L->wr;
int *chk_deg = (int *)calloc((size_t)m, sizeof(int));
int *var_deg = (int *)calloc((size_t)n, sizeof(int));
int *dist = (int *)malloc((size_t)(n + m) * sizeof(int));
int *queue = (int *)malloc((size_t)(n + m) * sizeof(int));
if (!chk_deg || !var_deg || !dist || !queue) {
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return -1;
}
lrs = seed;
(void)lxr; /* seed only matters for tie-breaking below */
for (int v = 0; v < n; v++) {
for (int e = 0; e < wc; e++) {
/* BFS from v over the graph built so far. Node ids:
0..n-1 variables, n..n+m-1 checks. */
for (int i = 0; i < n + m; i++)
dist[i] = -1;
int qh = 0, qt = 0;
dist[v] = 0;
queue[qt++] = v;
int found_checks = 0;
while (qh < qt && found_checks < m) {
int u = queue[qh++];
int d = dist[u];
if (u < n) {
for (int w = 0; w < var_deg[u]; w++) {
int nid = n + L->var_chk[u * wc + w];
if (dist[nid] < 0) {
dist[nid] = d + 1;
queue[qt++] = nid;
found_checks++;
}
}
} else {
int ch = u - n;
for (int k = 0; k < chk_deg[ch]; k++) {
int vv = L->chk_var[ch * wr + k];
if (dist[vv] < 0) {
dist[vv] = d + 1;
queue[qt++] = vv;
}
}
}
}
/* farthest distance among reached checks (-1 = unreached) */
int bestd = -2, have_unreached = 0;
for (int ch = 0; ch < m; ch++) {
int d = dist[n + ch];
if (d < 0) {
have_unreached = 1;
} else if (d > bestd) {
bestd = d;
}
}
int best = -1, bestdeg = wr + 1;
for (int ch = 0; ch < m; ch++) {
int d = dist[n + ch];
int far = have_unreached ? (d < 0) : (d == bestd);
if (!far)
continue;
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
bestdeg = chk_deg[ch];
best = ch;
}
}
if (best < 0) {
/* fallback: lowest-degree check anywhere */
for (int ch = 0; ch < m; ch++)
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
bestdeg = chk_deg[ch];
best = ch;
}
}
if (best < 0) {
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return -1;
}
L->var_chk[v * wc + var_deg[v]++] = best;
L->chk_var[best * wr + chk_deg[best]++] = v;
}
}
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return 0;
}
/* ---- Gauss-Jordan: H -> RREF, record pivot columns + enc rows ---- */
static int gauss_jordan(ldpc_t *L)
{
int m = L->m, n = LDPC_N;
int words = (n + 63) / 64;
uint64_t *H = (uint64_t *)calloc((size_t)m * words, sizeof(uint64_t));
if (!H)
return -1;
for (int r = 0; r < m; r++)
for (int k = 0; k < L->wr; k++) {
int c = L->chk_var[r * L->wr + k];
H[(size_t)r * words + c / 64] |= 1ULL << (c % 64);
}
int prow = 0;
for (int col = 0; col < n && prow < m; col++) {
int sel = -1;
for (int r = prow; r < m; r++)
if ((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL) {
sel = r;
break;
}
if (sel < 0)
continue;
if (sel != prow) {
for (int w = 0; w < words; w++) {
uint64_t t = H[(size_t)sel * words + w];
H[(size_t)sel * words + w] = H[(size_t)prow * words + w];
H[(size_t)prow * words + w] = t;
}
}
for (int r = 0; r < m; r++) {
if (r != prow &&
((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL)) {
for (int w = 0; w < words; w++)
H[(size_t)r * words + w] ^=
H[(size_t)prow * words + w];
}
}
L->pivot_col[prow++] = col;
}
if (prow != m) {
free(H);
return -1; /* H not full rank */
}
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
if (!is_pivot) {
free(H);
return -1;
}
for (int i = 0; i < m; i++)
is_pivot[L->pivot_col[i]] = 1;
L->col_of_dp = (int *)malloc((size_t)L->k * sizeof(int));
if (!L->col_of_dp) {
free(H);
free(is_pivot);
return -1;
}
int dp = 0;
for (int c = 0; c < n; c++)
if (!is_pivot[c])
L->col_of_dp[dp++] = c;
if (dp != L->k) {
free(H);
free(is_pivot);
return -1;
}
L->kwords = (L->k + 63) / 64;
L->enc_rows = (uint64_t *)calloc((size_t)m * L->kwords,
sizeof(uint64_t));
if (!L->enc_rows) {
free(H);
free(is_pivot);
return -1;
}
int *data_pos = (int *)malloc((size_t)n * sizeof(int));
if (!data_pos) {
free(H);
free(is_pivot);
return -1;
}
dp = 0;
for (int c = 0; c < n; c++)
data_pos[c] = is_pivot[c] ? -1 : dp++;
for (int i = 0; i < m; i++) {
for (int c = 0; c < n; c++) {
if (is_pivot[c])
continue;
if ((H[(size_t)i * words + c / 64] >> (c % 64)) & 1ULL) {
int p = data_pos[c];
L->enc_rows[(size_t)i * L->kwords + p / 64] |=
1ULL << (p % 64);
}
}
}
free(data_pos);
free(H);
free(is_pivot);
return 0;
}
/* bit helpers: MSB-first within each byte */
static inline int get_bit(const uint8_t *buf, int i)
{
return (buf[i / 8] >> (7 - (i % 8))) & 1;
}
static inline void set_bit(uint8_t *buf, int i, int v)
{
if (v)
buf[i / 8] |= (uint8_t)(1u << (7 - (i % 8)));
else
buf[i / 8] &= (uint8_t) ~(1u << (7 - (i % 8)));
}
static size_t ldpc_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
ldpc_t *L = (ldpc_t *)c->priv;
size_t nblocks = (len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
size_t slen = nblocks * (LDPC_N / 8);
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
if (!buf)
return 0;
uint8_t *dbytes = (uint8_t *)calloc((size_t)L->kbytes, 1);
uint64_t *dw = (uint64_t *)malloc((size_t)L->kwords * sizeof(uint64_t));
if (!dbytes || !dw) {
free(buf);
free(dbytes);
free(dw);
return 0;
}
for (size_t b = 0; b < nblocks; b++) {
size_t dlen = len - b * (size_t)L->kbytes < (size_t)L->kbytes
? len - b * (size_t)L->kbytes
: (size_t)L->kbytes;
memset(dbytes, 0, (size_t)L->kbytes);
memcpy(dbytes, data + b * (size_t)L->kbytes, dlen);
/* data as words, bit i of the block -> word i/64, bit i%64 */
memset(dw, 0, (size_t)L->kwords * sizeof(uint64_t));
for (int i = 0; i < L->k; i++)
if (get_bit(dbytes, i))
dw[i / 64] |= 1ULL << (i % 64);
uint8_t *cw = buf + b * (LDPC_N / 8);
for (int i = 0; i < L->k; i++)
set_bit(cw, L->col_of_dp[i], get_bit(dbytes, i));
for (int i = 0; i < L->m; i++) {
const uint64_t *row = L->enc_rows + (size_t)i * L->kwords;
int acc = 0;
for (int w = 0; w < L->kwords; w++)
acc ^= __builtin_parityll(row[w] & dw[w]);
set_bit(cw, L->pivot_col[i], acc);
}
}
free(dbytes);
free(dw);
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
*out = buf;
return slen;
}
static int ldpc_decode_block(ldpc_t *L, const uint8_t *cw_in,
uint8_t *data_out, long *corrected_out)
{
int n = LDPC_N, m = L->m, wc = LDPC_WC, wr = L->wr;
float L0 = (float)log((1.0 - LDPC_P0) / LDPC_P0);
for (int i = 0; i < n; i++) {
L->llr_ch[i] = get_bit(cw_in, i) ? -L0 : L0;
for (int w = 0; w < wc; w++)
L->msg_vc[i * wc + w] = L->llr_ch[i];
}
int converged = 0;
for (int it = 0; it < LDPC_MAX_ITER && !converged; it++) {
/* check update: two-minimum min-sum, via chk_edge ids */
for (int j = 0; j < m; j++) {
float min1 = 1e30f, min2 = 1e30f;
int argmin1 = -1, sign = 1;
for (int k = 0; k < wr; k++) {
int e = L->chk_edge[j * wr + k];
float x = L->msg_vc[e];
float a = fabsf(x);
if (a < min1) {
min2 = min1;
min1 = a;
argmin1 = k;
} else if (a < min2) {
min2 = a;
}
if (x < 0)
sign = -sign;
}
for (int k = 0; k < wr; k++) {
int e = L->chk_edge[j * wr + k];
float x = L->msg_vc[e];
int s = sign;
if (x < 0)
s = -s;
float mag = (k == argmin1 ? min2 : min1) * LDPC_MS_NORM;
L->msg_cv[e] = s > 0 ? mag : -mag;
}
}
/* hard decision + syndrome check */
converged = 1;
for (int i = 0; i < n; i++) {
float tot = L->llr_ch[i];
for (int w = 0; w < wc; w++)
tot += L->msg_cv[i * wc + w];
L->hard[i] = tot < 0 ? 1 : 0;
}
for (int j = 0; j < m; j++) {
int p = 0;
for (int k = 0; k < wr; k++)
p ^= L->hard[L->chk_var[j * wr + k]];
if (p) {
converged = 0;
break;
}
}
if (converged)
break;
/* var->check messages for the next iteration */
for (int i = 0; i < n; i++)
for (int w = 0; w < wc; w++) {
float tot = L->llr_ch[i];
for (int w2 = 0; w2 < wc; w2++)
if (w2 != w)
tot += L->msg_cv[i * wc + w2];
L->msg_vc[i * wc + w] = tot;
}
}
if (!converged)
return -1;
long corr = 0;
for (int i = 0; i < n; i++)
if (L->hard[i] != get_bit(cw_in, i))
corr++;
if (corrected_out)
*corrected_out = corr;
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
if (!is_pivot)
return -1;
for (int i = 0; i < m; i++)
is_pivot[L->pivot_col[i]] = 1;
int dp = 0;
memset(data_out, 0, (size_t)L->kbytes);
for (int col = 0; col < n; col++)
if (!is_pivot[col])
set_bit(data_out, dp++, L->hard[col]);
free(is_pivot);
return 0;
}
static int ldpc_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
ldpc_t *L = (ldpc_t *)c->priv;
size_t nblocks = (orig_len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
if (slen != nblocks * (LDPC_N / 8))
return -1;
long corr = 0;
for (size_t b = 0; b < nblocks; b++) {
uint8_t *db = (uint8_t *)malloc((size_t)L->kbytes);
if (!db)
return -1;
long bc = 0;
int rc = ldpc_decode_block(L, stored + b * (LDPC_N / 8), db, &bc);
if (rc != 0) {
free(db);
if (corrected)
*corrected = -1;
return -1;
}
corr += bc;
size_t dlen = orig_len - b * (size_t)L->kbytes < (size_t)L->kbytes
? orig_len - b * (size_t)L->kbytes
: (size_t)L->kbytes;
memcpy(out + b * (size_t)L->kbytes, db, dlen);
free(db);
}
if (corrected)
*corrected = corr;
return 0;
}
static void ldpc_destroy(ecc_codec_t *c)
{
ldpc_t *L = (ldpc_t *)c->priv;
free_ldpc(L);
free((void *)c->name);
free(c);
}
ecc_codec_t *ldpc_new(int rate_pct)
{
int m, wr;
const char *tag;
if (rate_pct == 90) {
m = 768;
wr = 32;
tag = "ldpc-r90";
} else if (rate_pct == 95) {
m = 384;
wr = 64;
tag = "ldpc-r95";
} else {
return NULL;
}
ldpc_t *L = (ldpc_t *)calloc(1, sizeof(*L));
if (!L)
return NULL;
L->m = m;
L->wr = wr;
L->k = LDPC_N - m;
L->kbytes = L->k / 8;
L->nedges = LDPC_N * LDPC_WC;
L->chk_var = (int *)malloc((size_t)m * wr * sizeof(int));
L->var_chk = (int *)malloc((size_t)LDPC_N * LDPC_WC * sizeof(int));
L->chk_edge = (int *)malloc((size_t)m * wr * sizeof(int));
L->pivot_col = (int *)malloc((size_t)m * sizeof(int));
L->msg_vc = (float *)malloc((size_t)L->nedges * sizeof(float));
L->msg_cv = (float *)malloc((size_t)L->nedges * sizeof(float));
L->llr_ch = (float *)malloc((size_t)LDPC_N * sizeof(float));
L->hard = (uint8_t *)malloc((size_t)LDPC_N);
if (!L->chk_var || !L->var_chk || !L->chk_edge || !L->pivot_col ||
!L->msg_vc || !L->msg_cv || !L->llr_ch || !L->hard) {
free_ldpc(L);
return NULL;
}
int ok = -1;
int attempt_used = -1;
for (int attempt = 0; attempt < 10 && ok != 0; attempt++) {
ok = build_H(L, 0x9e3779b97f4a7c15ULL +
(uint64_t)attempt * 0x100000001b3ULL);
attempt_used = attempt;
}
if (getenv("LDPC_DEBUG"))
fprintf(stderr, "ldpc: build_H ok=%d attempts=%d\n", ok,
attempt_used + 1);
if (ok != 0) {
free_ldpc(L);
return NULL;
}
int gj = gauss_jordan(L);
if (getenv("LDPC_DEBUG"))
fprintf(stderr, "ldpc: gauss_jordan=%d\n", gj);
if (gj != 0) {
free_ldpc(L);
return NULL;
}
/* edge ids for the decoder: chk_edge[j*wr+k] = var*wc+w */
for (int j = 0; j < m; j++)
for (int k = 0; k < wr; k++) {
int v = L->chk_var[j * wr + k];
int e = -1;
for (int w = 0; w < LDPC_WC; w++)
if (L->var_chk[v * LDPC_WC + w] == j)
e = v * LDPC_WC + w;
L->chk_edge[j * wr + k] = e;
}
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
if (!c) {
free_ldpc(L);
return NULL;
}
char *name = (char *)malloc(16);
if (!name) {
free_ldpc(L);
free(c);
return NULL;
}
snprintf(name, 16, "%s", tag);
c->name = name;
c->desc = "regular LDPC, min-sum belief propagation";
c->block_data = (size_t)L->kbytes;
c->encode = ldpc_encode;
c->decode = ldpc_decode;
c->recover_verified = NULL;
c->destroy = ldpc_destroy;
c->priv = L;
return c;
}
+71
View File
@@ -0,0 +1,71 @@
/* ldpc_diag.c - diagnostic for the LDPC codec (NOT part of bench).
* Encodes one fixed block, flips exactly k bits (k = 0..KMAX), decodes,
* and reports the failure count per k. This separates "decoder bug"
* (fails even at k=1..3) from "code weakness" (fails only near the
* expected threshold). Usage: ldpc_diag <r90|r95> [kmax] [trials]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "ecc_iface.h"
ecc_codec_t *ldpc_new(int rate_pct);
static uint64_t rs = 0xabcdef1234567ULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
int main(int argc, char **argv)
{
int rate = 90;
int kmax = 24, trials = 100;
if (argc > 1)
rate = atoi(argv[1] + 1); /* "r90" -> 90 */
if (argc > 2)
kmax = atoi(argv[2]);
if (argc > 3)
trials = atoi(argv[3]);
ecc_codec_t *c = ldpc_new(rate);
if (!c) {
fprintf(stderr, "ldpc_new failed\n");
return 2;
}
size_t dlen = c->block_data;
uint8_t *data = (uint8_t *)malloc(dlen);
uint8_t *out = (uint8_t *)malloc(dlen);
for (size_t i = 0; i < dlen; i++)
data[i] = (uint8_t)(xr() & 0xff);
uint8_t *stored = NULL;
size_t slen = c->encode(c, data, dlen, &stored);
if (!slen) {
fprintf(stderr, "encode failed\n");
return 2;
}
printf("rate=%d block_data=%zu stored=%zu overhead=%.2f%%\n", rate,
dlen, slen, c->overhead * 100.0);
uint8_t *rx = (uint8_t *)malloc(slen);
for (int k = 0; k <= kmax; k++) {
int fails = 0;
for (int t = 0; t < trials; t++) {
memcpy(rx, stored, slen);
/* flip k distinct random bits */
for (int f = 0; f < k; f++) {
size_t p = (size_t)(xr() % (slen * 8));
rx[p / 8] ^= (uint8_t)(1u << (7 - (p % 8)));
}
long corr = -1;
int rc = c->decode(c, rx, slen, dlen, out, &corr);
if (rc != 0 || memcmp(out, data, dlen) != 0)
fails++;
}
printf("k=%2d fails=%d/%d\n", k, fails, trials);
fflush(stdout);
}
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# mkcorpora.sh - build the experiment corpora in exp/corpora/.
# text.raw / text.lz : English-ish text (docs + sources)
# bin.raw / bin.lz : ELF binaries
# rand.raw / rand.lz : seeded pseudo-random bytes (incompressible)
# lz files are lzip -9 of the raw files: that is what lzply actually
# protects (the compressed blob), plus the raw files for stored entries.
set -e
cd "$(dirname "$0")/corpora"
# text: repo docs/sources + system docs
{ find /opt/lzply-exp-ecc -name "*.md" -o -name "*.c" -o -name "*.h" | sort | xargs cat
find /usr/share/doc -type f -size -200k 2>/dev/null | head -200 | sort | xargs cat 2>/dev/null
find /usr/include -name "*.h" 2>/dev/null | head -300 | sort | xargs cat 2>/dev/null
} > text.raw
head -c 4194304 text.raw > text4m.raw && mv text4m.raw text.raw
# binaries: ELF files from /bin and /usr/bin
{ for f in /bin/* /usr/bin/*; do
[ -f "$f" ] && head -c1 "$f" | grep -q . && file "$f" 2>/dev/null | grep -q ELF && cat "$f"
done
} > bin.raw 2>/dev/null
head -c 4194304 bin.raw > bin4m.raw && mv bin4m.raw bin.raw
# random: seeded python (reproducible on both servers)
python3 -c "import random; random.seed(1234); open(\"rand.raw\",\"wb\").write(bytes(random.getrandbits(8) for _ in range(4194304)))"
for f in text bin rand; do
lzip -9 -f -c "$f.raw" > "$f.lz" 2>/dev/null || lzip -9 -c "$f.raw" > "$f.lz"
done
ls -la
+89
View File
@@ -0,0 +1,89 @@
/* pass2_diag.c - targeted test of BCH pass-2 (hash-gated candidates).
* Encodes one bch1k block, flips exactly k bits (k around t), and
* reports: pass-1 success, and pass-2 rescue (candidate verifies
* against the SHA-256 of the original). This separates "pass 2 is
* weak" from "the harness wiring is broken".
* Usage: pass2_diag <t> [kmax] [trials]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "bch.h"
#include "bch_polys.h"
#include "sha256.h"
static uint64_t rs = 0xabcdef1234567ULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
static const bch_poly_t *poly_by_mt(int m, int t)
{
for (int i = 0; i < BCH_NPOLYS; i++)
if (bch_polys[i].m == m && bch_polys[i].t == t)
return &bch_polys[i];
return NULL;
}
int main(int argc, char **argv)
{
int t = argc > 1 ? atoi(argv[1]) : 16;
int kmax = argc > 2 ? atoi(argv[2]) : t + 8;
int trials = argc > 3 ? atoi(argv[3]) : 50;
const bch_poly_t *p = poly_by_mt(13, t);
if (!p) {
fprintf(stderr, "no poly m=13 t=%d\n", t);
return 2;
}
size_t dlen = bch_max_data(p);
size_t slen = bch_block_stored_len(dlen, p);
uint8_t *data = (uint8_t *)malloc(dlen);
uint8_t *stored = (uint8_t *)malloc(slen);
uint8_t *rx = (uint8_t *)malloc(slen);
uint8_t *out = (uint8_t *)malloc(dlen);
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * dlen);
for (size_t i = 0; i < dlen; i++)
data[i] = (uint8_t)(xr() & 0xff);
if (bch_encode_block(data, dlen, p, stored) != 0) {
fprintf(stderr, "encode failed\n");
return 2;
}
uint8_t want[32];
lzply_sha256(data, dlen, want);
printf("t=%d block_data=%zu stored=%zu\n", t, dlen, slen);
for (int k = t - 2; k <= kmax; k++) {
int p1 = 0, rescued = 0;
for (int tr = 0; tr < trials; tr++) {
memcpy(rx, stored, slen);
for (int f = 0; f < k; f++) {
size_t pos = (size_t)(xr() % (slen * 8));
rx[pos / 8] ^= (uint8_t)(1u << (7 - (pos % 8)));
}
int corr = -1;
if (bch_decode_block(rx, slen, dlen, p, out, &corr) == 0 &&
memcmp(out, data, dlen) == 0) {
p1++;
continue;
}
int nc = bch_decode_block_candidates(rx, slen, dlen, p, cands,
BCH_PASS2_MAX_CANDS);
for (int i = 0; i < nc; i++) {
uint8_t h[32];
lzply_sha256(cands + (size_t)i * dlen, dlen, h);
if (memcmp(h, want, 32) == 0) {
rescued++;
break;
}
}
}
printf("k=%2d pass1=%d/%d rescued=%d/%d\n", k, p1, trials, rescued,
trials);
fflush(stdout);
}
return 0;
}
+333
View File
@@ -0,0 +1,333 @@
/* polar.c - polar code codec for the experiments harness.
*
* N=4096, successive-cancellation (SC) decoding with the min-sum
* f-function. Construction is Arikan's Bhattacharyya recursion for
* the binary erasure channel with erasure probability equal to the
* BSC's Bhattacharyya parameter Z = 2*sqrt(p(1-p)) at a design
* crossover p (see polar_new: the codec name selects it, e.g.
* polar-r90-d3 designs for p=1e-3; plain polar-r90 designs for
* p=1e-2). The design point matters: designing for a much worse
* channel than the operating point ranks the marginal channels
* wrong and SC pays for it.
*
* polar-r90: K=3680 info bits (460 B), rate 0.89844, overhead 11.30%.
* polar-r95: K=3888 info bits (486 B), rate 0.94922, overhead 5.35%.
*
* A blob is split into blocks of K data bytes; the last block is
* zero-padded. Stored length per block is exactly N/8 = 512 bytes.
*
* Note: SC decoding always returns a codeword, so decode() cannot
* detect failure by itself -- it returns 0 whenever decoding
* completes, and the caller (bench / lzply's SHA-256) is the oracle
* that decides whether the recovered data is correct. That matches
* lzply's architecture: the entry SHA is the miscorrection guard.
* Channel LLR uses a fixed nominal crossover p0 = 1e-3, same honest
* setting as the LDPC codec.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "ecc_iface.h"
#define POLAR_N 4096
#define POLAR_LOGN 12
#define POLAR_P0 1e-3
typedef struct {
int k; /* info bits */
int kbytes; /* info bytes per block */
double p_design; /* design crossover for the BEC construction */
uint8_t frozen[POLAR_N]; /* 1 = frozen (0 bit) */
float *llr; /* N, decode workspace */
float *ws; /* N, SC scratch (bump-allocated down the tree) */
uint8_t *bits; /* N, decoded info vector (leaf decisions) */
uint8_t *psum; /* N, partial sums (re-encoded codeword) */
} polar_t;
static void polar_build_frozen(polar_t *P)
{
/* BEC Bhattacharyya recursion: Z starts at eps, then per level
the upper (bad) channel gets 2Z-Z^2 and the lower (good) one
gets Z^2. z[] holds the values in bit-reversed order matching
the standard construction; sorting by Z ascending gives the
reliability order. */
double eps = 2.0 * sqrt(P->p_design * (1.0 - P->p_design));
double z[POLAR_N];
for (int i = 0; i < POLAR_N; i++)
z[i] = eps;
for (int level = 0; level < POLAR_LOGN; level++) {
int step = 1 << (level + 1);
int half = 1 << level;
for (int base = 0; base < POLAR_N; base += step) {
for (int i = 0; i < half; i++) {
double a = z[base + i];
double b = z[base + half + i];
/* upper (first half) is the worse channel */
z[base + i] = 2 * a - a * a;
z[base + half + i] = b * b;
}
}
}
/* The recursion above indexes channels in natural order only if
the pairing is right; verify by construction: sort indices by
Z and take the K smallest as information positions. */
int idx[POLAR_N];
for (int i = 0; i < POLAR_N; i++)
idx[i] = i;
/* simple insertion-free sort: qsort with a comparator on z */
/* (z is captured via a file-scope pointer for the comparator) */
extern double *polar_sort_z;
polar_sort_z = z;
/* qsort needs a comparator; defined below */
extern int polar_cmp_idx(const void *, const void *);
qsort(idx, POLAR_N, sizeof(int), polar_cmp_idx);
memset(P->frozen, 1, POLAR_N);
for (int i = 0; i < P->k; i++)
P->frozen[idx[i]] = 0;
}
double *polar_sort_z = NULL;
int polar_cmp_idx(const void *a, const void *b)
{
int ia = *(const int *)a, ib = *(const int *)b;
if (polar_sort_z[ia] < polar_sort_z[ib])
return -1;
if (polar_sort_z[ia] > polar_sort_z[ib])
return 1;
return ia - ib;
}
/* polar transform: in-place butterfly, u ^= u shifted */
static void polar_transform(uint8_t *u, int n)
{
for (int len = 1; len < n; len <<= 1) {
for (int base = 0; base < n; base += 2 * len) {
for (int i = 0; i < len; i++) {
int a = base + i, b = base + len + i;
u[a] ^= u[b];
}
}
}
}
static inline int get_bit(const uint8_t *buf, int i)
{
return (buf[i / 8] >> (7 - (i % 8))) & 1;
}
static inline void set_bit(uint8_t *buf, int i, int v)
{
if (v)
buf[i / 8] |= (uint8_t)(1u << (7 - (i % 8)));
else
buf[i / 8] &= (uint8_t) ~(1u << (7 - (i % 8)));
}
static size_t polar_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
polar_t *P = (polar_t *)c->priv;
size_t nblocks = (len + (size_t)P->kbytes - 1) / (size_t)P->kbytes;
size_t slen = nblocks * (POLAR_N / 8);
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
if (!buf)
return 0;
uint8_t *u = (uint8_t *)malloc(POLAR_N);
if (!u) {
free(buf);
return 0;
}
for (size_t b = 0; b < nblocks; b++) {
size_t dlen = len - b * (size_t)P->kbytes < (size_t)P->kbytes
? len - b * (size_t)P->kbytes
: (size_t)P->kbytes;
memset(u, 0, POLAR_N);
int dp = 0;
for (int i = 0; i < POLAR_N; i++) {
if (P->frozen[i])
continue;
if (dp < (int)dlen * 8)
u[i] = (uint8_t)get_bit(data + b * (size_t)P->kbytes, dp);
dp++;
}
polar_transform(u, POLAR_N);
uint8_t *cw = buf + b * (POLAR_N / 8);
for (int i = 0; i < POLAR_N; i++)
set_bit(cw, i, u[i]);
}
free(u);
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
*out = buf;
return slen;
}
static inline float polar_f(float a, float b)
{
float m = fabsf(a) < fabsf(b) ? fabsf(a) : fabsf(b);
int s = ((a < 0) ^ (b < 0)) ? -1 : 1;
return s * m;
}
static inline float polar_g(float a, float b, int u)
{
return b + (u ? -a : a);
}
static void sc_rec(polar_t *P, const float *llr, int off, int len,
float *ws)
{
if (len == 1) {
/* Leaf: the decision is the decoded info bit. The partial
sum at a leaf is the bit itself. The two arrays must stay
separate: the combine step below rewrites psum (it becomes
the re-encoded codeword) and must not touch bits. */
int b = 0;
if (!P->frozen[off])
b = llr[0] < 0 ? 1 : 0;
P->bits[off] = (uint8_t)b;
P->psum[off] = (uint8_t)b;
return;
}
int half = len / 2;
/* Scratch for this level lives in ws[0..half); children bump
past it. Total scratch along any path is N floats. */
float *tmp = ws;
for (int i = 0; i < half; i++)
tmp[i] = polar_f(llr[i], llr[half + i]);
sc_rec(P, tmp, off, half, ws + half);
for (int i = 0; i < half; i++)
tmp[i] = polar_g(llr[i], llr[half + i], P->psum[off + i]);
sc_rec(P, tmp, off + half, half, ws + half);
for (int i = 0; i < half; i++)
P->psum[off + i] ^= P->psum[off + half + i];
}
static int polar_decode_block(polar_t *P, const uint8_t *cw_in,
uint8_t *data_out, long *corrected_out)
{
float L0 = (float)log((1.0 - POLAR_P0) / POLAR_P0);
for (int i = 0; i < POLAR_N; i++)
P->llr[i] = get_bit(cw_in, i) ? -L0 : L0;
sc_rec(P, P->llr, 0, POLAR_N, P->ws);
/* psum now holds the decoded codeword; count corrected bits
against the received codeword. */
long corr = 0;
for (int i = 0; i < POLAR_N; i++)
if (P->psum[i] != get_bit(cw_in, i))
corr++;
if (corrected_out)
*corrected_out = corr;
/* data bits out: info positions in increasing index order */
int dp = 0;
memset(data_out, 0, (size_t)P->kbytes);
for (int i = 0; i < POLAR_N; i++) {
if (P->frozen[i])
continue;
set_bit(data_out, dp++, P->bits[i]);
}
return 0;
}
static int polar_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
polar_t *P = (polar_t *)c->priv;
size_t nblocks = (orig_len + (size_t)P->kbytes - 1) / (size_t)P->kbytes;
if (slen != nblocks * (POLAR_N / 8))
return -1;
long corr = 0;
for (size_t b = 0; b < nblocks; b++) {
uint8_t *db = (uint8_t *)malloc((size_t)P->kbytes);
if (!db)
return -1;
long bc = 0;
polar_decode_block(P, stored + b * (POLAR_N / 8), db, &bc);
corr += bc;
size_t dlen = orig_len - b * (size_t)P->kbytes < (size_t)P->kbytes
? orig_len - b * (size_t)P->kbytes
: (size_t)P->kbytes;
memcpy(out + b * (size_t)P->kbytes, db, dlen);
free(db);
}
if (corrected)
*corrected = corr;
return 0;
}
static void polar_destroy(ecc_codec_t *c)
{
polar_t *P = (polar_t *)c->priv;
free(P->llr);
free(P->ws);
free(P->bits);
free(P->psum);
free(P);
free((void *)c->name);
free(c);
}
ecc_codec_t *polar_new(int rate_pct, int design_exp)
{
int k;
const char *tag;
if (rate_pct == 90) {
k = 3680;
tag = "polar-r90";
} else if (rate_pct == 95) {
k = 3888;
tag = "polar-r95";
} else {
return NULL;
}
polar_t *P = (polar_t *)calloc(1, sizeof(*P));
if (!P)
return NULL;
P->k = k;
P->kbytes = k / 8;
P->p_design = pow(10.0, -(double)design_exp);
P->llr = (float *)malloc((size_t)POLAR_N * sizeof(float));
P->ws = (float *)malloc((size_t)POLAR_N * sizeof(float));
P->bits = (uint8_t *)malloc((size_t)POLAR_N);
P->psum = (uint8_t *)malloc((size_t)POLAR_N);
if (!P->llr || !P->ws || !P->bits || !P->psum) {
free(P->llr);
free(P->ws);
free(P->bits);
free(P->psum);
free(P);
return NULL;
}
polar_build_frozen(P);
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
if (!c) {
free(P->llr);
free(P->ws);
free(P->bits);
free(P->psum);
free(P);
return NULL;
}
char *name = (char *)malloc(24);
if (!name) {
free(P->llr);
free(P->ws);
free(P->bits);
free(P->psum);
free(P);
free(c);
return NULL;
}
if (design_exp == 2)
snprintf(name, 24, "%s", tag);
else
snprintf(name, 24, "%s-d%d", tag, design_exp);
c->name = name;
c->desc = "polar code, successive-cancellation decoding";
c->block_data = (size_t)P->kbytes;
c->encode = polar_encode;
c->decode = polar_decode;
c->recover_verified = NULL;
c->destroy = polar_destroy;
c->priv = P;
return c;
}
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# run_matrix.sh - full corruption matrix for a list of codecs.
# Usage: run_matrix.sh <corpus> <blobsize> <trials> <outfile> <codec...>
# Each codec x setting is its own bench invocation; xargs -P spreads
# them over all cores. Pass 2 is OFF for the matrix (too slow at scale);
# rescue rates are measured separately by run_pass2.sh.
set -u
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
mkdir -p "$(dirname "$OUT")"
{
for CODEC in "$@"; do
for BER in 1e-5 1e-4 1e-3 3e-3 1e-2; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --nopass2 --out $OUT"
done
for B in "16,1" "64,1" "256,1" "1024,1" "64,4"; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --nopass2 --out $OUT"
done
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --clean --out $OUT"
done
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/matrix.log'
echo "matrix done: $OUT"
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# run_pass2.sh - BCH pass-2 rescue rates, small trial count (pass 2 is
# slow; 25 trials per setting is enough to see rescues).
# Usage: run_pass2.sh <corpus> <blobsize> <trials> <outfile> <codec...>
set -u
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
mkdir -p "$(dirname "$OUT")"
{
for CODEC in "$@"; do
for BER in 1e-4 1e-3 3e-3; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --out $OUT"
done
for B in "64,1" "256,1"; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --out $OUT"
done
done
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/pass2.log'
echo "pass2 done: $OUT"
+177
View File
@@ -0,0 +1,177 @@
/* uep.c - unequal error protection over small-block BCH.
*
* The blob is split into a critical prefix (the first C bytes -- the
* lzip header and the start of the LZMA stream, where an error costs
* the most) protected at BCH t_hi, and the remainder at t_lo, both
* with m=13 small blocks. Stored = prefix_stored + rest_stored; the
* split point is recomputed from C and orig_len, so no per-entry
* metadata is needed beyond the codec parameters.
*
* Two things to know before judging it:
* - Exact recovery is dominated by the WEAK tier: UEP cannot beat
* uniform BCH at the same total overhead on whole-blob recovery,
* because the weak tier fails first. The fair comparison is
* t_lo == the uniform baseline t, with t_hi > t_lo costing only
* a little extra overhead (the prefix is short).
* - The win, if any, is graceful degradation: the prefix survives
* when the rest does not. That only helps lzply if it gains a
* salvage mode (today the entry SHA gates all-or-nothing
* extraction), so prefix survival is reported separately by
* uep_diag.c, not by bench.c.
* Pass 2 is not wired: the recovery oracle is the whole-blob SHA,
* which cannot verify a prefix candidate on its own.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ecc_iface.h"
#include "bch_wrap.h"
#include "uep.h"
typedef struct {
ecc_codec_t *hi; /* bch1k-t{t_hi} */
ecc_codec_t *lo; /* bch1k-t{t_lo} */
int crit_bytes;
int t_hi, t_lo;
} uep_priv_t;
/* Max data bytes per block under small-block BCH at t (pinned m=13
poly, N=8191): floor((8191 - 13*t)/8). NOTE: this depends on t --
971 for t=32 but 1010 for t=8. An earlier version hardcoded 971
and broke every tier but t=32. */
static size_t bch1k_max_data(int t)
{
return (8191 - (size_t)13 * (size_t)t) / 8;
}
/* Stored length of dlen data bytes under small-block BCH at t:
blocks of bch1k_max_data(t) bytes, ceil((8*dlen + t*13)/8) stored
each. (Mirrors bch_block_stored_len for the pinned m=13 poly.) */
static size_t bch1k_stored_len(size_t dlen, int t)
{
size_t maxd = bch1k_max_data(t);
size_t total = 0;
size_t r = (size_t)t * 13;
while (dlen > 0) {
size_t b = dlen < maxd ? dlen : maxd;
total += (8 * b + r + 7) / 8;
dlen -= b;
}
return total;
}
static size_t uep_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
uep_priv_t *p = (uep_priv_t *)c->priv;
size_t clen = len < (size_t)p->crit_bytes ? len : (size_t)p->crit_bytes;
uint8_t *hi = NULL, *lo = NULL;
size_t hi_len = p->hi->encode(p->hi, data, clen, &hi);
size_t lo_len = 0;
if (hi_len)
lo_len = p->lo->encode(p->lo, data + clen, len - clen, &lo);
if (!hi_len || (len > clen && !lo_len)) {
free(hi);
free(lo);
return 0;
}
uint8_t *buf = (uint8_t *)malloc(hi_len + lo_len);
if (!buf) {
free(hi);
free(lo);
return 0;
}
memcpy(buf, hi, hi_len);
memcpy(buf + hi_len, lo, lo_len);
free(hi);
free(lo);
c->overhead = len ? (double)(hi_len + lo_len) / (double)len - 1.0 : 0.0;
*out = buf;
return hi_len + lo_len;
}
int uep_decode_parts(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out)
{
uep_priv_t *p = (uep_priv_t *)c->priv;
size_t clen = orig_len < (size_t)p->crit_bytes
? orig_len
: (size_t)p->crit_bytes;
size_t hi_len = bch1k_stored_len(clen, p->t_hi);
size_t lo_len = bch1k_stored_len(orig_len - clen, p->t_lo);
if (hi_len + lo_len != slen)
return 0;
int mask = 0;
long corr = -1;
if (p->hi->decode(p->hi, stored, hi_len, clen, out, &corr) == 0)
mask |= 1;
if (p->lo->decode(p->lo, stored + hi_len, lo_len, orig_len - clen,
out + clen, &corr) == 0)
mask |= 2;
return mask;
}
static int uep_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
(void)corrected;
return uep_decode_parts(c, stored, slen, orig_len, out) == 3 ? 0 : -1;
}
static void uep_destroy(ecc_codec_t *c)
{
uep_priv_t *p = (uep_priv_t *)c->priv;
if (p->hi)
p->hi->destroy(p->hi);
if (p->lo)
p->lo->destroy(p->lo);
free(p);
free((void *)c->name);
free(c);
}
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo)
{
ecc_codec_t *hi = bch_1k_new(t_hi);
ecc_codec_t *lo = bch_1k_new(t_lo);
if (!hi || !lo) {
if (hi)
hi->destroy(hi);
if (lo)
lo->destroy(lo);
return NULL;
}
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
uep_priv_t *p = (uep_priv_t *)calloc(1, sizeof(*p));
if (!c || !p) {
free(c);
free(p);
hi->destroy(hi);
lo->destroy(lo);
return NULL;
}
char *name = (char *)malloc(32);
if (!name) {
free(c);
free(p);
hi->destroy(hi);
lo->destroy(lo);
return NULL;
}
snprintf(name, 32, "uep-c%d-h%d-l%d", crit_bytes, t_hi, t_lo);
p->hi = hi;
p->lo = lo;
p->crit_bytes = crit_bytes;
p->t_hi = t_hi;
p->t_lo = t_lo;
c->name = name;
c->desc = "unequal error protection over small-block BCH";
c->block_data = bch1k_max_data(t_lo); /* bulk tier's block size */
c->encode = uep_encode;
c->decode = uep_decode;
c->recover_verified = NULL;
c->destroy = uep_destroy;
c->priv = p;
return c;
}
+14
View File
@@ -0,0 +1,14 @@
/* uep.h - UEP codec plus the part-wise decode helper used by uep_diag. */
#ifndef EXP_UEP_H
#define EXP_UEP_H
#include "ecc_iface.h"
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo);
/* Decode and report per-part success: bit 1 = critical prefix decoded,
bit 2 = remainder decoded. Returns the bitmask (0..3). */
int uep_decode_parts(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out);
#endif /* EXP_UEP_H */
+125
View File
@@ -0,0 +1,125 @@
/* uep_diag.c - diagnostic for the UEP codec (NOT part of bench).
* Reports BOTH whole-blob exact recovery AND critical-prefix survival
* per corruption setting, so the graceful-degradation claim can be
* judged: a prefix that survives while the rest fails is only useful
* with a salvage mode, but it is the metric UEP exists for.
* Usage: uep_diag <codec> <blob> <size> <trials> (--ber X | --burst L,C)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "ecc_iface.h"
#include "uep.h"
static uint64_t rs = 0x13579bdf2468aceULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
int main(int argc, char **argv)
{
if (argc < 6) {
fprintf(stderr,
"usage: uep_diag <codec> <blob> <size> <trials> "
"(--ber X | --burst L,C)\n");
return 2;
}
const char *codec_name = argv[1];
const char *blob_path = argv[2];
size_t win_size = (size_t)strtoull(argv[3], NULL, 0);
long trials = strtol(argv[4], NULL, 0);
double ber = 0;
long burst_len = 0, burst_count = 0;
int is_burst = 0;
if (!strcmp(argv[5], "--ber") && argc > 6)
ber = strtod(argv[6], NULL);
else if (!strcmp(argv[5], "--burst") && argc > 6) {
is_burst = 1;
burst_len = strtol(argv[6], NULL, 0);
char *comma = strchr(argv[6], ',');
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
} else {
fprintf(stderr, "uep_diag: need --ber X or --burst L,C\n");
return 2;
}
FILE *f = fopen(blob_path, "rb");
if (!f) {
fprintf(stderr, "uep_diag: cannot open %s\n", blob_path);
return 2;
}
fseek(f, 0, SEEK_END);
long file_len = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *file = (uint8_t *)malloc((size_t)file_len);
if (!file || fread(file, 1, (size_t)file_len, f) != (size_t)file_len)
return 2;
fclose(f);
ecc_codec_t *c = NULL;
/* parse the codec name the same way bench does */
int cb, th, tl;
if (sscanf(codec_name, "uep-c%d-h%d-l%d", &cb, &th, &tl) != 3) {
fprintf(stderr, "uep_diag: bad codec %s\n", codec_name);
return 2;
}
c = uep_new(cb, th, tl);
if (!c) {
fprintf(stderr, "uep_diag: uep_new failed\n");
return 2;
}
uint8_t *win = (uint8_t *)malloc(win_size);
uint8_t *out = (uint8_t *)malloc(win_size);
uint8_t *stored = NULL, *rx = NULL;
long whole = 0, prefix = 0;
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
for (long tr = 0; tr < trials; tr++) {
size_t off = (size_t)(xr() % ((size_t)file_len - win_size + 1));
memcpy(win, file + off, win_size);
size_t slen = c->encode(c, win, win_size, &stored);
if (!slen) {
fprintf(stderr, "uep_diag: encode failed\n");
return 2;
}
if (tr == 0) {
rx = (uint8_t *)malloc(slen);
if (!rx)
return 2;
}
memcpy(rx, stored, slen);
if (is_burst) {
for (long b = 0; b < burst_count; b++) {
if ((size_t)burst_len >= slen)
continue;
size_t start =
(size_t)(xr() % (slen - (size_t)burst_len + 1));
for (long k = 0; k < burst_len; k++)
rx[start + k] = (uint8_t)(xr() & 0xff);
}
} else {
for (size_t i = 0; i < slen; i++) {
uint8_t m = 0;
for (int b = 0; b < 8; b++)
if (xr() < ber_thr)
m |= (uint8_t)(1u << b);
rx[i] ^= m;
}
}
int mask = uep_decode_parts(c, rx, slen, win_size, out);
if (mask == 3 && memcmp(out, win, win_size) == 0)
whole++;
if (mask & 1)
prefix++;
free(stored);
stored = NULL;
}
printf("%s %s trials=%ld whole=%.4f prefix=%.4f overhead=%.2f%%\n",
codec_name, is_burst ? "burst" : "ber", trials,
(double)whole / (double)trials, (double)prefix / (double)trials,
c->overhead * 100.0);
return 0;
}
-50
View File
@@ -1,50 +0,0 @@
# experiments/Makefile - prototypes for the lzply compression research.
# Built with max cores via -j; each tool is standalone: `tool c in out`,
# `tool d in out`. Shared rANS core in rans.o.
CC = gcc
CFLAGS = -O3 -Wall -Wextra -march=native
LDLIBS = -llz -lm
TOOLS = rans_tool lzrans bwt ppm dict bchcheck
all: $(TOOLS)
rans.o: rans.c rans.h
$(CC) $(CFLAGS) -c -o $@ rans.c
rans_tool: rans_tool.o rans.o
$(CC) $(CFLAGS) -o $@ rans_tool.o rans.o
lzrans.o: lzrans.c rans.h
$(CC) $(CFLAGS) -c -o $@ lzrans.c
lzrans: lzrans.o rans.o
$(CC) $(CFLAGS) -o $@ lzrans.o rans.o
bwt.o: bwt.c rans.h
$(CC) $(CFLAGS) -c -o $@ bwt.c
bwt: bwt.o rans.o
$(CC) $(CFLAGS) -o $@ bwt.o rans.o
ppm.o: ppm.c
$(CC) $(CFLAGS) -c -o $@ ppm.c
ppm: ppm.o
$(CC) $(CFLAGS) -o $@ ppm.o $(LDLIBS)
dict.o: dict.c
$(CC) $(CFLAGS) -c -o $@ dict.c
dict: dict.o
$(CC) $(CFLAGS) -o $@ dict.o
bchcheck.o: bchcheck.c ../bch.h
$(CC) $(CFLAGS) -I.. -c -o $@ bchcheck.c
bchcheck: bchcheck.o ../bch.o ../bch_polys.h
$(CC) $(CFLAGS) -o $@ bchcheck.o ../bch.o
clean:
rm -f $(TOOLS) *.o
.PHONY: all clean
-134
View File
@@ -1,134 +0,0 @@
# lzply compression experiments (branch experiments/comp)
Prototypes for open-ended compression research. Each tool is standalone:
`tool c|o in out`, `tool d in out`. Shared rANS core in rans.[ch].
`bench.py <name> <enc> <dec> [corpora...]` times (best of 3), sizes,
and sha256-verifies round-trips; `bench1.py` is the single-run variant
(for slow tools); CSVs land in results/.
## Corpora (built by mkcorpora.py, deterministic per machine)
- text: 8 MiB UTF-8 docs from /usr/share/doc + common-licenses
- code: 8 MiB C headers (/usr/include) + this repo's sources
- bin: 8 MiB ELF binaries from /bin + /usr/bin
- mixed: 8 MiB round-robin 64 KiB chunks of text+code+bin
- rand: 4 MiB /dev/urandom (seed 1234), incompressible control
Corpora are NOT committed (regenerate with mkcorpora.py).
All ratios below are compressed/orig %; speeds are MB/s (orig bytes).
## Baseline: lzip (the current lzply stage; same liblz, same levels)
| tool | text | code | bin | mixed | rand | enc MB/s | dec MB/s |
|---|---|---|---|---|---|---|---|
| lzip -1 | 6.22 | 15.13 | 37.83 | 21.58 | 101.36 | 1.4-9.1 | 8.9-71.8 |
| lzip -6 | 3.56 | 9.38 | 32.61 | 17.41 | 101.36 | 0.9-2.3 | 7.9-71.4 |
| lzip -9 | 3.44 | 9.05 | 32.53 | 17.17 | 101.36 | 0.8-1.4 | 9.0-70.3 |
References: xz -6 ~= lzip -6 (text 3.51, code 9.20, bin 32.59,
mixed 17.30); zstd -19 text 3.63, code 9.48, bin 34.81, mixed 18.31;
gzip -9 text 23.48, code 16.40, bin 44.14, mixed 30.06;
bzip2 -9 text 9.25, code 12.55, bin 40.22, mixed 23.53,
dec only 5-9 MB/s.
## ANS: rANS order-0 (rans_tool) — REJECT as standalone, KEEP core
Static per-file freqs, 12-bit probs. Enc 30-38 MB/s, dec 47-62 MB/s,
RSS ~20 MB, but no LZ stage: text 64.40, code 67.62, bin 77.14,
mixed 78.11, rand 100.46. The core is the entropy stage for the BWT
and LZ prototypes below. (Two real bugs found and fixed in the core:
renormalisation threshold must be (L>>12)*f<<8 or the decoder
over-reads; the emitted stream can exceed n bytes, scratch is 2n+64.)
## LZ77 + rANS (lzrans) — REJECT as a lzip replacement
Hash-chain finder, 1 MiB window, lazy (`c`) and optimal-parse (`o`)
modes, deflate-style length codes, log2 distance codes, litlen/dist
rANS streams + raw extra bits.
| mode | text | code | bin | mixed | rand | enc | dec | RSS |
|---|---|---|---|---|---|---|---|---|
| lazy | 6.26 | 13.52 | 41.84 | 23.15 | 100.48 | 0.5-4.4 | 26-73 | 44 MB |
| optimal | 6.19 | 13.05 | — | — | — | 0.4-1.0 | 64-73 | 173 MB |
Optimal parsing recovers only ~1-3% relative, so the gap is not
parsing: it is LZMA's adaptive context entropy model plus deeper
match search and a larger dictionary. A static-table rANS cannot
close a ~75% relative gap on text.
## BWT + MTF + run tokens + rANS (bwt) — REJECT as a lzip replacement
Suffix array by cyclic doubling (see the linear-vs-rotation trap
below), MTF, runs >=4 tokenised as (value, 256, k), 257-symbol rANS.
| corpus | ratio | enc | dec |
|---|---|---|---|
| text | 6.35 | 177 s (0.05 MB/s) | 5.3 MB/s |
| code | 12.31 | 173 s | 6.3 MB/s |
| bin | 42.76 | 137 s | 5.9 MB/s |
| mixed | (bench running) | | |
| rand | (bench running) | | |
RSS ~200 MB. Beats bzip2 on text (6.35 vs 9.25), ~ties on code
(12.31 vs 12.55), loses on bin (42.76 vs 40.22); loses to lzip
everywhere by a wide margin. Encode is ~3 min/8 MB (doubling SA is
memory-latency-bound over 160 MB of rank arrays); decode is 5-6 MB/s
(LF-walk random access).
GOTCHA (real bug, fixed): a linear suffix sort is NOT rotation
order — "a" < "a bandana" linearly, but cyclically
"a bandanabanan" < "abanana bandan". A sentinel does not fix it
("a$" < "a bandana$" truncates the comparison). The SA must use
cyclic doubling (rank[(i+k) % n]).
## PPM order-2 + arithmetic coding (ppm) — REJECT
Order-2/1/0 contexts, escape mass = distinct-symbol count,
Witten-Neal-Cleary 32-bit arithmetic coder, counts updated in all
levels after every symbol. RSS ~80 MB.
| corpus | ratio | enc MB/s | dec MB/s |
|---|---|---|---|
| text | 32.84 | 6.3 | 3.9 |
| code | 30.82 | 6.3 | 4.1 |
| mixed | 39.18 | 4.8 | 3.2 |
Far behind lzip and slow: the bit-level coder plus 256-wide level
scans cost ~6 MB/s encode, ~4 MB/s decode. A simple order-2 PPM
with heavy escape mass is nowhere near PPMd-class.
## Dictionary transform + lzip (dict) — CONDITIONAL, code only
Per-file word dictionary (top 4096 words by saving, transmitted in
the header), words -> 3-byte codes, then lzip -6. RSS ~32 MB.
| corpus | dict+lzip6 | plain lzip6 | delta |
|---|---|---|---|
| text | 3.58 | 3.56 | +0.5% worse |
| code | 9.19 | 9.38 | -2.1% BETTER |
| bin | 33.30 | 32.61 | +2.1% worse |
| mixed | 17.65 | 17.41 | +1.4% worse |
| rand | 101.73 | 101.36 | worse |
Only code wins (+2.1%): long repeated identifiers survive as codes
better than as LZ matches. Everywhere else the dictionary costs
more than it saves (lzip already captures word repeats). Not a
default; a code-only optional preprocessing stage at most.
(Gotcha fixed during the build: words are sorted by count, so the
saving filter must `continue`, not `break`, or a short frequent
word like "the" discards the whole dictionary.)
## BCH end-to-end (bchcheck) — winners survive error correction
Blob -> BCH(t=8, lzply -e 4 level) -> flip N bits -> decode ->
decompress -> sha256 check.
- dict+lzip code blob (770,519 B): poly 0050, stored 770,563
(+44 B parity, 0.006%). 8 flips -> 8 corrected, full pipeline
recovers bit-identical. 32 flips -> decode FAIL (exceeds t=8 per
block; honest failure mode).
- plain lzip6 code blob (787,213 B): 8 flips -> 8 corrected,
recovered + decoded bit-identical.
## Verdicts (bottom line)
- No family beats lzip on ratio. lzip/LZMA's adaptive entropy
model + deep match search + large dictionary is very hard to beat
with a from-scratch prototype in this scope.
- KEEP: the rANS core (fast, correct, reusable as an entropy stage).
- CONDITIONAL: dict transform, code-only (+2.1% on code).
- REJECT: lzrans (lazy + optimal), BWT, PPM order-2, rANS order-0
standalone. Honest negatives, numbers above.
- Test totals: 334 timed bench invocations, all sha256-verified OK
(plus ~25 manual small-input round-trips and 3 BCH runs: 2 pass,
1 expected fail at 32 flips).
## Notes / environment
- hot_newyork (172.93.49.176), 8 cores, 30 GB RAM; server load was
10-17 during the runs (shared with other agents), so absolute
MB/s figures are load-dependent; ratios are exact.
- hot_chicago verification pending: its SSH stopped accepting new
sessions Dec 2 (sshd can't fork under load); a retry agent is
probing every 15 min. No Chicago numbers yet.
- The other lz_rs/deep-repair coordinator works in /opt/lzply/src
and /root/lzrs-verify/lzply; untouched by this work. No
Reed-Solomon was (re-)implemented here.
-88
View File
@@ -1,88 +0,0 @@
/* bchcheck.c - BCH end-to-end corruption test for experiment blobs.
* Takes a compressed blob, BCH-encodes it (t=8 by default, the lzply
* -e 4 level; largest t=8 poly if the blob exceeds one m=22 block),
* flips N random bits (seeded), decodes, and writes the recovered
* blob. Exit 0 if the recovered blob is byte-identical to the input,
* 1 if decode failed or the blob differs, 2 on usage/IO error.
* Usage: bchcheck blob nflips seed out [t]
* The caller then decompresses `out` with the prototype and checks
* the sha256 round-trip, proving the compressed stream survives BCH.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "bch.h"
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
/* Largest-capacity poly with the requested t (m=22 wins). */
static const bch_poly_t *largest_t_poly(int t) {
const bch_poly_t *best = NULL;
size_t bestcap = 0;
for (uint16_t id = 0x0001; id <= 0x0052; id++) {
const bch_poly_t *p = bch_poly_by_id(id);
if (!p || p->t != t) continue;
size_t cap = bch_max_data(p);
if (cap > bestcap) { bestcap = cap; best = p; }
}
return best;
}
int main(int argc, char **argv) {
if (argc < 5 || argc > 6) {
fprintf(stderr, "usage: %s blob nflips seed out [t]\n", argv[0]);
return 2;
}
int t = argc == 6 ? atoi(argv[5]) : 8;
long nflips = atol(argv[2]);
unsigned seed = (unsigned)atoi(argv[3]);
size_t n;
uint8_t *blob = slurp(argv[1], &n);
const bch_poly_t *poly = bch_poly_for_data(n, t);
if (!poly) poly = largest_t_poly(t);
if (!poly) { fprintf(stderr, "bchcheck: no poly for t=%d\n", t); return 2; }
size_t slen = bch_encoded_len(n, poly);
uint8_t *stored = malloc(slen ? slen : 1);
uint8_t *rec = malloc(n ? n : 1);
if (!stored || !rec) return 2;
if (bch_encode(blob, n, poly, stored) != slen) {
fprintf(stderr, "bchcheck: encode failed\n");
return 2;
}
/* xorshift64 PRNG for flip positions (seeded, deterministic) */
uint64_t xs = (uint64_t)seed * 0x9E3779B97F4A7C15ULL + 0x123456789ULL;
for (long k = 0; k < nflips; k++) {
xs ^= xs << 13; xs ^= xs >> 7; xs ^= xs << 17;
size_t bit = (size_t)(xs % (uint64_t)(slen * 8));
stored[bit / 8] ^= (uint8_t)(0x80u >> (bit % 8));
}
int corrected = 0;
int rc = bch_decode(stored, slen, n, poly, rec, &corrected);
fprintf(stderr, "bchcheck: poly=%04x blob=%zu stored=%zu overhead=%.1f%% "
"flips=%ld corrected=%d decode=%s\n",
poly->id, n, slen, 100.0 * (double)(slen - n) / (double)n,
nflips, corrected, rc == 0 ? "OK" : "FAIL");
if (rc != 0) return 1;
FILE *f = fopen(argv[4], "wb");
if (!f) { perror(argv[4]); return 2; }
if (n && fwrite(rec, 1, n, f) != n) return 2;
fclose(f);
if (memcmp(blob, rec, n) != 0) {
fprintf(stderr, "bchcheck: recovered blob DIFFERS\n");
return 1;
}
return 0;
}
-84
View File
@@ -1,84 +0,0 @@
#!/usr/bin/env python3
"""bench.py <name> <enc-template> <dec-template> [corpus...]
Templates use {in} {out} {dec}; run via /bin/sh. Times encode/decode
(wall, best of 3 for encode, best of 3 for decode), records ratio,
MB/s, sha256 round-trip. Appends CSV rows to results/<name>.csv and
prints a table. Encode failure on a corpus records 'FAIL'.
"""
import subprocess, sys, os, time, hashlib, csv
EXP = os.path.dirname(os.path.abspath(__file__))
CORP = os.path.join(EXP, "corpora")
RES = os.path.join(EXP, "results")
TMP = "/tmp/expbench"
os.makedirs(TMP, exist_ok=True)
os.makedirs(RES, exist_ok=True)
def sha(p):
h = hashlib.sha256()
with open(p, "rb") as fh:
for c in iter(lambda: fh.read(1 << 20), b""):
h.update(c)
return h.hexdigest()
def run(cmd, timeout=600):
t0 = time.perf_counter()
r = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=timeout)
return r.returncode, time.perf_counter() - t0
def bench_one(name, enc, dec, corpus):
src = os.path.join(CORP, corpus)
n = os.path.getsize(src)
want = sha(src)
out = os.path.join(TMP, name + ".out")
decf = os.path.join(TMP, name + ".dec")
for f in (out, decf):
if os.path.exists(f):
os.unlink(f)
best_enc = None
for _ in range(3):
rc, dt = run(enc.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
return (corpus, n, None, None, None, "ENCFAIL")
best_enc = dt if best_enc is None else min(best_enc, dt)
csize = os.path.getsize(out)
best_dec = None
for _ in range(3):
if os.path.exists(decf):
os.unlink(decf)
rc, dt = run(dec.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
return (corpus, n, csize, None, None, "DECFAIL")
best_dec = dt if best_dec is None else min(best_dec, dt)
ok = sha(decf) == want
return (corpus, n, csize, best_enc, best_dec, "OK" if ok else "MISMATCH")
def main():
name, enc, dec = sys.argv[1], sys.argv[2], sys.argv[3]
corpora = sys.argv[4:] or ["text", "code", "bin", "mixed", "rand"]
csvp = os.path.join(RES, name + ".csv")
new = not os.path.exists(csvp)
print(f"== {name}: enc=[{enc}] dec=[{dec}]")
print(f"{'corpus':8s} {'orig':>9s} {'comp':>9s} {'ratio%':>7s} {'encMB/s':>8s} {'decMB/s':>8s} status")
with open(csvp, "a", newline="") as fh:
w = csv.writer(fh)
if new:
w.writerow(["tool", "corpus", "orig", "comp", "ratio_pct",
"enc_s", "dec_s", "enc_MBs", "dec_MBs", "status"])
for c in corpora:
corpus, n, cs, es, ds, st = bench_one(name, enc, dec, c)
if cs is None:
print(f"{c:8s} {n:9d} {'-':>9s} {'-':>7s} {'-':>8s} {'-':>8s} {st}")
w.writerow([name, c, n, "", "", "", "", "", "", st])
continue
ratio = 100.0 * cs / n
emb = n / 1e6 / es if es else 0
dmb = n / 1e6 / ds if ds else 0
print(f"{c:8s} {n:9d} {cs:9d} {ratio:7.2f} {emb:8.1f} {dmb:8.1f} {st}")
w.writerow([name, c, n, cs, f"{ratio:.2f}", f"{es:.3f}", f"{ds:.3f}",
f"{emb:.1f}", f"{dmb:.1f}", st])
print("csv: " + csvp)
if __name__ == "__main__":
main()
-71
View File
@@ -1,71 +0,0 @@
#!/usr/bin/env python3
"""bench1.py: single-run variant of bench.py (for slow tools like bwt).
Usage: bench1.py <name> <enc-template> <dec-template> [corpus...]
Appends to results/<name>.csv and prints one line per corpus."""
import subprocess, sys, os, time, hashlib, csv
EXP = os.path.dirname(os.path.abspath(__file__))
CORP = os.path.join(EXP, "corpora")
RES = os.path.join(EXP, "results")
TMP = "/tmp/expbench"
os.makedirs(TMP, exist_ok=True)
os.makedirs(RES, exist_ok=True)
def sha(p):
h = hashlib.sha256()
with open(p, "rb") as fh:
for c in iter(lambda: fh.read(1 << 20), b""):
h.update(c)
return h.hexdigest()
def run(cmd, timeout=3600):
t0 = time.perf_counter()
r = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=timeout)
return r.returncode, time.perf_counter() - t0
def main():
name, enc, dec = sys.argv[1], sys.argv[2], sys.argv[3]
corpora = sys.argv[4:] or ["text", "code", "bin", "mixed", "rand"]
csvp = os.path.join(RES, name + ".csv")
new = not os.path.exists(csvp)
print(f"== {name} (single run)", flush=True)
with open(csvp, "a", newline="") as fh:
w = csv.writer(fh)
if new:
w.writerow(["tool", "corpus", "orig", "comp", "ratio_pct",
"enc_s", "dec_s", "enc_MBs", "dec_MBs", "status"])
for c in corpora:
src = os.path.join(CORP, c)
n = os.path.getsize(src)
want = sha(src)
out = os.path.join(TMP, name + ".out")
decf = os.path.join(TMP, name + ".dec")
for f in (out, decf):
if os.path.exists(f):
os.unlink(f)
rc, es = run(enc.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
print(f"{c}: ENCFAIL", flush=True)
w.writerow([name, c, n, "", "", "", "", "", "", "ENCFAIL"])
continue
cs = os.path.getsize(out)
if os.path.exists(decf):
os.unlink(decf)
rc, ds = run(dec.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
print(f"{c}: DECFAIL", flush=True)
w.writerow([name, c, n, cs, "", "", "", "", "", "DECFAIL"])
continue
ok = sha(decf) == want
st = "OK" if ok else "MISMATCH"
ratio = 100.0 * cs / n
print(f"{c:8s} {n:9d} {cs:9d} {ratio:6.2f}% enc {es:7.1f}s "
f"({n/1e6/es:5.1f} MB/s) dec {ds:6.1f}s ({n/1e6/ds:5.1f} MB/s) {st}",
flush=True)
w.writerow([name, c, n, cs, f"{ratio:.2f}", f"{es:.3f}", f"{ds:.3f}",
f"{n/1e6/es:.1f}", f"{n/1e6/ds:.1f}", st])
print("csv: " + csvp, flush=True)
if __name__ == "__main__":
main()
-273
View File
@@ -1,273 +0,0 @@
/* bwt.c - BWT + MTF + run-length tokens + rANS prototype.
* Classic bzip2-style pipeline, written from scratch: suffix array by
* doubling with counting sort, Burrows-Wheeler transform, move-to-front,
* runs of >=4 identical MTF values tokenised as (value, 256, k),
* rANS over a 257-symbol alphabet.
* Usage: bwt c in out | bwt d in out
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "rans.h"
#define NSYM 257
#define RUN_SYM 256
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
static void put32(uint8_t *p, uint32_t v) {
p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8);
p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
}
static uint32_t get32(const uint8_t *p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
/* Counting-sort SA by key array key[SA[i]] (keys in [0, kmax]).
* sa2 is scratch. */
static void csort(int32_t *sa, int32_t *sa2, const int32_t *key, size_t n,
int32_t kmax, int32_t *cnt) {
memset(cnt, 0, (size_t)(kmax + 1) * sizeof *cnt);
for (size_t i = 0; i < n; i++) cnt[key[sa[i]]]++;
int32_t sum = 0;
for (int32_t k = 0; k <= kmax; k++) {
int32_t c = cnt[k];
cnt[k] = sum;
sum += c;
}
for (size_t i = 0; i < n; i++) {
int32_t s = sa[i];
sa2[cnt[key[s]]++] = s;
}
memcpy(sa, sa2, n * sizeof *sa);
}
/* Suffix array of the CYCLIC rotations, by doubling with wraparound
* rank lookups: rotation i is compared via data[i+k mod n], so the
* order is rotation order (what BWT needs), not linear-suffix order.
* A linear sort puts "a" before "a bandana", but cyclically
* "a bandanabanan" < "abanana bandan"; a sentinel does not fix this
* either ("a$" < "a bandana$" truncates the comparison). Periodic
* rotations stay tied, which is harmless: identical rotations have
* identical BWT chars. */
static int32_t *build_sa(const uint8_t *d, size_t n) {
int32_t *sa = malloc(n * sizeof *sa);
int32_t *sa2 = malloc(n * sizeof *sa2);
int32_t *rank = malloc(n * sizeof *rank);
int32_t *tmp = malloc(n * sizeof *tmp);
int32_t *key = malloc(n * sizeof *key);
int32_t *cnt = malloc((n + 258) * sizeof *cnt);
if (!sa || !sa2 || !rank || !tmp || !key || !cnt) exit(2);
int32_t maxrank = 0;
for (size_t i = 0; i < n; i++) {
sa[i] = (int32_t)i;
rank[i] = d[i];
if (d[i] > maxrank) maxrank = d[i];
}
for (size_t k = 1; k < n; k *= 2) {
/* sort by second key rank[(i+k) % n], then first key rank[i];
* (i+k) % n without division: i+k < 2n always (k < n). */
for (size_t i = 0; i + k < n; i++) key[i] = rank[i + k] + 1;
for (size_t i = n - k; i < n; i++) key[i] = rank[i + k - n] + 1;
csort(sa, sa2, key, n, maxrank + 1, cnt);
for (size_t i = 0; i < n; i++) key[i] = rank[i] + 1;
csort(sa, sa2, key, n, maxrank + 1, cnt);
tmp[sa[0]] = 0;
int32_t r = 0;
for (size_t i = 1; i < n; i++) {
int32_t x = sa[i - 1], y = sa[i];
size_t x2 = (size_t)x + k; if (x2 >= n) x2 -= n;
size_t y2 = (size_t)y + k; if (y2 >= n) y2 -= n;
if (rank[x] != rank[y] || rank[x2] != rank[y2]) r++;
tmp[y] = r;
}
memcpy(rank, tmp, n * sizeof *rank);
maxrank = r;
if (maxrank == (int32_t)n - 1) break;
}
free(sa2); free(rank); free(tmp); free(key); free(cnt);
return sa;
}
static int encode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
uint32_t primary = 0;
uint8_t *bwt = malloc(n ? n : 1);
if (!bwt) return 2;
if (n > 0) {
int32_t *sa = build_sa(in, n);
for (size_t i = 0; i < n; i++) {
size_t sv = (size_t)sa[i];
if (sv == 0) primary = (uint32_t)i;
bwt[i] = in[(sv + n - 1) % n];
}
free(sa);
}
/* MTF */
uint8_t *mtf = malloc(n ? n : 1);
uint8_t lst[256];
for (int i = 0; i < 256; i++) lst[i] = (uint8_t)i;
for (size_t i = 0; i < n; i++) {
uint8_t c = bwt[i];
int pos = 0;
while (lst[pos] != c) pos++;
mtf[i] = (uint8_t)pos;
memmove(lst + 1, lst, (size_t)pos);
lst[0] = c;
}
free(bwt);
/* run tokenisation into 257-symbol stream */
uint16_t *tok = malloc((2 * n + 2) * sizeof *tok);
if (!tok) return 2;
size_t nt = 0, i = 0;
while (i < n) {
size_t j = i + 1;
while (j < n && mtf[j] == mtf[i]) j++;
size_t run = j - i;
if (run < 4) {
for (size_t k = 0; k < run; k++) tok[nt++] = mtf[i];
} else {
tok[nt++] = mtf[i];
size_t rem = run - 1;
while (rem > 0) {
size_t chunk = rem > 255 ? 255 : rem;
tok[nt++] = RUN_SYM;
tok[nt++] = (uint16_t)chunk;
rem -= chunk;
}
}
i = j;
}
free(mtf);
uint16_t freq[NSYM];
rans_freq_n(tok, nt, NSYM, freq);
uint8_t *stream = malloc(2 * nt + 64);
if (!stream) return 2;
size_t slen = rans_encode_raw_n(tok, nt, freq, NSYM, stream);
size_t hdr = 4 + 4 + 4 + 4 + NSYM * 2;
uint8_t *out = malloc(hdr + slen);
if (!out) return 2;
uint8_t *p = out;
memcpy(p, "BWTX", 4); p += 4;
put32(p, (uint32_t)n); p += 4;
put32(p, primary); p += 4;
put32(p, (uint32_t)nt); p += 4;
for (int s = 0; s < NSYM; s++) {
p[0] = (uint8_t)freq[s]; p[1] = (uint8_t)(freq[s] >> 8); p += 2;
}
memcpy(p, stream, slen); p += slen;
spit(outpath, out, (size_t)(p - out));
return 0;
}
static int decode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
size_t hdr = 4 + 4 + 4 + 4 + NSYM * 2;
if (n < hdr || memcmp(in, "BWTX", 4) != 0) {
fprintf(stderr, "bwt: bad magic/header\n");
return 3;
}
const uint8_t *p = in + 4;
uint32_t orig = get32(p); p += 4;
uint32_t primary = get32(p); p += 4;
uint32_t nt = get32(p); p += 4;
uint16_t freq[NSYM];
for (int s = 0; s < NSYM; s++) {
freq[s] = (uint16_t)(p[0] | (p[1] << 8)); p += 2;
}
uint16_t *tok = malloc((nt ? nt : 1) * sizeof *tok);
if (!tok) return 2;
if (rans_decode_raw_n(p, n - hdr, freq, NSYM, tok, nt) != 0) {
fprintf(stderr, "bwt: token stream corrupt\n");
return 3;
}
/* expand runs to MTF values */
uint8_t *mtf = malloc(orig ? orig : 1);
if (!mtf) return 2;
size_t m = 0;
uint8_t last = 0;
for (uint32_t i = 0; i < nt; i++) {
uint16_t s = tok[i];
if (s == RUN_SYM) {
if (i + 1 >= nt) { fprintf(stderr, "bwt: truncated run\n"); return 3; }
uint16_t k = tok[++i];
if (m + k > orig) { fprintf(stderr, "bwt: run overrun\n"); return 3; }
memset(mtf + m, last, k);
m += k;
} else {
if (m >= orig) { fprintf(stderr, "bwt: mtf overrun\n"); return 3; }
last = (uint8_t)s;
mtf[m++] = last;
}
}
if (m != orig) { fprintf(stderr, "bwt: short mtf %zu != %u\n", m, orig); return 3; }
free(tok);
/* inverse MTF */
uint8_t *bwt = malloc(orig ? orig : 1);
uint8_t lst[256];
for (int i = 0; i < 256; i++) lst[i] = (uint8_t)i;
for (size_t k = 0; k < orig; k++) {
uint8_t c = lst[mtf[k]];
bwt[k] = c;
memmove(lst + 1, lst, mtf[k]);
lst[0] = c;
}
free(mtf);
/* inverse BWT via LF-mapping */
uint8_t *out = malloc(orig ? orig : 1);
if (!out) return 2;
if (orig > 0) {
int32_t cnt[256] = {0};
for (size_t k = 0; k < orig; k++) cnt[bwt[k]]++;
int32_t C[256];
int32_t sum = 0;
for (int c = 0; c < 256; c++) { C[c] = sum; sum += cnt[c]; }
int32_t *lf = malloc(orig * sizeof *lf);
if (!lf) return 2;
int32_t occ[256] = {0};
for (size_t k = 0; k < orig; k++) {
uint8_t c = bwt[k];
lf[k] = C[c] + occ[c]++;
}
size_t idx = primary;
for (size_t k = orig; k-- > 0;) {
out[k] = bwt[idx];
idx = (size_t)lf[idx];
}
free(lf);
}
spit(outpath, out, orig);
return 0;
}
int main(int argc, char **argv) {
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
return 1;
}
return argv[1][0] == 'c' ? encode(argv[2], argv[3])
: decode(argv[2], argv[3]);
}
-260
View File
@@ -1,260 +0,0 @@
/* dict.c - word-dictionary transform (preprocessing stage for lzip).
* Builds a per-file dictionary of the most frequent words (alnum runs
* of length >= 3), replaces them with 2-byte codes, then the caller
* pipes the output through lzip. The dictionary is transmitted in
* the header, so the cost is honest.
* Format: magic "DICT", u32 orig_len, u16 ndict, then ndict entries
* (u8 len, bytes), then the transformed stream: 0xFF escape byte
* introduces a 2-byte code (little-endian); a literal 0xFF in the
* data is escaped as 0xFF 0xFF 0xFF (escape + code 0xFFFF = literal
* 0xFF); other bytes pass through. Words are maximal [A-Za-z0-9_]
* runs; only words in the dictionary are replaced.
* Usage: dict c in out | dict d in out
* (then: lzip -6 transformed; decode: lzip -d | dict d)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define ESC 0xFF
#define MAX_DICT 4096
#define MIN_WORD 3
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
static int is_word(int c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '_';
}
/* word table entry */
typedef struct { char *w; uint32_t count; } went_t;
static int cmp_count(const void *a, const void *b) {
uint32_t ca = ((const went_t *)a)->count, cb = ((const went_t *)b)->count;
return ca < cb ? 1 : ca > cb ? -1 : 0;
}
static uint32_t hash_str(const char *s, size_t n) {
uint32_t h = 2166136261u;
for (size_t i = 0; i < n; i++) { h ^= (uint8_t)s[i]; h *= 16777619u; }
return h;
}
static int encode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
/* count words in a hash table (open addressing) */
size_t hcap = 1 << 20;
went_t *ht = calloc(hcap, sizeof *ht);
if (!ht) return 2;
size_t i = 0;
while (i < n) {
if (!is_word(in[i])) { i++; continue; }
size_t j = i;
while (j < n && is_word(in[j])) j++;
size_t len = j - i;
if (len >= MIN_WORD) {
uint32_t h = hash_str((char *)in + i, len) & (hcap - 1);
while (ht[h].w) {
if (strlen(ht[h].w) == len &&
memcmp(ht[h].w, in + i, len) == 0) break;
h = (h + 1) & (hcap - 1);
}
if (!ht[h].w) {
ht[h].w = malloc(len + 1);
memcpy(ht[h].w, in + i, len);
ht[h].w[len] = 0;
}
ht[h].count++;
}
i = j;
}
/* collect, sort by count, keep the top MAX_DICT by SAVING:
* saving = count * (len - 3) - (len + 1) [dict cost]; keep > 0 */
went_t *all = malloc(hcap * sizeof *all);
size_t na = 0;
for (size_t k = 0; k < hcap; k++)
if (ht[k].w) all[na++] = ht[k];
qsort(all, na, sizeof *all, cmp_count);
went_t *dict = malloc(MAX_DICT * sizeof *dict);
size_t nd = 0;
for (size_t k = 0; k < na && nd < MAX_DICT; k++) {
size_t len = strlen(all[k].w);
/* code costs 3 bytes (ESC + 2), word costs len; saving per
* occurrence = len - 3; dict entry costs len + 1 bytes */
int64_t saving = (int64_t)all[k].count * ((int64_t)len - 3) -
(int64_t)(len + 1);
if (saving <= 0) continue; /* sorted by count, not saving */
dict[nd++] = all[k];
}
/* rebuild a lookup hash for the kept dictionary: code = index */
size_t lcap = 1 << 16;
int32_t *look = malloc(lcap * sizeof *look);
if (!look) return 2;
for (size_t k = 0; k < lcap; k++) look[k] = -1;
for (size_t k = 0; k < nd; k++) {
size_t len = strlen(dict[k].w);
uint32_t h = hash_str(dict[k].w, len) & (lcap - 1);
while (look[h] >= 0) h = (h + 1) & (lcap - 1);
look[h] = (int32_t)k;
}
/* transform */
size_t cap = n + 1024;
uint8_t *out = malloc(cap);
if (!out) return 2;
size_t o = 0;
/* make room for the dictionary header */
{
size_t hdr = 10;
for (size_t k = 0; k < nd; k++) hdr += 1 + strlen(dict[k].w);
if (cap < hdr + 16) {
cap = hdr + 16;
out = realloc(out, cap);
if (!out) return 2;
}
}
/* header: magic, orig_len, ndict, entries */
memcpy(out, "DICT", 4); o += 4;
out[o++] = (uint8_t)(n & 0xff);
out[o++] = (uint8_t)((n >> 8) & 0xff);
out[o++] = (uint8_t)((n >> 16) & 0xff);
out[o++] = (uint8_t)((n >> 24) & 0xff);
out[o++] = (uint8_t)(nd & 0xff);
out[o++] = (uint8_t)((nd >> 8) & 0xff);
for (size_t k = 0; k < nd; k++) {
size_t len = strlen(dict[k].w);
out[o++] = (uint8_t)len;
memcpy(out + o, dict[k].w, len);
o += len;
}
/* growable body: recompute with room (header already written) */
i = 0;
while (i < n) {
/* ensure room for the worst case (1 byte -> 3 bytes) + slack */
if (o + 8 > cap) {
cap *= 2;
out = realloc(out, cap);
if (!out) return 2;
}
if (is_word(in[i])) {
size_t j = i;
while (j < n && is_word(in[j])) j++;
size_t len = j - i;
int code = -1;
if (len >= MIN_WORD) {
uint32_t h = hash_str((char *)in + i, len) & (lcap - 1);
while (look[h] >= 0) {
int32_t k = look[h];
if (strlen(dict[k].w) == len &&
memcmp(dict[k].w, in + i, len) == 0) { code = k; break; }
h = (h + 1) & (lcap - 1);
}
}
if (code >= 0) {
out[o++] = ESC;
out[o++] = (uint8_t)(code & 0xff);
out[o++] = (uint8_t)((code >> 8) & 0xff);
} else {
memcpy(out + o, in + i, len);
o += len;
}
i = j;
} else {
uint8_t c = in[i++];
if (c == ESC) {
out[o++] = ESC;
out[o++] = 0xFF;
out[o++] = 0xFF;
} else {
out[o++] = c;
}
}
}
spit(outpath, out, o);
fprintf(stderr, "dict: %zu words kept (of %zu distinct)\n", nd, na);
return 0;
}
static int decode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
if (n < 10 || memcmp(in, "DICT", 4) != 0) {
fprintf(stderr, "dict: bad magic/header\n");
return 3;
}
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
uint32_t nd = (uint32_t)in[8] | ((uint32_t)in[9] << 8);
size_t p = 10;
char **dict = malloc((nd ? nd : 1) * sizeof *dict);
if (!dict) return 2;
for (uint32_t k = 0; k < nd; k++) {
if (p >= n) { fprintf(stderr, "dict: truncated dict\n"); return 3; }
size_t len = in[p++];
if (p + len > n) { fprintf(stderr, "dict: truncated dict\n"); return 3; }
dict[k] = malloc(len + 1);
memcpy(dict[k], in + p, len);
dict[k][len] = 0;
p += len;
}
uint8_t *out = malloc(orig ? orig : 1);
if (!out) return 2;
size_t o = 0;
while (p < n) {
uint8_t c = in[p++];
if (c == ESC) {
if (p + 1 >= n) { fprintf(stderr, "dict: truncated code\n"); return 3; }
uint32_t code = (uint32_t)in[p] | ((uint32_t)in[p + 1] << 8);
p += 2;
if (code == 0xFFFF) {
if (o >= orig) return 3;
out[o++] = ESC;
} else {
if (code >= nd) { fprintf(stderr, "dict: bad code\n"); return 3; }
size_t len = strlen(dict[code]);
if (o + len > orig) return 3;
memcpy(out + o, dict[code], len);
o += len;
}
} else {
if (o >= orig) return 3;
out[o++] = c;
}
}
if (o != orig) {
fprintf(stderr, "dict: short output %zu != %u\n", o, orig);
return 3;
}
spit(outpath, out, o);
return 0;
}
int main(int argc, char **argv) {
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
return 1;
}
return argv[1][0] == 'c' ? encode(argv[2], argv[3])
: decode(argv[2], argv[3]);
}
-412
View File
@@ -1,412 +0,0 @@
/* lzrans.c - LZ77 + rANS prototype for the lzply compression research.
* Hash-chain match finder (1 MiB window), lazy matching (`c`) or
* optimal parsing (`o`, DP over match costs; per candidate only its
* full length is considered), deflate-style length codes (29) and
* log2 distance codes (21, dist up to 2^20). Three streams: litlen
* (286 symbols: 0-255 literal, 256-284 length code, 285 end), dist
* (21 symbols), extra bits (raw LSB-first). Each token stream is
* rANS-coded with its own transmitted freq table.
* Usage: lzrans c|o in out | lzrans d in out
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "rans.h"
#define WINDOW (1u << 20)
#define MAX_MATCH 258
#define MIN_MATCH 3
#define HASH_BITS 16
#define HASH_SIZE (1u << HASH_BITS)
#define LITLEN_END 285
static const int len_base[29] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,
43,51,59,67,83,99,115,131,163,195,227,258};
static const int len_extra[29] = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,
4,4,4,4,5,5,5,5,0};
static int len_code_of(int len) {
int c = 0;
while (c < 28 && len >= len_base[c + 1]) c++;
return c;
}
/* dist 1..2^20 -> code 0..19, extra bits = code, base = 1<<code */
static int dist_code_of(uint32_t d) { return 31 - __builtin_clz(d); }
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
static void put32(uint8_t *p, uint32_t v) {
p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8);
p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
}
static uint32_t get32(const uint8_t *p) {
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
/* ---- bit writer (LSB-first) ---- */
typedef struct { uint8_t *buf; size_t len, cap; uint32_t acc; int nbits; } bitw_t;
static void bitw_put(bitw_t *w, uint32_t v, int n) {
w->acc |= v << w->nbits;
w->nbits += n;
while (w->nbits >= 8) {
if (w->len == w->cap) {
w->cap = w->cap ? w->cap * 2 : 4096;
w->buf = realloc(w->buf, w->cap);
if (!w->buf) exit(2);
}
w->buf[w->len++] = (uint8_t)(w->acc & 0xff);
w->acc >>= 8;
w->nbits -= 8;
}
}
static void bitw_flush(bitw_t *w) {
if (w->nbits) {
if (w->len == w->cap) {
w->cap = w->cap ? w->cap * 2 : 4096;
w->buf = realloc(w->buf, w->cap);
if (!w->buf) exit(2);
}
w->buf[w->len++] = (uint8_t)(w->acc & 0xff);
w->acc = 0; w->nbits = 0;
}
}
/* ---- bit reader (LSB-first) ---- */
typedef struct { const uint8_t *buf; size_t len, pos; uint32_t acc; int nbits; } bitr_t;
static uint32_t bitr_get(bitr_t *r, int n) {
while (r->nbits < n) {
uint32_t b = r->pos < r->len ? r->buf[r->pos++] : 0;
r->acc |= b << r->nbits;
r->nbits += 8;
}
uint32_t v = n == 32 ? r->acc : (r->acc & ((n == 0) ? 0u : ((1u << n) - 1)));
r->acc >>= n;
r->nbits -= n;
return v;
}
/* ---- match finder ---- */
typedef struct {
const uint8_t *data;
size_t n;
int32_t head[HASH_SIZE];
int32_t *prev;
} mf_t;
static uint32_t hash4(const uint8_t *p) {
uint32_t v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
return (v * 2654435761u) >> (32 - HASH_BITS);
}
static void mf_insert(mf_t *m, size_t pos) {
if (pos + 4 > m->n) return;
uint32_t h = hash4(m->data + pos);
m->prev[pos] = m->head[h];
m->head[h] = (int32_t)pos;
}
/* Longest match at pos (limit capped by caller). Returns 0 if < 3. */
static int mf_find(mf_t *m, size_t pos, int limit, int max_chain,
int *dist_out) {
if (pos + 4 > m->n) return 0;
uint32_t h = hash4(m->data + pos);
int32_t cand = m->head[h];
int best = 2, bestd = 0, chain = 0;
while (cand >= 0 && chain++ < max_chain) {
size_t c = (size_t)cand;
size_t d = pos - c;
if (d > WINDOW) break;
if (best >= 3) {
/* quick reject: byte at best must match */
if (c + (size_t)best >= m->n ||
m->data[c + best] != m->data[pos + best]) {
cand = m->prev[cand];
continue;
}
}
int l = 0;
while (l < limit && pos + (size_t)l < m->n &&
m->data[c + l] == m->data[pos + l]) l++;
if (l > best) {
best = l; bestd = (int)d;
if (best >= limit) break;
}
cand = m->prev[cand];
}
*dist_out = bestd;
return best >= MIN_MATCH ? best : 0;
}
/* ---- token streams ---- */
typedef struct {
uint16_t *litlen; size_t nlit, clit;
uint16_t *dist; size_t ndist, cdist;
bitw_t bits;
} toks_t;
static void toks_init(toks_t *t, size_t n) {
t->clit = n + 2; t->litlen = malloc(t->clit * 2);
t->cdist = n / 3 + 2; t->dist = malloc(t->cdist * 2);
t->nlit = t->ndist = 0;
memset(&t->bits, 0, sizeof t->bits);
if (!t->litlen || !t->dist) exit(2);
}
static void toks_lit(toks_t *t, uint8_t b) { t->litlen[t->nlit++] = b; }
static void toks_match(toks_t *t, int len, int dist) {
int lc = len_code_of(len);
t->litlen[t->nlit++] = (uint16_t)(256 + lc);
int dc = dist_code_of((uint32_t)dist);
t->dist[t->ndist++] = (uint16_t)dc;
bitw_put(&t->bits, (uint32_t)(len - len_base[lc]), len_extra[lc]);
bitw_put(&t->bits, (uint32_t)(dist - (1 << dc)), dc);
}
/* ---- lazy parse ---- */
static void parse_lazy(mf_t *m, toks_t *t) {
size_t n = m->n, pos = 0;
while (pos < n) {
if (n - pos < MIN_MATCH) { toks_lit(t, m->data[pos++]); continue; }
int d1 = 0;
int l1 = mf_find(m, pos, (int)(n - pos < MAX_MATCH ? n - pos : MAX_MATCH),
128, &d1);
if (l1 >= MIN_MATCH) {
mf_insert(m, pos);
int l2 = 0, d2 = 0;
if (n - (pos + 1) >= MIN_MATCH)
l2 = mf_find(m, pos + 1,
(int)(n - pos - 1 < MAX_MATCH ? n - pos - 1 : MAX_MATCH),
128, &d2);
if (l2 > l1) { toks_lit(t, m->data[pos]); pos++; continue; }
toks_match(t, l1, d1);
for (int k = 1; k < l1; k++) mf_insert(m, pos + (size_t)k);
pos += (size_t)l1;
} else {
toks_lit(t, m->data[pos]);
mf_insert(m, pos);
pos++;
}
}
}
/* ---- optimal parse (DP; per candidate only its full length) ---- */
static void parse_opt(mf_t *m, toks_t *t) {
size_t n = m->n;
double *cost = malloc((n + 1) * sizeof *cost);
int32_t *ch_len = malloc((n + 1) * sizeof *ch_len);
int32_t *ch_dist = malloc((n + 1) * sizeof *ch_dist);
if (!cost || !ch_len || !ch_dist) exit(2);
for (size_t i = 0; i <= n; i++) { cost[i] = 1e100; ch_len[i] = 0; ch_dist[i] = 0; }
cost[0] = 0;
for (size_t i = 0; i < n; i++) {
if (cost[i] < 1e99 && n - i >= MIN_MATCH) {
/* literal */
if (cost[i] + 9.0 < cost[i + 1]) {
cost[i + 1] = cost[i] + 9.0; ch_len[i + 1] = 0;
}
/* matches: walk the chain, full length per candidate */
if (i + 4 <= n) {
uint32_t h = hash4(m->data + i);
int32_t cand = m->head[h];
int chain = 0, best = 2;
int limit = (int)(n - i < MAX_MATCH ? n - i : MAX_MATCH);
while (cand >= 0 && chain++ < 32) {
size_t c = (size_t)cand;
size_t d = i - c;
if (d > WINDOW) break;
if (best >= 3 && (c + (size_t)best >= n ||
m->data[c + best] != m->data[i + best])) {
cand = m->prev[cand];
continue;
}
int l = 0;
while (l < limit && m->data[c + l] == m->data[i + l]) l++;
if (l >= MIN_MATCH && l > 2) {
int lc = len_code_of(l);
int dc = dist_code_of((uint32_t)d);
double mc = cost[i] + 8.0 + len_extra[lc] + 5.0 + dc;
if (mc < cost[i + (size_t)l]) {
cost[i + (size_t)l] = mc;
ch_len[i + (size_t)l] = l;
ch_dist[i + (size_t)l] = (int32_t)d;
}
if (l > best) best = l;
}
cand = m->prev[cand];
}
}
}
mf_insert(m, i);
}
/* reconstruct backwards, then reverse */
size_t pos = n, nt = 0;
uint16_t *rl = malloc((n + 1) * 2);
int32_t *rd = malloc((n + 1) * 4);
int32_t *rlen = malloc((n + 1) * 4);
if (!rl || !rd || !rlen) exit(2);
while (pos > 0) {
int32_t l = ch_len[pos];
if (l == 0) { rl[nt] = m->data[pos - 1]; rlen[nt] = 0; rd[nt] = 0; nt++; pos--; }
else { rl[nt] = 0; rlen[nt] = l; rd[nt] = ch_dist[pos]; nt++; pos -= (size_t)l; }
}
for (size_t k = nt; k-- > 0;) {
if (rlen[k] == 0) toks_lit(t, (uint8_t)rl[k]);
else toks_match(t, rlen[k], rd[k]);
}
free(cost); free(ch_len); free(ch_dist); free(rl); free(rd); free(rlen);
}
static int encode(const char *inpath, const char *outpath, int optimal) {
size_t n;
uint8_t *in = slurp(inpath, &n);
mf_t m;
m.data = in; m.n = n;
memset(m.head, 0xff, sizeof m.head);
m.prev = malloc((n ? n : 1) * sizeof *m.prev);
if (!m.prev) return 2;
toks_t t;
toks_init(&t, n);
if (optimal) parse_opt(&m, &t);
else parse_lazy(&m, &t);
t.litlen[t.nlit++] = LITLEN_END;
bitw_flush(&t.bits);
uint16_t freq_ll[286], freq_d[21];
rans_freq_n(t.litlen, t.nlit, 286, freq_ll);
rans_freq_n(t.dist, t.ndist, 21, freq_d);
uint8_t *s_ll = malloc(2 * t.nlit + 64);
uint8_t *s_d = malloc(2 * t.ndist + 64);
if (!s_ll || !s_d) return 2;
size_t sll_len = rans_encode_raw_n(t.litlen, t.nlit, freq_ll, 286, s_ll);
size_t sd_len = rans_encode_raw_n(t.dist, t.ndist, freq_d, 21, s_d);
size_t hdr = 4 + 4 + 1 + 20 + 286 * 2 + 21 * 2;
size_t total = hdr + sll_len + sd_len + t.bits.len;
uint8_t *out = malloc(total ? total : 1);
if (!out) return 2;
uint8_t *p = out;
memcpy(p, "LZRA", 4); p += 4;
put32(p, (uint32_t)n); p += 4;
*p++ = optimal ? 1 : 0;
put32(p, (uint32_t)t.nlit); p += 4;
put32(p, (uint32_t)t.ndist); p += 4;
put32(p, (uint32_t)t.bits.len); p += 4;
put32(p, (uint32_t)sll_len); p += 4;
put32(p, (uint32_t)sd_len); p += 4;
for (int s = 0; s < 286; s++) { p[0] = (uint8_t)freq_ll[s]; p[1] = (uint8_t)(freq_ll[s] >> 8); p += 2; }
for (int s = 0; s < 21; s++) { p[0] = (uint8_t)freq_d[s]; p[1] = (uint8_t)(freq_d[s] >> 8); p += 2; }
memcpy(p, s_ll, sll_len); p += sll_len;
memcpy(p, s_d, sd_len); p += sd_len;
memcpy(p, t.bits.buf, t.bits.len); p += t.bits.len;
spit(outpath, out, (size_t)(p - out));
return 0;
}
static int decode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
size_t hdr = 4 + 4 + 1 + 20 + 286 * 2 + 21 * 2;
if (n < hdr || memcmp(in, "LZRA", 4) != 0) {
fprintf(stderr, "lzrans: bad magic/header\n");
return 3;
}
const uint8_t *p = in + 4;
uint32_t orig = get32(p); p += 4;
p++; /* mode */
uint32_t nlit = get32(p); p += 4;
uint32_t ndist = get32(p); p += 4;
uint32_t ebits = get32(p); p += 4;
uint32_t sll_len = get32(p); p += 4;
uint32_t sd_len = get32(p); p += 4;
uint16_t freq_ll[286], freq_d[21];
for (int s = 0; s < 286; s++) { freq_ll[s] = (uint16_t)(p[0] | (p[1] << 8)); p += 2; }
for (int s = 0; s < 21; s++) { freq_d[s] = (uint16_t)(p[0] | (p[1] << 8)); p += 2; }
if ((size_t)(p - in) + sll_len + sd_len + ebits != n) {
fprintf(stderr, "lzrans: truncated file\n");
return 3;
}
uint16_t *litlen = malloc((nlit ? nlit : 1) * 2);
uint16_t *dist = malloc((ndist ? ndist : 1) * 2);
if (!litlen || !dist) return 2;
if (rans_decode_raw_n(p, sll_len, freq_ll, 286, litlen, nlit) != 0) {
fprintf(stderr, "lzrans: litlen stream corrupt\n");
return 3;
}
p += sll_len;
if (rans_decode_raw_n(p, sd_len, freq_d, 21, dist, ndist) != 0) {
fprintf(stderr, "lzrans: dist stream corrupt\n");
return 3;
}
p += sd_len;
uint8_t *out = malloc(orig ? orig : 1);
if (!out) return 2;
bitr_t br = { p, ebits, 0, 0, 0 };
size_t opos = 0, di = 0;
for (uint32_t i = 0; i < nlit; i++) {
uint16_t s = litlen[i];
if (s < 256) {
if (opos >= orig) { fprintf(stderr, "lzrans: overrun\n"); return 3; }
out[opos++] = (uint8_t)s;
} else if (s == LITLEN_END) {
break;
} else {
int lc = s - 256;
if (lc < 0 || lc > 28 || di >= ndist) {
fprintf(stderr, "lzrans: bad token\n");
return 3;
}
int len = len_base[lc] + (int)bitr_get(&br, len_extra[lc]);
int dc = dist[di++];
if (dc < 0 || dc > 20) { fprintf(stderr, "lzrans: bad dist\n"); return 3; }
int d = (1 << dc) + (int)bitr_get(&br, dc);
if ((size_t)d > opos || opos + (size_t)len > orig) {
fprintf(stderr, "lzrans: bad match\n");
return 3;
}
for (int k = 0; k < len; k++) {
out[opos] = out[opos - (size_t)d];
opos++;
}
}
}
if (opos != orig) {
fprintf(stderr, "lzrans: short output %zu != %u\n", opos, orig);
return 3;
}
spit(outpath, out, opos);
return 0;
}
int main(int argc, char **argv) {
if (argc != 4) {
fprintf(stderr, "usage: %s c|o|d in out\n", argv[0]);
return 1;
}
if (argv[1][0] == 'c') return encode(argv[2], argv[3], 0);
if (argv[1][0] == 'o') return encode(argv[2], argv[3], 1);
if (argv[1][0] == 'd') return decode(argv[2], argv[3]);
fprintf(stderr, "usage: %s c|o|d in out\n", argv[0]);
return 1;
}
-77
View File
@@ -1,77 +0,0 @@
#!/usr/bin/env python3
"""Build deterministic benchmark corpora on the server. Sizes capped.
text: /usr/share/doc text files + common-licenses (English prose/docs)
code: /usr/include headers + this repo sources (C/Markdown)
bin: ELF binaries from /bin, /usr/bin (executables)
mixed: round-robin 64KiB chunks of text+code+bin
rand: /dev/urandom control (incompressible)
"""
import os, glob, hashlib, random
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "corpora")
CAP = 8 * 1024 * 1024
def collect(patterns, cap, text_only=False):
buf = bytearray()
files = []
for p in patterns:
files += sorted(glob.glob(p, recursive=True))
for f in files:
try:
if not os.path.isfile(f):
continue
with open(f, "rb") as fh:
d = fh.read()
except OSError:
continue
if text_only:
try:
d.decode("utf-8")
except UnicodeDecodeError:
continue
buf += d
if len(buf) >= cap:
break
return bytes(buf[:cap])
def write(name, data):
p = os.path.join(OUT, name)
with open(p, "wb") as fh:
fh.write(data)
print(name + ": " + str(len(data)) + " bytes sha256=" + hashlib.sha256(data).hexdigest()[:16])
text = collect(["/usr/share/doc/**/*", "/usr/share/common-licenses/*"], CAP, text_only=True)
write("text", text)
code = collect(["/usr/include/**/*.h", "/opt/lzply-exp-comp/*.c",
"/opt/lzply-exp-comp/*.h", "/opt/lzply-exp-comp/*.md"], CAP)
write("code", code)
bins = []
for d in ("/bin", "/usr/bin"):
for f in sorted(glob.glob(d + "/*")):
try:
with open(f, "rb") as fh:
h = fh.read(4)
if h[:4] == b"\x7fELF":
bins.append(f)
except OSError:
pass
buf = bytearray()
for f in bins:
with open(f, "rb") as fh:
buf += fh.read()
if len(buf) >= CAP:
break
bindata = bytes(buf[:CAP])
write("bin", bindata)
parts = [text, code, bindata]
m = bytearray()
i = 0
while len(m) < CAP:
for part in parts:
off = (i * 65536) % max(1, len(part) - 65536)
m += part[off:off + 65536]
if len(m) >= CAP:
break
i += 1
write("mixed", bytes(m[:CAP]))
rnd = random.Random(1234).randbytes(4 * 1024 * 1024)
write("rand", rnd)
-349
View File
@@ -1,349 +0,0 @@
/* ppm.c - order-2 PPM + arithmetic coding prototype (context mixing).
* Three context levels (order-2, order-1, order-0) with escape to the
* next level; escape mass = number of distinct symbols seen in the
* context. Order -1 is uniform over 256 symbols. The coder is the
* classic Witten-Neal-Cleary 32-bit arithmetic coder (E1/E2/E3).
* Counts are updated in ALL levels after every symbol, on both sides.
* Usage: ppm c in out | ppm d in out
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define ESC 256
#define NSYM 257
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
/* ---- bit writer (MSB-first) ---- */
typedef struct {
uint8_t *buf; size_t len, cap;
uint32_t acc; int nbits;
} bitw_t;
static void bitw_put(bitw_t *w, int bit) {
w->acc = (w->acc << 1) | (uint32_t)bit;
if (++w->nbits == 8) {
if (w->len == w->cap) {
w->cap = w->cap ? w->cap * 2 : 65536;
w->buf = realloc(w->buf, w->cap);
if (!w->buf) exit(2);
}
w->buf[w->len++] = (uint8_t)w->acc;
w->acc = 0; w->nbits = 0;
}
}
static void bitw_flush(bitw_t *w) {
if (w->nbits) {
w->acc <<= (8 - w->nbits);
if (w->len == w->cap) {
w->cap = w->cap ? w->cap * 2 : 65536;
w->buf = realloc(w->buf, w->cap);
if (!w->buf) exit(2);
}
w->buf[w->len++] = (uint8_t)w->acc;
w->acc = 0; w->nbits = 0;
}
}
/* ---- bit reader (MSB-first, 0 past EOF) ---- */
typedef struct {
const uint8_t *buf; size_t len, pos;
uint32_t acc; int nbits;
} bitr_t;
static int bitr_get(bitr_t *r) {
if (r->nbits == 0) {
uint8_t b = r->pos < r->len ? r->buf[r->pos++] : 0;
r->acc = b; r->nbits = 8;
}
int bit = (int)((r->acc >> 7) & 1);
r->acc <<= 1; r->nbits--;
return bit;
}
/* ---- arithmetic coder ---- */
typedef struct {
uint32_t low, high;
int follow;
bitw_t *w;
} enc_t;
static void enc_bit(enc_t *e, int bit) {
bitw_put(e->w, bit);
while (e->follow > 0) { bitw_put(e->w, !bit); e->follow--; }
}
static void enc_symbol(enc_t *e, uint32_t cum_lo, uint32_t cum_hi, uint32_t total) {
uint64_t range = (uint64_t)(e->high - e->low) + 1;
e->high = e->low + (uint32_t)(range * cum_hi / total) - 1;
e->low = e->low + (uint32_t)(range * cum_lo / total);
for (;;) {
if (e->high < 0x80000000u) {
enc_bit(e, 0);
} else if (e->low >= 0x80000000u) {
enc_bit(e, 1);
e->low -= 0x80000000u; e->high -= 0x80000000u;
} else if (e->low >= 0x40000000u && e->high < 0xC0000000u) {
e->follow++;
e->low -= 0x40000000u; e->high -= 0x40000000u;
} else break;
e->low <<= 1; e->high = (e->high << 1) | 1;
}
}
static void enc_flush(enc_t *e) {
e->follow++;
if (e->low < 0x40000000u) enc_bit(e, 0);
else enc_bit(e, 1);
bitw_flush(e->w);
}
typedef struct {
uint32_t low, high, value;
bitr_t *r;
} dec_t;
static void dec_init(dec_t *d, bitr_t *r) {
d->low = 0; d->high = 0xFFFFFFFFu; d->value = 0; d->r = r;
for (int i = 0; i < 32; i++) d->value = (d->value << 1) | (uint32_t)bitr_get(r);
}
static uint32_t dec_cum(dec_t *d, uint32_t total) {
uint64_t range = (uint64_t)(d->high - d->low) + 1;
return (uint32_t)(((uint64_t)(d->value - d->low + 1) * total - 1) / range);
}
static void dec_update(dec_t *d, uint32_t cum_lo, uint32_t cum_hi, uint32_t total) {
uint64_t range = (uint64_t)(d->high - d->low) + 1;
d->high = d->low + (uint32_t)(range * cum_hi / total) - 1;
d->low = d->low + (uint32_t)(range * cum_lo / total);
for (;;) {
if (d->high < 0x80000000u) {
/* no shift */
} else if (d->low >= 0x80000000u) {
d->value -= 0x80000000u; d->low -= 0x80000000u; d->high -= 0x80000000u;
} else if (d->low >= 0x40000000u && d->high < 0xC0000000u) {
d->value -= 0x40000000u; d->low -= 0x40000000u; d->high -= 0x40000000u;
} else break;
d->low <<= 1; d->high = (d->high << 1) | 1;
d->value = (d->value << 1) | (uint32_t)bitr_get(d->r);
}
}
/* ---- PPM model ----
* cnt0[256], cnt1[256][256], cnt2[65536][256] (uint32), totals and
* distinct-symbol counts per context. ~64 MB for cnt2. */
static uint32_t *cnt2; /* [65536][256] */
static uint32_t cnt1[256][256];
static uint32_t cnt0[256];
static uint32_t tot2[65536];
static uint32_t tot1[256];
static uint32_t tot0;
static uint32_t dist2[65536];
static uint32_t dist1[256];
static uint32_t dist0;
static void model_reset(void) {
memset(cnt1, 0, sizeof cnt1);
memset(cnt0, 0, sizeof cnt0);
memset(tot2, 0, sizeof tot2);
memset(tot1, 0, sizeof tot1);
memset(dist2, 0, sizeof dist2);
memset(dist1, 0, sizeof dist1);
tot0 = 0; dist0 = 0;
if (cnt2) memset(cnt2, 0, (size_t)65536 * 256 * sizeof *cnt2);
}
static void model_update(int b, int p2, int p1) {
uint32_t c2 = (uint32_t)((p2 << 8) | p1);
uint32_t *row2 = cnt2 + (size_t)c2 * 256;
if (row2[b] == 0) dist2[c2]++;
row2[b]++;
tot2[c2]++;
if (cnt1[p1][b] == 0) dist1[p1]++;
cnt1[p1][b]++;
tot1[p1]++;
if (cnt0[b] == 0) dist0++;
cnt0[b]++;
tot0++;
}
/* Cumulative interval of symbol s (0..255) or ESC in a level.
* cnt: per-symbol counts; dist: escape mass; tot: symbol total.
* total = tot + dist. Returns 0 if the symbol has freq 0. */
static int level_interval(const uint32_t *cnt, uint32_t dist, uint32_t tot,
int s, uint32_t *lo, uint32_t *hi, uint32_t *total) {
*total = tot + dist;
uint32_t acc = 0;
if (s == ESC) {
for (int i = 0; i < 256; i++) acc += cnt[i];
*lo = acc; *hi = acc + dist;
return dist > 0;
}
for (int i = 0; i < s; i++) acc += cnt[i];
*lo = acc; *hi = acc + cnt[s];
return cnt[s] > 0;
}
/* Find the symbol for a cum value in a level; fills lo/hi/total. */
static int level_lookup(const uint32_t *cnt, uint32_t dist, uint32_t tot,
uint32_t cum, uint32_t *lo, uint32_t *hi,
uint32_t *total) {
*total = tot + dist;
uint32_t acc = 0;
for (int i = 0; i < 256; i++) {
uint32_t f = cnt[i];
if (cum < acc + f) { *lo = acc; *hi = acc + f; return i; }
acc += f;
}
*lo = acc; *hi = acc + dist;
return ESC;
}
static int encode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
cnt2 = malloc((size_t)65536 * 256 * sizeof *cnt2);
if (!cnt2) return 2;
model_reset();
bitw_t w;
memset(&w, 0, sizeof w);
enc_t e = { 0, 0xFFFFFFFFu, 0, &w };
int p2 = 0, p1 = 0;
for (size_t i = 0; i < n; i++) {
int b = in[i];
uint32_t c2 = (uint32_t)((p2 << 8) | p1);
uint32_t *row2 = cnt2 + (size_t)c2 * 256;
uint32_t lo, hi, total;
int done = 0;
if (tot2[c2] > 0) {
if (level_interval(row2, dist2[c2], tot2[c2], b, &lo, &hi, &total)) {
enc_symbol(&e, lo, hi, total);
done = 1;
} else {
level_interval(row2, dist2[c2], tot2[c2], ESC, &lo, &hi, &total);
enc_symbol(&e, lo, hi, total);
}
}
if (!done && tot1[p1] > 0) {
if (level_interval(cnt1[p1], dist1[p1], tot1[p1], b, &lo, &hi, &total)) {
enc_symbol(&e, lo, hi, total);
done = 1;
} else {
level_interval(cnt1[p1], dist1[p1], tot1[p1], ESC, &lo, &hi, &total);
enc_symbol(&e, lo, hi, total);
}
}
if (!done && tot0 > 0) {
if (level_interval(cnt0, dist0, tot0, b, &lo, &hi, &total)) {
enc_symbol(&e, lo, hi, total);
done = 1;
} else {
level_interval(cnt0, dist0, tot0, ESC, &lo, &hi, &total);
enc_symbol(&e, lo, hi, total);
}
}
if (!done) {
/* order -1: uniform over 256 */
enc_symbol(&e, (uint32_t)b, (uint32_t)b + 1, 256);
}
model_update(b, p2, p1);
p2 = p1; p1 = b;
}
enc_flush(&e);
size_t total_out = 8 + w.len;
uint8_t *out = malloc(total_out ? total_out : 1);
if (!out) return 2;
memcpy(out, "PPM2", 4);
out[4] = (uint8_t)(n & 0xff);
out[5] = (uint8_t)((n >> 8) & 0xff);
out[6] = (uint8_t)((n >> 16) & 0xff);
out[7] = (uint8_t)((n >> 24) & 0xff);
memcpy(out + 8, w.buf, w.len);
spit(outpath, out, total_out);
return 0;
}
static int decode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
if (n < 8 || memcmp(in, "PPM2", 4) != 0) {
fprintf(stderr, "ppm: bad magic/header\n");
return 3;
}
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
cnt2 = malloc((size_t)65536 * 256 * sizeof *cnt2);
if (!cnt2) return 2;
model_reset();
bitr_t br = { in + 8, n - 8, 0, 0, 0 };
dec_t d;
dec_init(&d, &br);
uint8_t *out = malloc(orig ? orig : 1);
if (!out) return 2;
int p2 = 0, p1 = 0;
for (uint32_t i = 0; i < orig; i++) {
int b = -1;
uint32_t c2 = (uint32_t)((p2 << 8) | p1);
uint32_t *row2 = cnt2 + (size_t)c2 * 256;
uint32_t lo, hi, total, cum;
if (tot2[c2] > 0) {
cum = dec_cum(&d, tot2[c2] + dist2[c2]);
int s = level_lookup(row2, dist2[c2], tot2[c2], cum, &lo, &hi, &total);
dec_update(&d, lo, hi, total);
if (s != ESC) b = s;
}
if (b < 0 && tot1[p1] > 0) {
cum = dec_cum(&d, tot1[p1] + dist1[p1]);
int s = level_lookup(cnt1[p1], dist1[p1], tot1[p1], cum, &lo, &hi, &total);
dec_update(&d, lo, hi, total);
if (s != ESC) b = s;
}
if (b < 0 && tot0 > 0) {
cum = dec_cum(&d, tot0 + dist0);
int s = level_lookup(cnt0, dist0, tot0, cum, &lo, &hi, &total);
dec_update(&d, lo, hi, total);
if (s != ESC) b = s;
}
if (b < 0) {
cum = dec_cum(&d, 256);
b = (int)cum;
dec_update(&d, cum, cum + 1, 256);
}
out[i] = (uint8_t)b;
model_update(b, p2, p1);
p2 = p1; p1 = b;
}
spit(outpath, out, orig);
return 0;
}
int main(int argc, char **argv) {
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
return 1;
}
return argv[1][0] == 'c' ? encode(argv[2], argv[3])
: decode(argv[2], argv[3]);
}
-221
View File
@@ -1,221 +0,0 @@
/* rans.c - rANS entropy coder (see rans.h). Standard rANS:
* encode backwards, x in [2^23, 2^32); decode forwards from the
* 4-byte final state stored at the end of the stream. */
#include "rans.h"
#include <stdlib.h>
#include <string.h>
void rans_freq(const uint8_t *in, size_t n, uint16_t *freq) {
uint32_t cnt[256] = {0};
for (size_t i = 0; i < n; i++) cnt[in[i]]++;
uint32_t total = 0;
for (int s = 0; s < 256; s++) {
/* scale counts to PROB_SCALE, present symbols keep >= 1 */
uint32_t f = n ? (uint32_t)(((uint64_t)cnt[s] * RANS_PROB_SCALE) / n) : 0;
if (cnt[s] && f == 0) f = 1;
freq[s] = (uint16_t)f;
total += f;
}
/* Fix the sum to exactly PROB_SCALE by adjusting the largest. */
int mx = 0;
for (int s = 1; s < 256; s++) if (freq[s] > freq[mx]) mx = s;
if (total < RANS_PROB_SCALE) freq[mx] += (uint16_t)(RANS_PROB_SCALE - total);
else if (total > RANS_PROB_SCALE) {
uint32_t over = total - RANS_PROB_SCALE;
/* take from the largest symbol, never below 1 if present */
uint32_t give = freq[mx] - (cnt[mx] ? 1u : 0u);
if (give > over) give = over;
freq[mx] -= (uint16_t)give;
/* if still over (pathological), trim the next largest */
for (int s = 0; s < 256 && total - give > RANS_PROB_SCALE; s++) {
if (s == mx || !cnt[s]) continue;
uint32_t g = freq[s] - 1;
uint32_t need = total - give - RANS_PROB_SCALE;
if (g > need) g = need;
freq[s] -= (uint16_t)g; give += g;
}
}
}
size_t rans_encode_raw(const uint8_t *in, size_t n, const uint16_t *freq,
uint8_t *out) {
uint32_t cum[256];
uint32_t c = 0;
for (int s = 0; s < 256; s++) { cum[s] = c; c += freq[s]; }
uint32_t x = RANS_L;
/* Encode backwards; emit bytes into a temp tail, then reverse.
* Simpler: write backwards from the end of a scratch area. We
* write into out[0..] backwards via a local reverse pass: emit
* into out in reverse order by filling from the end. Caller
* guarantees out holds n + 64 bytes, so use the tail. */
uint8_t *p = out + 2 * n + 64; /* one past the end of scratch */
/* reserve 4 bytes at the very start of the emitted stream for the
* final state; emit stream bytes before them. Work backwards: */
uint8_t *w = p;
for (size_t i = n; i-- > 0;) {
uint8_t s = in[i];
uint32_t f = freq[s];
/* xmax = (L>>12)*f<<8: keeps post-update state in [L, 2^31) so the
* decoder renormalisation consumes exactly the bytes emitted here. */
uint32_t xmax = ((RANS_L >> RANS_PROB_BITS) * f) << 8;
while (x >= xmax) { *--w = (uint8_t)(x & 0xff); x >>= 8; }
x = (((x / f) << RANS_PROB_BITS) | ((x % f) + cum[s]));
}
/* w..p holds the emitted bytes in order; final state x follows. */
size_t nbytes = (size_t)(p - w);
memmove(out + 4, w, nbytes);
out[0] = (uint8_t)(x & 0xff);
out[1] = (uint8_t)((x >> 8) & 0xff);
out[2] = (uint8_t)((x >> 16) & 0xff);
out[3] = (uint8_t)((x >> 24) & 0xff);
return nbytes + 4;
}
int rans_decode_raw(const uint8_t *in, size_t in_len, const uint16_t *freq,
uint8_t *out, size_t out_len) {
if (in_len < 4) return -1;
uint16_t cum[256];
uint8_t dsym[RANS_PROB_SCALE];
uint32_t c = 0;
for (int s = 0; s < 256; s++) {
cum[s] = (uint16_t)c;
for (uint32_t k = 0; k < freq[s]; k++) dsym[c + k] = (uint8_t)s;
c += freq[s];
}
if (c != RANS_PROB_SCALE) return -1;
uint32_t x = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
size_t p = 4;
for (size_t i = 0; i < out_len; i++) {
uint32_t slot = x & (RANS_PROB_SCALE - 1);
uint8_t s = dsym[slot];
out[i] = s;
uint32_t f = freq[s];
x = f * (x >> RANS_PROB_BITS) + (slot - cum[s]);
while (x < RANS_L) {
if (p >= in_len) return -1;
x = (x << 8) | in[p++];
}
}
return 0;
}
int rans_encode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len) {
uint16_t freq[256];
rans_freq(in, n, freq);
uint8_t *buf = malloc(520 + 2 * n + 64);
if (!buf) return -1;
memcpy(buf, "RANS", 4);
buf[4] = (uint8_t)(n & 0xff);
buf[5] = (uint8_t)((n >> 8) & 0xff);
buf[6] = (uint8_t)((n >> 16) & 0xff);
buf[7] = (uint8_t)((n >> 24) & 0xff);
for (int s = 0; s < 256; s++) {
buf[8 + 2 * s] = (uint8_t)(freq[s] & 0xff);
buf[8 + 2 * s + 1] = (uint8_t)((freq[s] >> 8) & 0xff);
}
size_t m = rans_encode_raw(in, n, freq, buf + 520);
*out = buf;
*out_len = 520 + m;
return 0;
}
int rans_decode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len) {
if (n < 520 || memcmp(in, "RANS", 4) != 0) return -1;
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
uint16_t freq[256];
for (int s = 0; s < 256; s++)
freq[s] = (uint16_t)(in[8 + 2 * s] | (in[8 + 2 * s + 1] << 8));
uint8_t *buf = malloc(orig ? orig : 1);
if (!buf) return -1;
if (rans_decode_raw(in + 520, n - 520, freq, buf, orig) != 0) {
free(buf);
return -1;
}
*out = buf;
*out_len = orig;
return 0;
}
/* ---- general-alphabet layer (uint16_t symbols) ---- */
void rans_freq_n(const uint16_t *in, size_t n, int nsym, uint16_t *freq) {
uint32_t cnt[1024] = {0};
for (size_t i = 0; i < n; i++) cnt[in[i]]++;
uint32_t total = 0;
for (int s = 0; s < nsym; s++) {
uint32_t f = n ? (uint32_t)(((uint64_t)cnt[s] * RANS_PROB_SCALE) / n) : 0;
if (cnt[s] && f == 0) f = 1;
freq[s] = (uint16_t)f;
total += f;
}
int mx = 0;
for (int s = 1; s < nsym; s++) if (freq[s] > freq[mx]) mx = s;
if (total < RANS_PROB_SCALE) freq[mx] += (uint16_t)(RANS_PROB_SCALE - total);
else if (total > RANS_PROB_SCALE) {
uint32_t over = total - RANS_PROB_SCALE;
uint32_t give = freq[mx] - (cnt[mx] ? 1u : 0u);
if (give > over) give = over;
freq[mx] -= (uint16_t)give;
for (int s = 0; s < nsym && total - give > RANS_PROB_SCALE; s++) {
if (s == mx || !cnt[s]) continue;
uint32_t g = freq[s] - 1;
uint32_t need = total - give - RANS_PROB_SCALE;
if (g > need) g = need;
freq[s] -= (uint16_t)g; give += g;
}
}
}
size_t rans_encode_raw_n(const uint16_t *in, size_t n, const uint16_t *freq,
int nsym, uint8_t *out) {
uint32_t cum[1024];
uint32_t c = 0;
for (int s = 0; s < nsym; s++) { cum[s] = c; c += freq[s]; }
uint32_t x = RANS_L;
uint8_t *p = out + 2 * n + 64;
uint8_t *w = p;
for (size_t i = n; i-- > 0;) {
uint16_t s = in[i];
uint32_t f = freq[s];
uint32_t xmax = ((RANS_L >> RANS_PROB_BITS) * f) << 8;
while (x >= xmax) { *--w = (uint8_t)(x & 0xff); x >>= 8; }
x = (((x / f) << RANS_PROB_BITS) | ((x % f) + cum[s]));
}
size_t nbytes = (size_t)(p - w);
memmove(out + 4, w, nbytes);
out[0] = (uint8_t)(x & 0xff);
out[1] = (uint8_t)((x >> 8) & 0xff);
out[2] = (uint8_t)((x >> 16) & 0xff);
out[3] = (uint8_t)((x >> 24) & 0xff);
return nbytes + 4;
}
int rans_decode_raw_n(const uint8_t *in, size_t in_len, const uint16_t *freq,
int nsym, uint16_t *out, size_t out_len) {
if (in_len < 4) return -1;
uint16_t cum[1024];
uint16_t dsym[RANS_PROB_SCALE];
uint32_t c = 0;
for (int s = 0; s < nsym; s++) {
cum[s] = (uint16_t)c;
for (uint32_t k = 0; k < freq[s]; k++) dsym[c + k] = (uint16_t)s;
c += freq[s];
}
if (c != RANS_PROB_SCALE) return -1;
uint32_t x = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
size_t p = 4;
for (size_t i = 0; i < out_len; i++) {
uint32_t slot = x & (RANS_PROB_SCALE - 1);
uint16_t s = dsym[slot];
out[i] = s;
uint32_t f = freq[s];
x = f * (x >> RANS_PROB_BITS) + (slot - cum[s]);
while (x < RANS_L) {
if (p >= in_len) return -1;
x = (x << 8) | in[p++];
}
}
return 0;
}
-44
View File
@@ -1,44 +0,0 @@
/* rans.h - rANS entropy coder shared by the lzply experiments.
* 12-bit probabilities (scale 4096), 23-bit renormalisation window.
* Two layers:
* - stream layer: rans_freq / rans_encode_raw / rans_decode_raw work
* on a raw byte stream with a caller-supplied freq table (for
* multi-stream coders, e.g. LZ token streams).
* - file layer: rans_encode / rans_decode wrap one stream with a
* header (magic "RANS", u32 orig_len, 256 x u16 freq table).
*/
#ifndef EXP_RANS_H
#define EXP_RANS_H
#include <stddef.h>
#include <stdint.h>
#define RANS_PROB_BITS 12
#define RANS_PROB_SCALE (1u << RANS_PROB_BITS)
#define RANS_L (1u << 23)
/* Count + normalise frequencies of `in` to sum RANS_PROB_SCALE.
* Symbols present get >= 1. */
void rans_freq(const uint8_t *in, size_t n, uint16_t *freq /*[256]*/);
/* Encode `in` with `freq`; `out` must hold 2*n + 64 bytes. Returns
* bytes written. */
size_t rans_encode_raw(const uint8_t *in, size_t n, const uint16_t *freq,
uint8_t *out);
/* Decode `in_len` bytes into `out` (out_len bytes). Returns 0 ok, -1 bad. */
int rans_decode_raw(const uint8_t *in, size_t in_len, const uint16_t *freq,
uint8_t *out, size_t out_len);
/* Whole-file wrap: mallocs *out. Returns 0 ok, -1 bad. */
int rans_encode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len);
int rans_decode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len);
#endif
/* General-alphabet layer (uint16_t symbols, nsym <= 1024): for token
* streams such as literal/length (286 symbols) and distance (21). */
void rans_freq_n(const uint16_t *in, size_t n, int nsym, uint16_t *freq);
size_t rans_encode_raw_n(const uint16_t *in, size_t n, const uint16_t *freq,
int nsym, uint8_t *out /* 2*n+64 */);
int rans_decode_raw_n(const uint8_t *in, size_t in_len, const uint16_t *freq,
int nsym, uint16_t *out, size_t out_len);
-46
View File
@@ -1,46 +0,0 @@
/* rans_tool.c - standalone rANS order-0 compressor: `rans_tool c in out`,
* `rans_tool d in out`. Used for the ANS-family measurements. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rans.h"
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
int main(int argc, char **argv) {
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
return 1;
}
size_t n;
uint8_t *in = slurp(argv[2], &n);
uint8_t *out = NULL;
size_t on = 0;
int rc = argv[1][0] == 'c' ? rans_encode(in, n, &out, &on)
: rans_decode(in, n, &out, &on);
if (rc != 0) {
fprintf(stderr, "%s: %s failed (bad input?)\n", argv[0], argv[1]);
return 3;
}
spit(argv[3], out, on);
return 0;
}
View File
Whitespace-only changes.
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
bzip2,text,8388608,776306,9.25,2.969,1.346,2.8,6.2,OK
bzip2,code,8388608,1053123,12.55,2.754,0.937,3.0,8.9,OK
bzip2,bin,8388608,3373815,40.22,1.866,1.575,4.5,5.3,OK
bzip2,mixed,8388608,1974225,23.53,2.081,0.875,4.0,9.6,OK
bzip2,rand,4194304,4213434,100.46,1.336,0.958,3.1,4.4,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 bzip2 text 8388608 776306 9.25 2.969 1.346 2.8 6.2 OK
3 bzip2 code 8388608 1053123 12.55 2.754 0.937 3.0 8.9 OK
4 bzip2 bin 8388608 3373815 40.22 1.866 1.575 4.5 5.3 OK
5 bzip2 mixed 8388608 1974225 23.53 2.081 0.875 4.0 9.6 OK
6 bzip2 rand 4194304 4213434 100.46 1.336 0.958 3.1 4.4 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
dict-lzip6,text,8388608,299963,3.58,2.541,0.166,3.3,50.4,OK
dict-lzip6,code,8388608,770519,9.19,4.144,0.218,2.0,38.5,OK
dict-lzip6,bin,8388608,2793130,33.30,9.522,0.467,0.9,18.0,OK
dict-lzip6,mixed,8388608,1480819,17.65,5.358,0.317,1.6,26.5,OK
dict-lzip6,rand,4194304,4266698,101.73,2.794,0.475,1.5,8.8,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 dict-lzip6 text 8388608 299963 3.58 2.541 0.166 3.3 50.4 OK
3 dict-lzip6 code 8388608 770519 9.19 4.144 0.218 2.0 38.5 OK
4 dict-lzip6 bin 8388608 2793130 33.30 9.522 0.467 0.9 18.0 OK
5 dict-lzip6 mixed 8388608 1480819 17.65 5.358 0.317 1.6 26.5 OK
6 dict-lzip6 rand 4194304 4266698 101.73 2.794 0.475 1.5 8.8 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
gzip9,text,8388608,1969901,23.48,0.830,0.117,10.1,71.6,OK
gzip9,code,8388608,1376091,16.40,0.980,0.066,8.6,127.7,OK
gzip9,bin,8388608,3702420,44.14,2.700,0.115,3.1,72.6,OK
gzip9,mixed,8388608,2521765,30.06,1.180,0.117,7.1,71.5,OK
gzip9,rand,4194304,4194967,100.02,0.428,0.059,9.8,71.3,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 gzip9 text 8388608 1969901 23.48 0.830 0.117 10.1 71.6 OK
3 gzip9 code 8388608 1376091 16.40 0.980 0.066 8.6 127.7 OK
4 gzip9 bin 8388608 3702420 44.14 2.700 0.115 3.1 72.6 OK
5 gzip9 mixed 8388608 2521765 30.06 1.180 0.117 7.1 71.5 OK
6 gzip9 rand 4194304 4194967 100.02 0.428 0.059 9.8 71.3 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip1,text,8388608,521474,6.22,0.923,0.117,9.1,71.8,OK
lzip1,code,8388608,1268850,15.13,1.127,0.216,7.4,38.8,OK
lzip1,bin,8388608,3173235,37.83,3.144,0.468,2.7,17.9,OK
lzip1,mixed,8388608,1809972,21.58,1.789,0.271,4.7,31.0,OK
lzip1,rand,4194304,4251394,101.36,3.104,0.474,1.4,8.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip1 text 8388608 521474 6.22 0.923 0.117 9.1 71.8 OK
3 lzip1 code 8388608 1268850 15.13 1.127 0.216 7.4 38.8 OK
4 lzip1 bin 8388608 3173235 37.83 3.144 0.468 2.7 17.9 OK
5 lzip1 mixed 8388608 1809972 21.58 1.789 0.271 4.7 31.0 OK
6 lzip1 rand 4194304 4251394 101.36 3.104 0.474 1.4 8.9 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip6,text,8388608,298558,3.56,3.655,0.117,2.3,71.4,OK
lzip6,code,8388608,787213,9.38,5.138,0.168,1.6,50.0,OK
lzip6,bin,8388608,2735269,32.61,9.676,0.416,0.9,20.2,OK
lzip6,mixed,8388608,1460156,17.41,5.519,0.267,1.5,31.4,OK
lzip6,rand,4194304,4251435,101.36,3.173,0.531,1.3,7.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip6 text 8388608 298558 3.56 3.655 0.117 2.3 71.4 OK
3 lzip6 code 8388608 787213 9.38 5.138 0.168 1.6 50.0 OK
4 lzip6 bin 8388608 2735269 32.61 9.676 0.416 0.9 20.2 OK
5 lzip6 mixed 8388608 1460156 17.41 5.519 0.267 1.5 31.4 OK
6 lzip6 rand 4194304 4251435 101.36 3.173 0.531 1.3 7.9 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip9,text,8388608,288746,3.44,6.658,0.119,1.3,70.3,OK
lzip9,code,8388608,758969,9.05,9.062,0.168,0.9,50.0,OK
lzip9,bin,8388608,2729180,32.53,10.747,0.479,0.8,17.5,OK
lzip9,mixed,8388608,1440405,17.17,8.603,0.272,1.0,30.8,OK
lzip9,rand,4194304,4251435,101.36,3.071,0.467,1.4,9.0,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip9 text 8388608 288746 3.44 6.658 0.119 1.3 70.3 OK
3 lzip9 code 8388608 758969 9.05 9.062 0.168 0.9 50.0 OK
4 lzip9 bin 8388608 2729180 32.53 10.747 0.479 0.8 17.5 OK
5 lzip9 mixed 8388608 1440405 17.17 8.603 0.272 1.0 30.8 OK
6 lzip9 rand 4194304 4251435 101.36 3.071 0.467 1.4 9.0 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzrans-lazy,text,8388608,525357,6.26,1.888,0.119,4.4,70.6,OK
lzrans-lazy,code,8388608,1134159,13.52,3.264,0.116,2.6,72.5,OK
lzrans-lazy,bin,8388608,3510054,41.84,9.644,0.320,0.9,26.2,OK
lzrans-lazy,mixed,8388608,1942374,23.15,3.963,0.165,2.1,50.7,OK
lzrans-lazy,rand,4194304,4214292,100.48,9.295,0.115,0.5,36.3,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzrans-lazy text 8388608 525357 6.26 1.888 0.119 4.4 70.6 OK
3 lzrans-lazy code 8388608 1134159 13.52 3.264 0.116 2.6 72.5 OK
4 lzrans-lazy bin 8388608 3510054 41.84 9.644 0.320 0.9 26.2 OK
5 lzrans-lazy mixed 8388608 1942374 23.15 3.963 0.165 2.1 50.7 OK
6 lzrans-lazy rand 4194304 4214292 100.48 9.295 0.115 0.5 36.3 OK
-3
View File
@@ -1,3 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzrans-opt,text,8388608,519352,6.19,18.714,0.132,0.4,63.5,OK
lzrans-opt,code,8388608,1094779,13.05,8.628,0.115,1.0,72.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzrans-opt text 8388608 519352 6.19 18.714 0.132 0.4 63.5 OK
3 lzrans-opt code 8388608 1094779 13.05 8.628 0.115 1.0 72.9 OK
-4
View File
@@ -1,4 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
ppm,text,8388608,2754814,32.84,1.327,2.176,6.3,3.9,OK
ppm,code,8388608,2585570,30.82,1.324,2.040,6.3,4.1,OK
ppm,mixed,8388608,3286801,39.18,1.732,2.635,4.8,3.2,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 ppm text 8388608 2754814 32.84 1.327 2.176 6.3 3.9 OK
3 ppm code 8388608 2585570 30.82 1.324 2.040 6.3 4.1 OK
4 ppm mixed 8388608 3286801 39.18 1.732 2.635 4.8 3.2 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
rans0,text,8388608,5401895,64.40,0.221,0.170,38.0,49.3,OK
rans0,code,8388608,5672388,67.62,0.277,0.171,30.3,49.1,OK
rans0,bin,8388608,6470778,77.14,0.217,0.179,38.6,46.9,OK
rans0,mixed,8388608,6552704,78.11,0.218,0.174,38.4,48.1,OK
rans0,rand,4194304,4213441,100.46,0.115,0.068,36.4,61.6,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 rans0 text 8388608 5401895 64.40 0.221 0.170 38.0 49.3 OK
3 rans0 code 8388608 5672388 67.62 0.277 0.171 30.3 49.1 OK
4 rans0 bin 8388608 6470778 77.14 0.217 0.179 38.6 46.9 OK
5 rans0 mixed 8388608 6552704 78.11 0.218 0.174 38.4 48.1 OK
6 rans0 rand 4194304 4213441 100.46 0.115 0.068 36.4 61.6 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
xz6,text,8388608,294056,3.51,4.257,0.076,2.0,110.1,OK
xz6,code,8388608,771984,9.20,7.147,0.200,1.2,42.0,OK
xz6,bin,8388608,2733616,32.59,12.330,0.367,0.7,22.8,OK
xz6,mixed,8388608,1450908,17.30,7.553,0.271,1.1,31.0,OK
xz6,rand,4194304,4194584,100.01,3.323,0.085,1.3,49.1,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 xz6 text 8388608 294056 3.51 4.257 0.076 2.0 110.1 OK
3 xz6 code 8388608 771984 9.20 7.147 0.200 1.2 42.0 OK
4 xz6 bin 8388608 2733616 32.59 12.330 0.367 0.7 22.8 OK
5 xz6 mixed 8388608 1450908 17.30 7.553 0.271 1.1 31.0 OK
6 xz6 rand 4194304 4194584 100.01 3.323 0.085 1.3 49.1 OK
-6
View File
@@ -1,6 +0,0 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
zstd19,text,8388608,304391,3.63,3.549,0.055,2.4,151.8,OK
zstd19,code,8388608,795239,9.48,11.348,0.071,0.7,117.7,OK
zstd19,bin,8388608,2919792,34.81,14.260,0.169,0.6,49.5,OK
zstd19,mixed,8388608,1535960,18.31,8.021,0.066,1.0,126.9,OK
zstd19,rand,4194304,4194413,100.00,3.020,0.037,1.4,112.0,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 zstd19 text 8388608 304391 3.63 3.549 0.055 2.4 151.8 OK
3 zstd19 code 8388608 795239 9.48 11.348 0.071 0.7 117.7 OK
4 zstd19 bin 8388608 2919792 34.81 14.260 0.169 0.6 49.5 OK
5 zstd19 mixed 8388608 1535960 18.31 8.021 0.066 1.0 126.9 OK
6 zstd19 rand 4194304 4194413 100.00 3.020 0.037 1.4 112.0 OK