diff --git a/README.md b/README.md index d40a14d..785a46b 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ libdmodemctl. Thus they operate in the same way. the Minitel and the Tektronix 4014. They have sixel, ReGIS and Tektronix graphics, and the font of each machine (the SyncTERM copies of their ROMs, LGPL-2.0-or-later: `core/licenses/syncterm-fonts-LGPL-2.0.txt`) -- **File transfers** (Windows app): send and receive files on the modem line or on a Telnet, rlogin or SSH login. The protocols are the same as the D-Modem app: ZMODEM (with Automatic Receive when the remote side starts sz, rz or kermit -s, and with Crash Recovery), YMODEM, YMODEM-G, XMODEM, XMODEM-1K, Kermit, Intel HEX, Motorola S-records and plain text. Use the Transfer menu, or the Send and Receive buttons of the Terminal page +- **File transfers** (Windows app): send and receive files on the modem line or on a Telnet, rlogin or SSH login. The protocols are the same as the D-Modem app: ZMODEM (with Automatic Receive when the remote side starts sz, rz or kermit -s, with Crash Recovery, and with zstd compression to the D-Modem BBS and app), YMODEM, YMODEM-G, XMODEM, XMODEM-1K, Kermit, Intel HEX, Motorola S-records and plain text. Use the Transfer menu, or the Send and Receive buttons of the Terminal page - **Copy and capture** (Windows app): select text with the mouse (Shift and the mouse when the remote side uses the mouse), then copy it. Paste to Host, Select All, Capture Text (to a file), Capture to Printer, and Print (the screen or the selection). Text that the remote side sends to its printer port goes to the printer. Use the Edit and Transfer menus, or click the right mouse button on the terminal - **ASCII Setup** (Windows app, Modem menu): the same items as HyperTerminal. For the data that you send: Enter sends CR LF, the local echo, and the line delay and character delay of a text file. For the data that you receive: an LF after each CR, 7-bit ASCII, and the wrap of long lines. The settings apply to the modem terminal and to the Remote terminal - **Terminal Settings** (Windows app, Modem menu): the same items as HyperTerminal, for the modem terminal and for the Remote terminal. They are what Backspace sends (Ctrl+H, Del, or Ctrl+H, Space, Ctrl+H), the function, arrow and Ctrl keys as terminal keys or Windows keys, the backscroll buffer lines, the font, the cursor, the Telnet terminal ID, and Exit program upon disconnecting. The status bar shows the connect timer during a call diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index ad0e0df..63897f3 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -28,7 +28,8 @@ set(DMODEMCTL_SOURCES src/xfer_hex.c src/xfer_kermit.c src/xfer_xy.c - src/xfer_z.c) + src/xfer_z.c + src/zstd_codec.c) if(DMODEMCTL_SHARED) add_library(dmodemctl SHARED ${DMODEMCTL_SOURCES}) diff --git a/core/include/dmodemctl.h b/core/include/dmodemctl.h index 21285bd..0dae30a 100644 --- a/core/include/dmodemctl.h +++ b/core/include/dmodemctl.h @@ -708,6 +708,11 @@ typedef struct dmc_xfer_options { /* plain text sent: a wait after each line, and after each character, in ms */ int line_delay_ms, char_delay_ms; + /* ZMODEM with zstd stopped: files are not compressed (sending), and + compressed files are not taken (receiving). When it is not + stopped, zstd is used only where the other side can use it too + (D-Modem's BBS, GUI and app) */ + int no_zstd; } dmc_xfer_options; /* files from the remote into folder (name: XMODEM's file, which it does @@ -728,6 +733,8 @@ DMC_API dmc_xfer *dmc_xfer_send_opt(int protocol, const char *const *paths, DMC_API void dmc_xfer_skip(dmc_xfer *x); /* whether the protocol can skip a file (receiving) */ DMC_API int dmc_xfer_can_skip(int protocol); +/* whether the file now goes compressed with zstd (ZMODEM with zstd) */ +DMC_API int dmc_xfer_zstd(dmc_xfer *x); /* bytes from the remote */ DMC_API void dmc_xfer_feed(dmc_xfer *x, const char *data, int n); /* bytes for the remote: how many */ diff --git a/core/src/xfer.c b/core/src/xfer.c index a15ceb9..3157f09 100644 --- a/core/src/xfer.c +++ b/core/src/xfer.c @@ -784,6 +784,16 @@ int dmc_xfer_can_skip(int protocol) return protocol == DMC_XFER_ZMODEM || protocol == DMC_XFER_KERMIT; } +void xfer_zstd(dmc_xfer *x, int on) +{ + x->zstd = on; +} + +int dmc_xfer_zstd(dmc_xfer *x) +{ + return x ? x->zstd : 0; +} + dmc_xfer *dmc_xfer_receive_opt(int protocol, const char *folder, const char *name, const dmc_xfer_options *o) { diff --git a/core/src/xfer.h b/core/src/xfer.h index d377eb3..90038e6 100644 --- a/core/src/xfer.h +++ b/core/src/xfer.h @@ -77,6 +77,7 @@ struct dmc_xfer { int keep_partial; /* crash recovery: a part is kept */ dmc_xfer_options opt; volatile int skip; /* the user skipped the file now */ + volatile int zstd; /* the file now goes with zstd */ void *heap; /* freed at the end */ void *proto; /* the protocol's state (Kermit's) */ void (*proto_free)(void *); /* how it's freed (NULL: free) */ @@ -129,6 +130,8 @@ void xfer_create(dmc_xfer *x, const char *name); continued (its length, appended to), or a new one (0); -2 when the file is there whole (size known), and nothing opened */ long long xfer_create_resume(dmc_xfer *x, const char *name, long long size); +/* whether the file now goes compressed with zstd (ZMODEM) */ +void xfer_zstd(dmc_xfer *x, int on); /* the user's skip of the file now, taken (once) */ int xfer_skip_wanted(dmc_xfer *x); /* the received file written */ diff --git a/core/src/xfer_z.c b/core/src/xfer_z.c index 9dca210..4bd8450 100644 --- a/core/src/xfer_z.c +++ b/core/src/xfer_z.c @@ -8,11 +8,21 @@ * (ZCRCG) with the receiver's ZRPOS putting the sender back * where the line went wrong, files offered by name, size and * time, and ended with ZFIN and "OO". + * + * With zstd (docs/zmodem-zstd.md of D-Modem): the receiver + * tells it can decompress by CANZSTD in its ZRINIT's ZF1, and + * the sender asks for it file by file with ZTZSTD in the + * ZFILE's ZF2. The file then goes as independent zstd frames, + * one for each chunk of the file, and every position on the + * line is still an offset in the file: a ZDATA starts a frame, + * and the receiver writes (and acknowledges) only whole + * frames, so ZRPOS and crash recovery work as without zstd. */ #include #include #include "xfer.h" +#include "zstd_codec.h" #define ZPAD '*' #define ZDLE 0x18 @@ -39,6 +49,17 @@ enum { #define CANFC32 0x20 #define ZCBIN 1 #define ZCRECOV 3 /* ZF0: continue a part of the file */ +#define CANZSTD 0x40 /* ZRINIT ZF1: zstd frames taken */ +#define ZTZSTD 8 /* ZFILE ZF2: the file in zstd frames */ + +/* zstd: the file's bytes in each frame the sender makes (halved after a + ZRPOS, to ZSTD_MIN_CHUNK; doubled after an ACK), and the most a frame + may hold */ +#define ZSTD_CHUNK (64 * 1024) +#define ZSTD_MIN_CHUNK 1024 +#define ZSTD_MAX (256 * 1024) +/* the receiver's frames not complete yet, at the most */ +#define ZSTD_HELD (ZSTD_MAX + ZSTD_MAX / 8 + 8200 + 64) #define BLOCK 1024 /* bytes between the sender's ZCRCQs (its window) */ @@ -73,6 +94,13 @@ struct z { unsigned char data[8200]; /* a data subpacket that came */ unsigned char out[2 * 8200 + 32]; int on; + int zstd; /* zstd frames: we take them (receiving), + the receiver takes them (sending) */ + unsigned char *held; /* the frame not complete yet */ + int nheld; + unsigned char *frame; /* the frame being sent */ + unsigned char *chunk; /* the file's bytes in it */ + int chunk_size; /* how many of them, at the most */ }; static long long hpos(const struct header *h) @@ -90,11 +118,14 @@ static struct header hdr_pos(int type, long long pos) return h; } -static struct header hdr_flags(int type, int f0) +/* a header of flags: ZF0 (p[3]), ZF1 (p[2]) and ZF2 (p[1]) */ +static struct header hdr_flags(int type, int f0, int f1, int f2) { struct header h; h.type = type; - h.p[0] = h.p[1] = h.p[2] = 0; + h.p[0] = 0; + h.p[1] = (unsigned char)f2; + h.p[2] = (unsigned char)f1; h.p[3] = (unsigned char)f0; return h; } @@ -442,6 +473,17 @@ static int read_data_or_fail(struct z *z, int max, int *end) return n; } +static void z_free(void *p) +{ + struct z *z = (struct z *)p; + if (z) { + free(z->held); + free(z->frame); + free(z->chunk); + free(z); + } +} + static struct z *z_new(dmc_xfer *x) { struct z *z = (struct z *)calloc(1, sizeof(*z)); @@ -449,20 +491,119 @@ static struct z *z_new(dmc_xfer *x) xfer_fail(x, "out of memory"); z->x = x; x->proto = z; + x->proto_free = z_free; return z; } +/* ------------------------------------------------------------------ */ +/* zstd */ + +/* the extensions of files that zstd does not make smaller: sent as they + are */ +static const char *const precompressed[] = { + "zip", "gz", "tgz", "bz2", "xz", "zst", "lz", "lzma", "7z", "rar", + "arj", "arc", "lzh", "lha", "zoo", "pak", "sqz", "cab", "z", "jpg", + "jpeg", "png", "gif", "webp", "mp3", "ogg", "opus", "flac", "mp4", + "mkv", "avi", "mov", "webm", "jar", "apk", "docx", "xlsx", "pptx", + "odt", "epub", "pdf" +}; + +static int worth_compressing(const char *name) +{ + const char *dot = NULL; + for (const char *p = name; *p; p++) + if (*p == '.') + dot = p + 1; + else if (*p == '/' || *p == '\\') + dot = NULL; + if (!dot) + return 1; + for (size_t i = 0; i < sizeof(precompressed) / sizeof(precompressed[0]); i++) + if (same_ci(dot, precompressed[i])) + return 0; + return 1; +} + +/* whether the start of the open file gets at least 5% smaller with zstd + (and the file back at its start) */ +static int sample_compresses(struct z *z) +{ + dmc_xfer *x = z->x; + unsigned char *buf = (unsigned char *)malloc(ZSTD_CHUNK); + int n = 0, fn = 0, yes = 1; + if (!buf) + return 0; + while (n < ZSTD_CHUNK) { + int r = xfer_src_read(x, buf + n, ZSTD_CHUNK - n); + if (r <= 0) + break; + n += r; + } + if (fseek(x->src, 0, SEEK_SET) != 0) { + free(buf); + xfer_fail(x, "can't go back to the start of the file"); + } + unsigned char *f = zc_encode(buf, n, &fn); + if (!f || n == 0 || (long long)fn * 100 > (long long)n * 95) + yes = 0; + free(f); + free(buf); + return yes; +} + +/* the received data with the frames it completes decompressed and + written (*wrote the file's bytes): -1 when a frame is bad, the frames + held are too many, or a subpacket that ends a segment (ZCRCW, ZCRCE) + ends in the middle of a frame; else 0 */ +static int unpack(struct z *z, const unsigned char *data, int n, int end, + long long *wrote) +{ + *wrote = 0; + if (!z->held) { + z->held = (unsigned char *)malloc(ZSTD_HELD); + if (!z->held) + xfer_fail(z->x, "out of memory"); + } + if (z->nheld + n > ZSTD_HELD) + return -1; + memcpy(z->held + z->nheld, data, (size_t)n); + z->nheld += n; + int at = 0; + for (;;) { + int len = zc_frame_len(z->held + at, z->nheld - at, ZSTD_MAX); + if (len < 0) + return -1; + if (len == 0) + break; + int got; + unsigned char *c = zc_decode(z->held + at, len, ZSTD_MAX, &got, NULL); + if (!c) + return -1; + xfer_dst_write(z->x, c, got); + free(c); + *wrote += got; + at += len; + } + memmove(z->held, z->held + at, (size_t)(z->nheld - at)); + z->nheld -= at; + if (z->nheld > 0 && (end == ZCRCW || end == ZCRCE)) + return -1; + return 0; +} + /* ------------------------------------------------------------------ */ /* receiving (the other side runs sz) */ static void zrinit(struct z *z) { - send_hex(z, hdr_flags(ZRINIT, CANFDX | CANOVIO | CANFC32)); + send_hex(z, hdr_flags(ZRINIT, CANFDX | CANOVIO | CANFC32, + z->zstd ? CANZSTD : 0, 0)); } -/* a file's data after its ZFILE (its info, len bytes; f0 its ZF0): 1 - received, 0 skipped */ -static int receive_file(struct z *z, const unsigned char *info, int len, int f0) +/* a file's data after its ZFILE (its info, len bytes; f0 and f2 its ZF0 + and ZF2): 1 received, 0 skipped */ +static int receive_file(struct z *z, const unsigned char *info, int len, int f0, + int f2) { dmc_xfer *x = z->x; char name[XFER_NAME], meta[256]; @@ -484,6 +625,13 @@ static int receive_file(struct z *z, const unsigned char *info, int len, int f0) if (*e == ' ') mtime = strtoll(e + 1, NULL, 8); long long pos = 0, rpos_at = 0; + /* zstd frames: only if we said we take them */ + int zstd = f2 == ZTZSTD; + if (zstd && !z->zstd) { + send_hex(z, hdr_pos(ZSKIP, 0)); + return 0; + } + z->nheld = 0; /* crash recovery (ours, or the sender's ZCRECOV): from the end of a part that is in the folder */ if (x->opt.resume || f0 == ZCRECOV) { @@ -498,12 +646,14 @@ static int receive_file(struct z *z, const unsigned char *info, int len, int f0) } xfer_file_start(x, x->dst_name, size); xfer_bytes(x, pos); - int errors = 0, ok = 0; + xfer_zstd(x, zstd); + int errors = 0, ok = 0, quiet = 0; struct header h; /* (until the sender has had time to hear our ZRPOS, what still comes of its stream from before isn't an error, and isn't asked for again: each ZRPOS a restart of its own) */ -#define RPOS() (send_hex(z, hdr_pos(ZRPOS, pos)), rpos_at = xfer_now()) +#define RPOS() (z->nheld = 0, send_hex(z, hdr_pos(ZRPOS, pos)), \ + rpos_at = xfer_now()) #define WAITING() (xfer_now() - rpos_at < RPOS_GRACE_MS) RPOS(); for (;;) { @@ -517,7 +667,9 @@ static int receive_file(struct z *z, const unsigned char *info, int len, int f0) /* (8 KB of a stream with no header in it: ours lost; asked for again) */ int st = read_header(z, 8 * 1024, 1, &h); - if (st == H_QUIET) + /* (quiet: what the sender waits on lost, a ZDATA's end or a + ZEOF; asked for again, as for an error, a few times) */ + if (st == H_QUIET && ++quiet > 3) xfer_fail(x, "the other side went quiet"); if (st != H_OK) { if (WAITING()) @@ -527,15 +679,31 @@ static int receive_file(struct z *z, const unsigned char *info, int len, int f0) RPOS(); continue; } + quiet = 0; if (h.type == ZDATA) { if (hpos(&h) != pos) { /* not where we are: back to it (not an error) */ RPOS(); continue; } + /* (a ZDATA starts a frame) */ + z->nheld = 0; for (;;) { int end; - int n = read_data_or_fail(z, 8192, &end); + long long wrote = 0; + /* (the line quiet in the middle of a subpacket: its + end damaged, and the sender waits for an ACK of + it; an error, asked for again) */ + int n = read_data(z, 8192, &end); + if (n == -2 && ++quiet > 3) + xfer_fail(x, "the other side went quiet"); + if (n >= 0 && zstd) { + /* (the whole frames written, even when + one after them is bad) */ + if (unpack(z, z->data, n, end, &wrote) < 0) + n = -1; + pos += wrote; + } if (n < 0) { if (++errors > MAX_ERRORS) xfer_fail(x, "too many errors on the line"); @@ -544,9 +712,12 @@ static int receive_file(struct z *z, const unsigned char *info, int len, int f0) RPOS(); break; } - xfer_dst_write(x, z->data, n); - pos += n; + if (!zstd) { + xfer_dst_write(x, z->data, n); + pos += n; + } errors = 0; + quiet = 0; xfer_bytes(x, pos); if (end == ZCRCW) { send_hex(z, hdr_pos(ZACK, pos)); @@ -584,6 +755,7 @@ static int receive_file(struct z *z, const unsigned char *info, int len, int f0) } #undef RPOS #undef WAITING + xfer_zstd(x, 0); if (!ok) { xfer_abandon(x); return 0; @@ -597,6 +769,7 @@ void z_receive(dmc_xfer *x) struct z *z = z_new(x); unsigned char info[4100]; int errors = 0; + z->zstd = !x->opt.no_zstd; zrinit(z); long long last_header = xfer_now(); for (;;) { @@ -633,7 +806,7 @@ void z_receive(dmc_xfer *x) break; } memcpy(info, z->data, (size_t)n); - if (receive_file(z, info, n, h.p[3])) { + if (receive_file(z, info, n, h.p[3], h.p[1])) { xfer_file_done(x); zrinit(z); } @@ -727,17 +900,41 @@ static long long seek(struct z *z, long long to) return to; } +/* the receiver's word while we send, if any (what isn't a header's + start let go first: an XON, a CR LF): 1 with its header in *h */ +static int heard(struct z *z, struct header *h) +{ + dmc_xfer *x = z->x; + for (;;) { + int c = xfer_peek(x); + if (c < 0 || c == ZPAD || c == ZDLE) + break; + xfer_read(x, 0); + } + return xfer_available(x) && header_or_null(z, h); +} + /* the file's data from start in ZCRCG subpackets, a ZCRCQ every WINDOW bytes to hear how it goes, ZCRCE and ZEOF at the end; a ZRPOS from the - receiver puts it back there; done at the receiver's ZRINIT */ -static void stream(struct z *z, long long start) + receiver puts it back there; done at the receiver's ZRINIT. With zstd + (zstd set) each chunk of the file goes as one frame, in as many + subpackets as it takes, and only a frame's end ends a ZCRCQ or ZCRCE */ +static void stream(struct z *z, long long start, int zstd) { dmc_xfer *x = z->x; unsigned char buf[BLOCK]; int errors = 0; long long at = start, last_back = -1, pos; struct header h; - /* (errors counted while no progress is made) */ + if (zstd && !z->chunk) { + z->chunk = (unsigned char *)malloc(ZSTD_CHUNK); + if (!z->chunk) + xfer_fail(x, "out of memory"); + } + if (z->chunk_size == 0) + z->chunk_size = ZSTD_CHUNK; + /* (errors counted while no progress is made; a line with errors + gets smaller frames) */ #define BACK(to) do { \ long long to_ = (to); \ if (to_ > last_back) \ @@ -747,6 +944,8 @@ static void stream(struct z *z, long long start) xfer_fail(x, "too many errors on the line"); \ xfer_error(x); \ at = to_; \ + if (z->chunk_size / 2 >= ZSTD_MIN_CHUNK) \ + z->chunk_size /= 2; \ xfer_sleep(20); \ xfer_purge(x); \ } while (0) @@ -755,15 +954,7 @@ static void stream(struct z *z, long long start) send_bin(z, hdr_pos(ZDATA, pos)); int since_ack = 0, restart = 0; for (;;) { - /* the receiver's word in between, if any (what isn't a - header's start let go first: an XON, a CR LF) */ - for (;;) { - int c = xfer_peek(x); - if (c < 0 || c == ZPAD || c == ZDLE) - break; - xfer_read(x, 0); - } - if (xfer_available(x) && header_or_null(z, &h)) { + if (heard(z, &h)) { if (h.type == ZRPOS) { BACK(hpos(&h)); restart = 1; @@ -774,17 +965,59 @@ static void stream(struct z *z, long long start) if (h.type == ZSKIP) return; } - int len = 0; - while (len < BLOCK) { - int r = xfer_src_read(x, buf + len, BLOCK - len); - if (r <= 0) + int len = 0, end; + if (!zstd) { + while (len < BLOCK) { + int r = xfer_src_read(x, buf + len, BLOCK - len); + if (r <= 0) + break; + len += r; + } + pos += len; + since_ack += len; + end = len < BLOCK ? ZCRCE : since_ack >= WINDOW ? ZCRCQ : ZCRCG; + send_data(z, buf, len, end); + } else { + /* a chunk of the file, as one frame */ + int fn = 0; + while (len < z->chunk_size) { + int r = xfer_src_read(x, z->chunk + len, z->chunk_size - len); + if (r <= 0) + break; + len += r; + } + free(z->frame); + z->frame = NULL; + if (len > 0) { + z->frame = zc_encode(z->chunk, len, &fn); + if (!z->frame) + xfer_fail(x, "out of memory"); + } + since_ack += fn; + end = len < z->chunk_size ? ZCRCE : since_ack >= WINDOW ? ZCRCQ : ZCRCG; + int o = 0; + do { + int k = fn - o < BLOCK ? fn - o : BLOCK; + send_data(z, z->frame + o, k, o + k < fn ? ZCRCG : end); + o += k; + /* (a ZRPOS in the middle of the frame: the + rest of it not sent) */ + if (o < fn && heard(z, &h)) { + if (h.type == ZRPOS) { + BACK(hpos(&h)); + restart = 1; + break; + } + if (h.type == ZCAN || h.type == ZABORT) + xfer_cancelled(x, "cancelled by the receiver"); + if (h.type == ZSKIP) + return; + } + } while (o < fn); + if (restart) break; - len += r; + pos += len; } - pos += len; - since_ack += len; - int end = len < BLOCK ? ZCRCE : since_ack >= WINDOW ? ZCRCQ : ZCRCG; - send_data(z, buf, len, end); xfer_bytes(x, pos); if (end == ZCRCE) break; @@ -798,6 +1031,8 @@ static void stream(struct z *z, long long start) restart = 1; break; } + if (z->chunk_size * 2 <= ZSTD_CHUNK) + z->chunk_size *= 2; } } if (restart) @@ -844,8 +1079,13 @@ static int send_file(struct z *z, const struct xfer_file *f, int files_left, long long start = -1; int tries = 0; struct header h; + /* zstd: where the receiver takes it, for a file that gets smaller */ + xfer_open(z->x, f); + int zstd = z->zstd && f->size > 0 && worth_compressing(f->name) && + sample_compresses(z); while (start < 0) { - send_bin(z, hdr_flags(ZFILE, z->x->opt.resume ? ZCRECOV : ZCBIN)); + send_bin(z, hdr_flags(ZFILE, z->x->opt.resume ? ZCRECOV : ZCBIN, 0, + zstd ? ZTZSTD : 0)); send_data(z, info, n, ZCRCW); for (;;) { int got = header_or_null(z, &h); @@ -853,8 +1093,10 @@ static int send_file(struct z *z, const struct xfer_file *f, int files_left, start = hpos(&h); break; } - if (got && h.type == ZSKIP) + if (got && h.type == ZSKIP) { + xfer_close(z->x); return 1; + } if (got && h.type == ZCRC) { send_hex(z, hdr_pos(ZCRC, 0)); continue; @@ -872,8 +1114,9 @@ static int send_file(struct z *z, const struct xfer_file *f, int files_left, break; } } - xfer_open(z->x, f); - stream(z, start); + xfer_zstd(z->x, zstd); + stream(z, start, zstd); + xfer_zstd(z->x, 0); xfer_close(z->x); return 0; } @@ -883,6 +1126,7 @@ void z_send(dmc_xfer *x) struct z *z = z_new(x); struct header r = wait_for_zrinit(z); z->crc32 = (r.p[3] & CANFC32) != 0; + z->zstd = !x->opt.no_zstd && (r.p[2] & CANZSTD) != 0; long long left = 0; for (int i = 0; i < x->nfiles; i++) left += x->files[i].size > 0 ? x->files[i].size : 0; diff --git a/core/src/zstd_codec.c b/core/src/zstd_codec.c new file mode 100644 index 0000000..138f6eb --- /dev/null +++ b/core/src/zstd_codec.c @@ -0,0 +1,1571 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * zstd_codec.c - Zstandard (RFC 8878), whole frames: see zstd_codec.h. + * The same steps as the app's Zstd.kt, so that the two + * make the same frames. + */ +#include +#include +#include + +#include "zstd_codec.h" + +#define MAX_BLOCK (128 * 1024) +#define HUF_MAX 11 + +typedef unsigned char u8; +typedef int64_t i64; +typedef uint64_t u64; + +static int hbit(unsigned v) +{ + int b = -1; + while (v) { + b++; + v >>= 1; + } + return b; +} + +static const int LL_BASE[36] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, + 20, 22, 24, 28, 32, 40, 48, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 }; +static const int LL_BITS[36] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, + 3, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; +static const int ML_BASE[53] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, + 99, 131, 259, 515, 1027, 2051, 4099, 8195, 16387, 32771, 65539 }; +static const int ML_BITS[53] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; +static const int LL_DEF[36] = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 3, 2, 1, 1, 1, 1, 1, -1, -1, -1, -1 }; +static const int ML_DEF[53] = { 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1 }; +static const int OF_DEF[29] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, -1, -1, -1, -1, -1 }; + +/* ------------------------------------------------------------------ */ +/* a growing byte buffer */ + +typedef struct { + u8 *p; + int n, cap; + int oom; +} zb; + +static void zb_room(zb *b, int more) +{ + if (b->oom) + return; + if (b->n + more > b->cap) { + int cap = b->cap ? b->cap : 256; + while (cap < b->n + more) + cap *= 2; + u8 *q = realloc(b->p, (size_t)cap); + if (!q) { + b->oom = 1; + return; + } + b->p = q; + b->cap = cap; + } +} + +static void zb_put(zb *b, int c) +{ + zb_room(b, 1); + if (!b->oom) + b->p[b->n++] = (u8)c; +} + +static void zb_add(zb *b, const u8 *s, int n) +{ + if (n <= 0) + return; + zb_room(b, n); + if (!b->oom) { + memcpy(b->p + b->n, s, (size_t)n); + b->n += n; + } +} + +static void zb_free(zb *b) +{ + free(b->p); + memset(b, 0, sizeof *b); +} + +/* ------------------------------------------------------------------ */ +/* bits */ + +/* a forward bit stream (FSE table descriptions), the lowest bits first */ +typedef struct { + const u8 *p; + int n; + i64 pos; + int bad; +} fwd_bits; + +static int fwd_peek(fwd_bits *f, int nb) +{ + int v = 0; + for (int k = 0; k < nb; k++) { + i64 q = f->pos + k; + if (q < 8LL * f->n) + v |= ((f->p[q >> 3] >> (q & 7)) & 1) << k; + } + return v; +} + +static int fwd_read(fwd_bits *f, int nb) +{ + int v = fwd_peek(f, nb); + f->pos += nb; + if (f->pos > 8LL * f->n) + f->bad = 1; + return v; +} + +/* a backward bit stream (Huffman and FSE coded data): from under the + last byte's marker toward the start */ +typedef struct { + const u8 *p; + int n; + i64 off; +} back_bits; + +static int back_init(back_bits *b, const u8 *p, int n) +{ + b->p = p; + b->n = n; + if (n <= 0 || p[n - 1] == 0) + return 0; + b->off = 8LL * (n - 1) + hbit(p[n - 1]); + return 1; +} + +static u64 back_read(back_bits *b, int nb) +{ + u64 v = 0; + b->off -= nb; + for (int k = nb - 1; k >= 0; k--) { + i64 q = b->off + k; + v = (v << 1) | (q >= 0 ? (u64)((b->p[q >> 3] >> (q & 7)) & 1) : 0); + } + return v; +} + +/* a forward bit writer, the lowest bits first */ +typedef struct { + zb b; + int acc, n; +} bit_w; + +static void bw_put(bit_w *w, u64 v, int nb) +{ + for (int k = 0; k < nb; k++) { + w->acc |= (int)((v >> k) & 1) << w->n; + if (++w->n == 8) { + zb_put(&w->b, w->acc); + w->acc = 0; + w->n = 0; + } + } +} + +static void bw_close(bit_w *w) +{ + bw_put(w, 1, 1); + if (w->n != 0) + bw_put(w, 0, 8 - w->n); +} + +/* ------------------------------------------------------------------ */ +/* tables */ + +#define FSE_MAX 512 /* 1 << 9 */ +#define HUF_SIZE (1 << HUF_MAX) + +/* an FSE decoding table: each state's symbol, bits and baseline */ +typedef struct { + int log; + int sym[FSE_MAX], nb[FSE_MAX], base[FSE_MAX]; +} fse_t; + +/* a Huffman decoding table: by max_bits bits, the symbol and its length */ +typedef struct { + int max_bits; /* 0: none */ + u8 sym[HUF_SIZE], nb[HUF_SIZE]; +} huf_t; + +/* an FSE table from the counts (-1: "less than 1") at accuracy log al + (4.1.1) */ +static int fse_build(fse_t *t, const int *cnt, int nsym, int al) +{ + int size = 1 << al, high = size - 1; + int next[256]; + if (al > 9 || nsym > 256) + return 0; + t->log = al; + for (int s = 0; s < nsym; s++) { + if (cnt[s] == -1) { + if (high < 0) + return 0; + t->sym[high--] = s; + next[s] = 1; + } else + next[s] = cnt[s] > 0 ? cnt[s] : 0; + } + int step = (size >> 1) + (size >> 3) + 3, mask = size - 1, pos = 0; + for (int s = 0; s < nsym; s++) + for (int i = 0; i < cnt[s]; i++) { + if (pos > high) + return 0; + t->sym[pos] = s; + do + pos = (pos + step) & mask; + while (pos > high); + } + if (pos != 0) + return 0; + for (int i = 0; i < size; i++) { + int d = next[t->sym[i]]++; + if (d <= 0) + return 0; + int nb = al - hbit((unsigned)d); + t->nb[i] = nb; + t->base[i] = (d << nb) - size; + } + return 1; +} + +/* an FSE table description at p[0..n): the counts (*nc of them) and the + accuracy log, and its bytes; -1 if bad */ +static int fse_desc(const u8 *p, int n, int max_al, int max_sym, int *cnt, int *nc, int *al_out) +{ + if (n < 1) + return -1; + fwd_bits in = { p, n, 0, 0 }; + int al = 5 + fwd_read(&in, 4); + if (al > max_al) + return -1; + int remaining = 1 << al, bits = al + 1, k = 0; + while (remaining > 0 && k < max_sym) { + int lower = (1 << (bits - 1)) - 1; + int thr = (1 << bits) - 1 - (remaining + 1); + int v; + if ((fwd_peek(&in, bits - 1) & lower) < thr) { + v = fwd_read(&in, bits - 1); + } else { + v = fwd_read(&in, bits); + if (v > lower) + v -= thr; + } + int c = v - 1; + remaining -= c < 0 ? -c : c; + cnt[k++] = c; + if (c == 0) { + for (;;) { + int rep = fwd_read(&in, 2); + for (int j = 0; j < rep && k < max_sym; j++) + cnt[k++] = 0; + if (rep != 3 || in.bad) + break; + } + } + if (remaining < 0) + return -1; + bits = hbit((unsigned)remaining + 1) + 1; + if (in.bad) + return -1; + } + if (remaining != 0 || in.bad) + return -1; + *nc = k; + *al_out = al; + return (int)((in.pos + 7) / 8); +} + +/* a Huffman table from the weights of symbols 0..nw-1, the last's (nw) + implied (4.2.1) */ +static int huf_build(huf_t *h, const int *w, int nw) +{ + int sum = 0; + for (int i = 0; i < nw; i++) { + if (w[i] > HUF_MAX + 1 || w[i] < 0) + return 0; + if (w[i] != 0) + sum += 1 << (w[i] - 1); + } + if (sum == 0 || nw > 255) + return 0; + int mb = hbit((unsigned)sum) + 1; + int left = (1 << mb) - sum; + if (mb > HUF_MAX || (left & (left - 1)) != 0) + return 0; + int bits[256]; + for (int s = 0; s < nw; s++) + bits[s] = w[s] != 0 ? mb + 1 - w[s] : 0; + bits[nw] = mb + 1 - (hbit((unsigned)left) + 1); + int rank_cnt[HUF_MAX + 2] = { 0 }, rank_idx[HUF_MAX + 2] = { 0 }; + for (int s = 0; s <= nw; s++) + if (bits[s] != 0) + rank_cnt[bits[s]]++; + rank_idx[mb] = 0; + for (int i = mb; i >= 1; i--) + rank_idx[i - 1] = rank_idx[i] + rank_cnt[i] * (1 << (mb - i)); + h->max_bits = mb; + for (int s = 0; s <= nw; s++) { + if (bits[s] == 0) + continue; + int len = 1 << (mb - bits[s]); + int at = rank_idx[bits[s]]; + if (at + len > (1 << mb)) + return 0; + for (int k = 0; k < len; k++) { + h->sym[at + k] = (u8)s; + h->nb[at + k] = (u8)bits[s]; + } + rank_idx[bits[s]] += len; + } + return 1; +} + +/* a Huffman tree description at p[0..n): its bytes, or -1 */ +static int huf_desc(const u8 *p, int n, huf_t *h) +{ + int w[256], nw = 0, used; + if (n < 1) + return -1; + int h0 = p[0]; + if (h0 >= 128) { + int cnt = h0 - 127; + used = 1 + (cnt + 1) / 2; + if (used > n) + return -1; + for (int i = 0; i < cnt; i++) { + int b = p[1 + i / 2]; + w[nw++] = (i & 1) ? b & 15 : b >> 4; + } + } else { + int cs = h0, cnt[256], nc, al; + used = 1 + cs; + if (used > n || cs == 0) + return -1; + int d = fse_desc(p + 1, cs, 6, 255, cnt, &nc, &al); + if (d < 0 || d >= cs) + return -1; + fse_t *t = malloc(sizeof *t); + if (!t) + return -1; + back_bits in; + if (!fse_build(t, cnt, nc, al) || !back_init(&in, p + 1 + d, cs - d)) { + free(t); + return -1; + } + int s1 = (int)back_read(&in, al), s2 = (int)back_read(&in, al); + for (;;) { + if (nw > 253) { + free(t); + return -1; + } + w[nw++] = t->sym[s1]; + s1 = t->base[s1] + (int)back_read(&in, t->nb[s1]); + if (in.off < 0) { + w[nw++] = t->sym[s2]; + break; + } + w[nw++] = t->sym[s2]; + s2 = t->base[s2] + (int)back_read(&in, t->nb[s2]); + if (in.off < 0) { + w[nw++] = t->sym[s1]; + break; + } + } + free(t); + } + return huf_build(h, w, nw) ? used : -1; +} + +/* a Huffman coded stream into out[0..count); 0 if bad */ +static int huf_stream(const huf_t *h, const u8 *p, int n, int count, u8 *out) +{ + back_bits in; + if (!back_init(&in, p, n)) + return 0; + int mask = (1 << h->max_bits) - 1; + int st = (int)back_read(&in, h->max_bits); + for (int k = 0; k < count; k++) { + out[k] = h->sym[st]; + int nb = h->nb[st]; + st = ((st << nb) & mask) | (int)back_read(&in, nb); + } + return in.off + h->max_bits == 0; +} + +static int len_code(int v, const int *base, int n) +{ + int c = 0; + while (c + 1 < n && base[c + 1] <= v) + c++; + return c; +} + +/* the repeat offsets after a sequence's offset value (3.2.2.3): its + offset */ +static i64 apply_offset(i64 *rep, i64 ov, int ll) +{ + if (ov > 3) { + rep[2] = rep[1]; + rep[1] = rep[0]; + rep[0] = ov - 3; + return rep[0]; + } + int idx = (int)ov - 1 + (ll == 0 ? 1 : 0); + if (idx == 0) + return rep[0]; + i64 off = idx == 3 ? rep[0] - 1 : rep[idx]; + if (idx > 1) + rep[2] = rep[1]; + rep[1] = rep[0]; + rep[0] = off; + return off; +} + +/* ------------------------------------------------------------------ */ +/* the encoder's tables */ + +/* an FSE encoder: each symbol's states in order */ +typedef struct { + int al, nsym; + int cnt[53]; + int first[54]; + int states[FSE_MAX]; +} fse_enc; + +static void fse_enc_init(fse_enc *e, const int *c, int nsym, int al) +{ + fse_t t; + int fill[53]; + e->al = al; + e->nsym = nsym; + memcpy(e->cnt, c, sizeof(int) * (size_t)nsym); + fse_build(&t, c, nsym, al); + e->first[0] = 0; + for (int s = 0; s < nsym; s++) { + int k = c[s] < 0 ? 1 : c[s]; + e->first[s + 1] = e->first[s] + k; + fill[s] = e->first[s]; + } + for (int i = 0; i < (1 << al); i++) + e->states[fill[t.sym[i]]++] = i; +} + +static int fse_enc_step(const fse_enc *e, int st, int s, bit_w *w) +{ + int c = e->cnt[s] < 0 ? 1 : e->cnt[s]; + int x = st + (1 << e->al); + int nb = hbit((unsigned)x) - hbit((unsigned)c); + if ((x >> nb) < c) + nb--; + int d = x >> nb; + bw_put(w, (u64)(x & ((1 << nb) - 1)), nb); + return e->states[e->first[s] + d - c]; +} + +/* Huffman code lengths of the counts, none over HUF_MAX; 0 with fewer + than two symbols */ +static int huf_lengths(const int *freq, int *bits) +{ + int f[256]; + i64 w[512]; + int l[512], r[512], live[256], stk_i[512], stk_d[512]; + memcpy(f, freq, sizeof f); + for (;;) { + int nn = 0, nl = 0; + for (int s = 0; s < 256; s++) + if (f[s] != 0) { + w[nn] = f[s]; + l[nn] = -1; + r[nn] = s; + live[nl++] = nn++; + } + if (nl < 2) + return 0; + /* the two lightest (the earlier on a tie) */ + while (nl > 1) { + int pick[2]; + for (int j = 0; j < 2; j++) { + int ia = 0; + for (int k = 1; k < nl; k++) { + int a = live[k], b = live[ia]; + if (w[a] != w[b] ? w[a] < w[b] : a < b) + ia = k; + } + pick[j] = live[ia]; + memmove(live + ia, live + ia + 1, sizeof(int) * (size_t)(nl - ia - 1)); + nl--; + } + w[nn] = w[pick[0]] + w[pick[1]]; + l[nn] = pick[0]; + r[nn] = pick[1]; + live[nl++] = nn++; + } + int mx = 0, sp = 0; + memset(bits, 0, sizeof(int) * 256); + stk_i[sp] = live[0]; + stk_d[sp++] = 0; + while (sp > 0) { + sp--; + int i = stk_i[sp], d = stk_d[sp]; + if (l[i] < 0) { + bits[r[i]] = d; + if (d > mx) + mx = d; + } else { + stk_i[sp] = l[i]; + stk_d[sp++] = d + 1; + stk_i[sp] = r[i]; + stk_d[sp++] = d + 1; + } + } + if (mx <= HUF_MAX) + return 1; + for (int s = 0; s < 256; s++) + if (f[s] != 0) + f[s] = (f[s] + 1) / 2; + } +} + +/* the codes of the lengths, as the decoder's table has them */ +static void huf_codes(const int *bits, int *code) +{ + int mb = 0; + int rank_cnt[HUF_MAX + 2] = { 0 }, rank_idx[HUF_MAX + 2] = { 0 }; + for (int s = 0; s < 256; s++) + if (bits[s] > mb) + mb = bits[s]; + for (int s = 0; s < 256; s++) + if (bits[s] != 0) + rank_cnt[bits[s]]++; + rank_idx[mb] = 0; + for (int i = mb; i >= 1; i--) + rank_idx[i - 1] = rank_idx[i] + rank_cnt[i] * (1 << (mb - i)); + for (int s = 0; s < 256; s++) { + code[s] = 0; + if (bits[s] == 0) + continue; + code[s] = rank_idx[bits[s]] >> (mb - bits[s]); + rank_idx[bits[s]] += 1 << (mb - bits[s]); + } +} + +static void huf_encode(const u8 *lit, int from, int to, const int *bits, const int *code, zb *o) +{ + bit_w w = { { 0 }, 0, 0 }; + for (int k = to - 1; k >= from; k--) + bw_put(&w, (u64)code[lit[k]], bits[lit[k]]); + bw_close(&w); + zb_add(o, w.b.p, w.b.n); + if (w.b.oom) + o->oom = 1; + zb_free(&w.b); +} + +static void lit_header(zb *o, int type, int regen, int comp, int one_stream) +{ + if (type < 2) { + if (regen < 32) { + zb_put(o, type | (regen << 3)); + } else if (regen < 4096) { + zb_put(o, type | (1 << 2) | ((regen & 15) << 4)); + zb_put(o, (regen >> 4) & 0xff); + } else { + zb_put(o, type | (3 << 2) | ((regen & 15) << 4)); + zb_put(o, (regen >> 4) & 0xff); + zb_put(o, (regen >> 12) & 0xff); + } + return; + } + int sf, nb, hs; + if (one_stream) { + sf = 0; nb = 10; hs = 3; + } else if (regen < 1024 && comp < 1024) { + sf = 1; nb = 10; hs = 3; + } else if (regen < 16384 && comp < 16384) { + sf = 2; nb = 14; hs = 4; + } else { + sf = 3; nb = 18; hs = 5; + } + u64 h = (u64)type | ((u64)sf << 2) | ((u64)regen << 4) | ((u64)comp << (4 + nb)); + for (int k = 0; k < hs; k++) + zb_put(o, (int)((h >> (8 * k)) & 0xff)); +} + +/* the literals coded (one stream under 1024, else four and the jump + table) into o; 0 if a stream is too large */ +static int huf_section(const u8 *lit, int n, const int *bits, zb *o) +{ + int code[256]; + huf_codes(bits, code); + if (n < 1024) { + huf_encode(lit, 0, n, bits, code, o); + return 1; + } + int seg = (n + 3) / 4; + zb s[4]; + memset(s, 0, sizeof s); + for (int k = 0; k < 4; k++) { + int a = k * seg < n ? k * seg : n, b = (k + 1) * seg < n ? (k + 1) * seg : n; + huf_encode(lit, a, b, bits, code, &s[k]); + } + int ok = 1; + for (int k = 0; k < 3; k++) { + if (s[k].n > 65535) + ok = 0; + zb_put(o, s[k].n & 0xff); + zb_put(o, (s[k].n >> 8) & 0xff); + } + for (int k = 0; k < 4; k++) { + zb_add(o, s[k].p, s[k].n); + if (s[k].oom) + o->oom = 1; + zb_free(&s[k]); + } + return ok; +} + +static void fse_normalize(const int *f, int nsym, int al, int *c) +{ + i64 total = 0; + int size = 1 << al, sum = 0, big = 0; + for (int s = 0; s < nsym; s++) + total += f[s]; + for (int s = 0; s < nsym; s++) { + c[s] = 0; + if (f[s] == 0) + continue; + i64 v = ((i64)f[s] * size + total / 2) / total; + c[s] = v < 1 ? 1 : (int)v; + sum += c[s]; + if (c[s] > c[big]) + big = s; + } + c[big] += size - sum; + while (c[big] < 1) { + int need = 1 - c[big]; + c[big] = 1; + for (int s = 0; s < nsym; s++) { + while (need > 0 && s != big && c[s] > 1) { + c[s]--; + need--; + } + if (need == 0) + break; + } + } +} + +static void fse_desc_write(const int *c, int n, int al, zb *o) +{ + bit_w w = { { 0 }, 0, 0 }; + bw_put(&w, (u64)(al - 5), 4); + int remaining = 1 << al, s = 0; + while (s < n && remaining > 0) { + int bits = hbit((unsigned)remaining + 1) + 1; + int lower = (1 << (bits - 1)) - 1; + int thr = (1 << bits) - 1 - (remaining + 1); + int v = c[s] + 1; + if (v < thr) + bw_put(&w, (u64)v, bits - 1); + else if (v <= lower) + bw_put(&w, (u64)v, bits); + else + bw_put(&w, (u64)(v + thr), bits); + remaining -= c[s] < 0 ? -c[s] : c[s]; + s++; + if (c[s - 1] == 0) { + int z = 0; + while (s + z < n && c[s + z] == 0) + z++; + s += z; + while (z >= 3) { + bw_put(&w, 3, 2); + z -= 3; + } + bw_put(&w, (u64)z, 2); + } + } + if (w.n != 0) + bw_put(&w, 0, 8 - w.n); + zb_add(o, w.b.p, w.b.n); + if (w.b.oom) + o->oom = 1; + zb_free(&w.b); +} + +static double fse_cost(const int *cnt, int ncnt, int al, const int *sym, int ns) +{ + double bits = 0; + for (int k = 0; k < ns; k++) { + int x = sym[k]; + if (x >= ncnt || cnt[x] == 0) + return -1; + int c = cnt[x] < 0 ? 1 : cnt[x]; + int hb = hbit((unsigned)c); + bits += al - (hb + (double)(c - (1 << hb)) / (1 << hb)); + } + return bits; +} + +/* ------------------------------------------------------------------ */ +/* the encoder */ + +struct enc { + const u8 *hist; + int n, window; + i64 rep[3]; + int head[1 << 14]; + int *chain; + int ins; + int enc_bits[256], has_enc_bits; + zb out; + int match_off; + /* a block's sequences */ + int *sq_ll, *sq_ov, *sq_ml, *llc, *ofc, *mlc; +}; + +static int hash3(const u8 *h, int i) +{ + uint32_t v = ((uint32_t)h[i] << 16) | ((uint32_t)h[i + 1] << 8) | h[i + 2]; + return (int)((v * 2654435761u) >> 18); +} + +static void enc_insert(struct enc *e, int i) +{ + if (i + 2 >= e->n) + return; + int h = hash3(e->hist, i); + e->chain[i] = e->head[h]; + e->head[h] = i + 1; +} + +static int len_at(const u8 *h, int i, int d, int lim) +{ + int l = 0; + while (l < lim && h[i - d + l] == h[i + l]) + l++; + return l; +} + +static int best_match(struct enc *e, int i, int end) +{ + int lim = end - i < 65536 ? end - i : 65536, best = 0; + for (int r = 0; r < 3; r++) { + i64 d = e->rep[r]; + if (d <= 0 || d > i || d > e->window) + continue; + int l = len_at(e->hist, i, (int)d, lim); + if (l > best) { + best = l; + e->match_off = (int)d; + } + } + int rep_best = best; + if (lim >= 3) { + int c = e->head[hash3(e->hist, i)], depth = 48; + while (c != 0 && depth-- > 0) { + int cand = c - 1, d = i - cand; + if (d > e->window || d <= 0) + break; + int l = len_at(e->hist, i, d, lim); + if (l > best && (l > rep_best + 1 || best < 3) && (l > 3 || d <= 1024)) { + best = l; + e->match_off = d; + } + if (best == lim) + break; + c = e->chain[cand]; + } + } + return best >= 3 ? best : 0; +} + +static void put_block(struct enc *e, const u8 *body, int body_n, int type, int size, int last) +{ + int h = (last ? 1 : 0) | (type << 1) | (size << 3); + zb_put(&e->out, h & 0xff); + zb_put(&e->out, (h >> 8) & 0xff); + zb_put(&e->out, (h >> 16) & 0xff); + zb_add(&e->out, body, body_n); +} + +static void enc_catch_up(struct enc *e, int upto) +{ + while (e->ins < upto) { + enc_insert(e, e->ins); + e->ins++; + } +} + +static void enc_block(struct enc *e, int start, int end, int last) +{ + const u8 *hist = e->hist; + int nb = end - start; + i64 rep_saved[3]; + memcpy(rep_saved, e->rep, sizeof rep_saved); + int ns = 0; + zb lit = { 0 }, best_lit = { 0 }, body = { 0 }; + int i = start, lit_at = start; + if (e->ins < start) + e->ins = start; + while (i + 3 <= end) { + enc_catch_up(e, i); + int len = best_match(e, i, end); + int off = e->match_off; + if (len != 0 && i + 1 + 3 <= end) { + enc_catch_up(e, i + 1); + int len2 = best_match(e, i + 1, end); + if (len2 > len + 1) { + i++; + continue; + } + } + if (len == 0) { + i++; + continue; + } + int ll = i - lit_at; + int ov; + if (ll != 0) + ov = off == e->rep[0] ? 1 : off == e->rep[1] ? 2 : off == e->rep[2] ? 3 : off + 3; + else + ov = off == e->rep[1] ? 1 : off == e->rep[2] ? 2 : off == e->rep[0] - 1 ? 3 : off + 3; + apply_offset(e->rep, ov, ll); + zb_add(&lit, hist + lit_at, i - lit_at); + e->sq_ll[ns] = ll; + e->sq_ov[ns] = ov; + e->sq_ml[ns] = len; + ns++; + i += len; + lit_at = i; + } + zb_add(&lit, hist + lit_at, end - lit_at); + enc_catch_up(e, e->ins > end - 2 ? e->ins : end - 2); + + /* the literals: raw, RLE, Huffman with a new table or the last */ + int nl = lit.n, freq[256] = { 0 }, kinds = 0, last_sym = 0; + int new_bits[256], has_new_bits = 0; + for (int k = 0; k < nl; k++) + freq[lit.p[k]]++; + for (int s = 0; s < 256; s++) + if (freq[s] != 0) { + kinds++; + last_sym = s; + } + lit_header(&best_lit, 0, nl, 0, 0); + zb_add(&best_lit, lit.p, nl); + if (kinds == 1 && nl > 1) { + zb r = { 0 }; + lit_header(&r, 1, nl, 0, 0); + zb_put(&r, lit.p[0]); + if (r.n < best_lit.n) { + zb_free(&best_lit); + best_lit = r; + } else + zb_free(&r); + } else if (kinds > 1 && nl >= 16) { + int bits[256]; + if (last_sym <= 128 && huf_lengths(freq, bits)) { + int mb = 0; + zb desc = { 0 }, st = { 0 }; + for (int s = 0; s < 256; s++) + if (bits[s] > mb) + mb = bits[s]; + zb_put(&desc, 127 + last_sym); + for (int s = 0; s < last_sym; s += 2) { + int w0 = bits[s] != 0 ? mb + 1 - bits[s] : 0; + int w1 = s + 1 < last_sym && bits[s + 1] != 0 ? mb + 1 - bits[s + 1] : 0; + zb_put(&desc, (w0 << 4) | w1); + } + if (huf_section(lit.p, nl, bits, &st)) { + int comp = desc.n + st.n; + if (!(nl < 1024 && comp >= 1024)) { + zb r = { 0 }; + lit_header(&r, 2, nl, comp, nl < 1024); + zb_add(&r, desc.p, desc.n); + zb_add(&r, st.p, st.n); + if (r.n < best_lit.n && !r.oom) { + zb_free(&best_lit); + best_lit = r; + memcpy(new_bits, bits, sizeof new_bits); + has_new_bits = 1; + } else + zb_free(&r); + } + } + zb_free(&desc); + zb_free(&st); + } + int fits = e->has_enc_bits; + for (int s = 0; fits && s < 256; s++) + if (freq[s] != 0 && e->enc_bits[s] == 0) + fits = 0; + if (fits) { + zb st = { 0 }; + if (huf_section(lit.p, nl, e->enc_bits, &st) && !(nl < 1024 && st.n >= 1024)) { + zb r = { 0 }; + lit_header(&r, 3, nl, st.n, nl < 1024); + zb_add(&r, st.p, st.n); + if (r.n < best_lit.n && !r.oom) { + zb_free(&best_lit); + best_lit = r; + has_new_bits = 0; + } else + zb_free(&r); + } + zb_free(&st); + } + } + zb_add(&body, best_lit.p, best_lit.n); + + /* the sequences */ + if (ns < 128) { + zb_put(&body, ns); + } else if (ns < 0x7F00) { + zb_put(&body, (ns >> 8) + 128); + zb_put(&body, ns & 0xff); + } else { + zb_put(&body, 255); + zb_put(&body, (ns - 0x7F00) & 0xff); + zb_put(&body, (ns - 0x7F00) >> 8); + } + if (ns != 0) { + int *llc = e->llc, *mlc = e->mlc, *ofc = e->ofc; + for (int k = 0; k < ns; k++) { + llc[k] = len_code(e->sq_ll[k], LL_BASE, 36); + mlc[k] = len_code(e->sq_ml[k], ML_BASE, 53); + ofc[k] = hbit((unsigned)e->sq_ov[k]); + } + const int *codes[3] = { llc, ofc, mlc }; + const int *defs[3] = { LL_DEF, OF_DEF, ML_DEF }; + const int ndefs[3] = { 36, 29, 53 }; + const int dal[3] = { 6, 5, 6 }, max_al[3] = { 9, 8, 9 }; + fse_enc enc[3]; + int modes = 0; + zb descs = { 0 }; + for (int t = 0; t < 3; t++) { + double cp = fse_cost(defs[t], ndefs[t], dal[t], codes[t], ns); + int f[53] = { 0 }, nsym = 0, k2 = 0, nc[53]; + for (int k = 0; k < ns; k++) { + int x = codes[t][k]; + if (f[x]++ == 0) + k2++; + if (x + 1 > nsym) + nsym = x + 1; + } + int al = hbit((unsigned)ns) - 1; + if (al < 5) + al = 5; + if (hbit((unsigned)k2) + 1 > al) + al = hbit((unsigned)k2) + 1; + if (al > max_al[t]) + al = max_al[t]; + fse_normalize(f, nsym, al, nc); + zb d = { 0 }; + fse_desc_write(nc, nsym, al, &d); + double cn = 8.0 * d.n + fse_cost(nc, nsym, al, codes[t], ns); + if (cp >= 0 && cp <= cn) { + fse_enc_init(&enc[t], defs[t], ndefs[t], dal[t]); + } else { + modes |= 2 << (6 - 2 * t); + zb_add(&descs, d.p, d.n); + fse_enc_init(&enc[t], nc, nsym, al); + } + zb_free(&d); + } + zb_put(&body, modes); + zb_add(&body, descs.p, descs.n); + if (descs.oom) + body.oom = 1; + zb_free(&descs); + const fse_enc *fl = &enc[0], *fo = &enc[1], *fm = &enc[2]; + bit_w w = { { 0 }, 0, 0 }; + int k = ns - 1; + int sl = fl->states[fl->first[llc[k]]]; + int sm = fm->states[fm->first[mlc[k]]]; + int so = fo->states[fo->first[ofc[k]]]; + for (;;) { + bw_put(&w, (u64)(e->sq_ll[k] - LL_BASE[llc[k]]), LL_BITS[llc[k]]); + bw_put(&w, (u64)(e->sq_ml[k] - ML_BASE[mlc[k]]), ML_BITS[mlc[k]]); + bw_put(&w, (u64)(e->sq_ov[k] - (1 << ofc[k])), ofc[k]); + if (--k < 0) + break; + so = fse_enc_step(fo, so, ofc[k], &w); + sm = fse_enc_step(fm, sm, mlc[k], &w); + sl = fse_enc_step(fl, sl, llc[k], &w); + } + bw_put(&w, (u64)sm, fm->al); + bw_put(&w, (u64)so, fo->al); + bw_put(&w, (u64)sl, fl->al); + bw_close(&w); + zb_add(&body, w.b.p, w.b.n); + if (w.b.oom) + body.oom = 1; + zb_free(&w.b); + } + if (lit.oom || best_lit.oom || body.oom) + e->out.oom = 1; + + u8 first = hist[start]; + int same = 1, coded = 0; + for (int k = start; k < end; k++) + if (hist[k] != first) { + same = 0; + break; + } + if (same && nb > 1) { + put_block(e, &first, 1, 1, nb, last); + } else if (body.n < nb) { + put_block(e, body.p, body.n, 2, body.n, last); + if (has_new_bits) { + memcpy(e->enc_bits, new_bits, sizeof new_bits); + e->has_enc_bits = 1; + } + coded = 1; + } else { + put_block(e, hist + start, nb, 0, nb, last); + } + /* (the decoder saw no sequences of a block not coded: its offsets as + before) */ + if (!coded) + memcpy(e->rep, rep_saved, sizeof rep_saved); + zb_free(&lit); + zb_free(&best_lit); + zb_free(&body); +} + +unsigned char *zc_encode(const unsigned char *data, int n, int *out_n) +{ + struct enc *e = calloc(1, sizeof *e); + unsigned char *res = NULL; + int blk = n < MAX_BLOCK ? n : MAX_BLOCK; + if (!e) + return NULL; + e->hist = data; + e->n = n; + e->window = n > 1 ? n : 1; + e->rep[0] = 1; + e->rep[1] = 4; + e->rep[2] = 8; + e->chain = malloc(sizeof(int) * (size_t)(n > 0 ? n : 1)); + e->sq_ll = malloc(sizeof(int) * (size_t)(blk / 3 + 1)); + e->sq_ov = malloc(sizeof(int) * (size_t)(blk / 3 + 1)); + e->sq_ml = malloc(sizeof(int) * (size_t)(blk / 3 + 1)); + e->llc = malloc(sizeof(int) * (size_t)(blk / 3 + 1)); + e->ofc = malloc(sizeof(int) * (size_t)(blk / 3 + 1)); + e->mlc = malloc(sizeof(int) * (size_t)(blk / 3 + 1)); + if (e->chain && e->sq_ll && e->sq_ov && e->sq_ml && e->llc && e->ofc && e->mlc) { + /* the header: single segment, the checksum, the content size */ + int fcs_flag = n < 256 ? 0 : n < 65536 + 256 ? 1 : 2; + zb_put(&e->out, 0x28); + zb_put(&e->out, 0xB5); + zb_put(&e->out, 0x2F); + zb_put(&e->out, 0xFD); + zb_put(&e->out, (fcs_flag << 6) | 0x20 | 0x04); + if (fcs_flag == 0) { + zb_put(&e->out, n); + } else if (fcs_flag == 1) { + zb_put(&e->out, (n - 256) & 0xff); + zb_put(&e->out, (n - 256) >> 8); + } else { + for (int k = 0; k < 4; k++) + zb_put(&e->out, (n >> (8 * k)) & 0xff); + } + if (n == 0) + put_block(e, NULL, 0, 0, 0, 1); + for (int at = 0; at < n;) { + int len = n - at < MAX_BLOCK ? n - at : MAX_BLOCK; + enc_block(e, at, at + len, at + len == n); + at += len; + } + u64 sum = zc_xxh64(data, (size_t)n); + for (int k = 0; k < 4; k++) + zb_put(&e->out, (int)((sum >> (8 * k)) & 0xff)); + if (!e->out.oom) { + res = e->out.p; + *out_n = e->out.n; + e->out.p = NULL; + } + } + zb_free(&e->out); + free(e->chain); + free(e->sq_ll); + free(e->sq_ov); + free(e->sq_ml); + free(e->llc); + free(e->ofc); + free(e->mlc); + free(e); + return res; +} + +/* ------------------------------------------------------------------ */ +/* the decoder */ + +struct dec { + const u8 *p; + int max; + u8 *hist; + int hn, hcap; + u8 *lit; /* a block's literals */ + int nlit; + i64 rep[3]; + huf_t huf; + fse_t ll, of, ml; + int have[3]; + i64 window; + jmp_buf jb; + const char *why; +}; + +#if defined(__GNUC__) || defined(__clang__) +__attribute__((noreturn)) +#endif +static void bad(struct dec *d, const char *why) +{ + d->why = why; + longjmp(d->jb, 1); +} + +static void emit(struct dec *d, u8 c) +{ + if (d->hn >= d->max) + bad(d, "more content than the limit"); + if (d->hn == d->hcap) { + int cap = d->hcap * 2 < d->max ? d->hcap * 2 : d->max; + u8 *q = realloc(d->hist, (size_t)cap); + if (!q) + bad(d, "no memory"); + d->hist = q; + d->hcap = cap; + } + d->hist[d->hn++] = c; +} + +static int dec_literals(struct dec *d, int at, int n) +{ + const u8 *p = d->p; + if (n < 1) + bad(d, "no literals"); + int b0 = p[at], type = b0 & 3, sf = (b0 >> 2) & 3; + d->nlit = 0; + if (type < 2) { + int regen, hs; + if ((sf & 1) == 0) { + regen = b0 >> 3; + hs = 1; + } else if (sf == 1) { + if (n < 2) + bad(d, "bad literals"); + regen = (b0 >> 4) | (p[at + 1] << 4); + hs = 2; + } else { + if (n < 3) + bad(d, "bad literals"); + regen = (b0 >> 4) | (p[at + 1] << 4) | (p[at + 2] << 12); + hs = 3; + } + if (regen > MAX_BLOCK) + bad(d, "bad literals"); + if (type == 0) { + if (hs + regen > n) + bad(d, "bad literals"); + memcpy(d->lit, p + at + hs, (size_t)regen); + d->nlit = regen; + return hs + regen; + } + if (hs + 1 > n) + bad(d, "bad literals"); + memset(d->lit, p[at + hs], (size_t)regen); + d->nlit = regen; + return hs + 1; + } + int streams = sf == 0 ? 1 : 4; + int hs = sf < 2 ? 3 : sf == 2 ? 4 : 5; + int nb = sf < 2 ? 10 : sf == 2 ? 14 : 18; + if (n < hs) + bad(d, "bad literals"); + u64 h = 0; + for (int k = 0; k < hs; k++) + h |= (u64)p[at + k] << (8 * k); + int regen = (int)((h >> 4) & ((1u << nb) - 1)); + int comp = (int)((h >> (4 + nb)) & ((1u << nb) - 1)); + if (hs + comp > n || regen > MAX_BLOCK) + bad(d, "bad literals"); + int q = at + hs, left = comp; + if (type == 2) { + int k = huf_desc(p + q, left, &d->huf); + if (k < 0) + bad(d, "a bad Huffman table"); + q += k; + left -= k; + } else if (d->huf.max_bits == 0) + bad(d, "no Huffman table"); + if (streams == 1) { + if (!huf_stream(&d->huf, p + q, left, regen, d->lit)) + bad(d, "bad Huffman data"); + } else { + if (left < 6) + bad(d, "bad literals"); + int sz[4]; + sz[0] = p[q] | (p[q + 1] << 8); + sz[1] = p[q + 2] | (p[q + 3] << 8); + sz[2] = p[q + 4] | (p[q + 5] << 8); + sz[3] = left - 6 - sz[0] - sz[1] - sz[2]; + if (sz[3] < 0) + bad(d, "bad literals"); + int seg = (regen + 3) / 4, o = 0; + q += 6; + for (int k = 0; k < 4; k++) { + int cnt = k < 3 ? seg : regen - 3 * seg; + if (cnt < 0 || !huf_stream(&d->huf, p + q, sz[k], cnt, d->lit + o)) + bad(d, "bad Huffman data"); + o += cnt; + q += sz[k]; + } + } + d->nlit = regen; + return hs + comp; +} + +static void dec_sequences(struct dec *d, int start, int n) +{ + const u8 *p = d->p; + if (n < 1) + bad(d, "no sequences"); + int at = start, b0 = p[at], ns; + if (b0 < 128) { + ns = b0; + at += 1; + } else if (b0 < 255) { + if (n < 2) + bad(d, "bad sequences"); + ns = ((b0 - 128) << 8) + p[at + 1]; + at += 2; + } else { + if (n < 3) + bad(d, "bad sequences"); + ns = p[at + 1] + (p[at + 2] << 8) + 0x7F00; + at += 3; + } + int end = start + n, li = 0; + if (ns != 0) { + if (at >= end) + bad(d, "bad sequences"); + int modes = p[at++]; + if (modes & 3) + bad(d, "bad sequences"); + fse_t *tabs[3] = { &d->ll, &d->of, &d->ml }; + const int *defs[3] = { LL_DEF, OF_DEF, ML_DEF }; + const int ndefs[3] = { 36, 29, 53 }; + const int nsyms[3] = { 36, 32, 53 }; + const int def_al[3] = { 6, 5, 6 }, max_al[3] = { 9, 8, 9 }; + for (int t = 0; t < 3; t++) { + switch ((modes >> (6 - 2 * t)) & 3) { + case 0: + fse_build(tabs[t], defs[t], ndefs[t], def_al[t]); + break; + case 1: + if (at >= end || p[at] >= nsyms[t]) + bad(d, "bad sequences"); + tabs[t]->log = 0; + tabs[t]->sym[0] = p[at++]; + tabs[t]->nb[0] = 0; + tabs[t]->base[0] = 0; + break; + case 2: { + int cnt[256], nc, al; + int k = fse_desc(p + at, end - at, max_al[t], nsyms[t], cnt, &nc, &al); + if (k < 0 || !fse_build(tabs[t], cnt, nc, al)) + bad(d, "a bad FSE table"); + at += k; + break; + } + default: + if (!d->have[t]) + bad(d, "no FSE table to repeat"); + } + d->have[t] = 1; + } + back_bits in; + if (!back_init(&in, p + at, end - at)) + bad(d, "bad sequences"); + int sl = (int)back_read(&in, d->ll.log); + int so = (int)back_read(&in, d->of.log); + int sm = (int)back_read(&in, d->ml.log); + for (int k = 0; k < ns; k++) { + int llc = d->ll.sym[sl], ofc = d->of.sym[so], mlc = d->ml.sym[sm]; + if (llc > 35 || mlc > 52 || ofc > 31) + bad(d, "bad sequences"); + i64 ov = ((i64)1 << ofc) + (i64)back_read(&in, ofc); + int mlen = ML_BASE[mlc] + (int)back_read(&in, ML_BITS[mlc]); + int llen = LL_BASE[llc] + (int)back_read(&in, LL_BITS[llc]); + if (k + 1 < ns) { + sl = d->ll.base[sl] + (int)back_read(&in, d->ll.nb[sl]); + sm = d->ml.base[sm] + (int)back_read(&in, d->ml.nb[sm]); + so = d->of.base[so] + (int)back_read(&in, d->of.nb[so]); + } + if (in.off < 0 || li + llen > d->nlit) + bad(d, "bad sequences"); + for (int j = 0; j < llen; j++) + emit(d, d->lit[li++]); + i64 off = apply_offset(d->rep, ov, llen); + if (off <= 0 || off > d->hn || off > d->window) + bad(d, "a bad offset"); + int from = d->hn - (int)off; + for (int j = 0; j < mlen; j++) + emit(d, d->hist[from + j]); + } + } + while (li < d->nlit) + emit(d, d->lit[li++]); +} + +static void dec_run(struct dec *d, int n) +{ + const u8 *p = d->p; + if (n < 6) + bad(d, "too short"); + uint32_t magic = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + if (magic != ZC_MAGIC) + bad(d, "not a frame"); + int fhd = p[4], single = (fhd & 0x20) != 0; + if (fhd & 0x08) + bad(d, "a reserved bit"); + if (fhd & 3) + bad(d, "a dictionary"); + int checksum = (fhd & 0x04) != 0, fcs_flag = fhd >> 6; + int fcs = fcs_flag == 0 ? (single ? 1 : 0) : 1 << fcs_flag; + int at = 5; + i64 win = 0, size = -1; + if (!single) { + int wd = p[at++]; + i64 wb = (i64)1 << (10 + (wd >> 3)); + win = wb + wb / 8 * (wd & 7); + } + if (fcs != 0) { + if (at + fcs > n) + bad(d, "too short"); + u64 v = 0; + for (int k = 0; k < fcs; k++) + v |= (u64)p[at + k] << (8 * k); + if (fcs == 2) + v += 256; + if (v > (u64)d->max) + bad(d, "content over the limit"); + size = (i64)v; + if (single) + win = size; + at += fcs; + } + if (win > d->max) + bad(d, "a window over the limit"); + d->window = win > 1 ? win : 1; + for (;;) { + if (at + 3 > n) + bad(d, "too short"); + int h = p[at] | (p[at + 1] << 8) | (p[at + 2] << 16); + at += 3; + int last = h & 1, type = (h >> 1) & 3, bs = h >> 3; + if (type == 3 || bs > MAX_BLOCK) + bad(d, "a bad block"); + if (type == 0) { + if (at + bs > n) + bad(d, "too short"); + for (int k = 0; k < bs; k++) + emit(d, p[at + k]); + at += bs; + } else if (type == 1) { + if (at + 1 > n) + bad(d, "too short"); + for (int k = 0; k < bs; k++) + emit(d, p[at]); + at += 1; + } else { + if (at + bs > n) + bad(d, "too short"); + int l = dec_literals(d, at, bs); + dec_sequences(d, at + l, bs - l); + at += bs; + } + if (last) + break; + } + if (checksum) { + if (at + 4 > n) + bad(d, "too short"); + u64 sum = zc_xxh64(d->hist, (size_t)d->hn); + for (int k = 0; k < 4; k++) + if (p[at + k] != ((sum >> (8 * k)) & 0xff)) + bad(d, "a bad checksum"); + at += 4; + } + if (at != n) + bad(d, "bytes after the frame"); + if (size >= 0 && size != d->hn) + bad(d, "the wrong size"); +} + +unsigned char *zc_decode(const unsigned char *frame, int n, int max, int *out_n, const char **why) +{ + struct dec *d = calloc(1, sizeof *d); + unsigned char *res = NULL; + if (why) + *why = "no memory"; + if (!d) + return NULL; + d->p = frame; + d->max = max; + d->hcap = max < 1024 ? (max > 0 ? max : 1) : 1024; + d->hist = malloc((size_t)d->hcap); + d->lit = malloc(MAX_BLOCK); + d->rep[0] = 1; + d->rep[1] = 4; + d->rep[2] = 8; + if (d->hist && d->lit) { + if (setjmp(d->jb) == 0) { + dec_run(d, n); + res = d->hist; + *out_n = d->hn; + d->hist = NULL; + if (why) + *why = NULL; + } else if (why) { + *why = d->why; + } + } + free(d->hist); + free(d->lit); + free(d); + return res; +} + +int zc_frame_len(const unsigned char *b, int n, int max) +{ + if (n < 5) + return 0; + uint32_t magic = (uint32_t)b[0] | ((uint32_t)b[1] << 8) | ((uint32_t)b[2] << 16) | ((uint32_t)b[3] << 24); + if (magic != ZC_MAGIC) + return -1; + int fhd = b[4]; + /* (no reserved bit, no dictionary; the checksum and the content + size in it) */ + if ((fhd & 0x0b) || !(fhd & 0x04) || (!(fhd & 0x20) && (fhd >> 6) == 0)) + return -1; + int single = (fhd & 0x20) != 0; + int at = 5 + (single ? 0 : 1); + switch (fhd >> 6) { + case 0: at += single ? 1 : 0; break; + case 1: at += 2; break; + case 2: at += 4; break; + default: at += 8; + } + for (;;) { + if (n < at + 3) + return 0; + int bh = b[at] | (b[at + 1] << 8) | (b[at + 2] << 16); + at += 3; + int size = bh >> 3; + switch ((bh >> 1) & 3) { + case 0: + case 2: at += size; break; + case 1: at += 1; break; + default: return -1; + } + if (bh & 1) + break; + if (at > max + max / 8) + return -1; + } + if (fhd & 0x04) + at += 4; + return n < at ? 0 : at; +} + +/* ------------------------------------------------------------------ */ +/* XXH64 */ + +#define P1 0x9E3779B185EBCA87ULL +#define P2 0xC2B2AE3D27D4EB4FULL +#define P3 0x165667B19E3779F9ULL +#define P4 0x85EBCA77C2B2AE63ULL +#define P5 0x27D4EB2F165667C5ULL + +static u64 rotl(u64 v, int r) +{ + return (v << r) | (v >> (64 - r)); +} + +static u64 le64(const u8 *b) +{ + u64 v = 0; + for (int k = 0; k < 8; k++) + v |= (u64)b[k] << (8 * k); + return v; +} + +static u64 le32(const u8 *b) +{ + return (u64)b[0] | ((u64)b[1] << 8) | ((u64)b[2] << 16) | ((u64)b[3] << 24); +} + +static u64 xround(u64 acc, u64 in) +{ + return rotl(acc + in * P2, 31) * P1; +} + +static u64 xmerge(u64 acc, u64 v) +{ + return (acc ^ xround(0, v)) * P1 + P4; +} + +uint64_t zc_xxh64(const unsigned char *b, size_t len) +{ + const u8 *i = b, *end = b + len; + u64 h; + if (len >= 32) { + u64 v1 = P1 + P2, v2 = P2, v3 = 0, v4 = 0 - P1; + while (end - i >= 32) { + v1 = xround(v1, le64(i)); + v2 = xround(v2, le64(i + 8)); + v3 = xround(v3, le64(i + 16)); + v4 = xround(v4, le64(i + 24)); + i += 32; + } + h = rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18); + h = xmerge(h, v1); + h = xmerge(h, v2); + h = xmerge(h, v3); + h = xmerge(h, v4); + } else { + h = P5; + } + h += (u64)len; + while (end - i >= 8) { + h = rotl(h ^ xround(0, le64(i)), 27) * P1 + P4; + i += 8; + } + if (end - i >= 4) { + h = rotl(h ^ (le32(i) * P1), 23) * P2 + P3; + i += 4; + } + while (i < end) { + h = rotl(h ^ (*i * P5), 11) * P1; + i++; + } + h = (h ^ (h >> 33)) * P2; + h = (h ^ (h >> 29)) * P3; + return h ^ (h >> 32); +} diff --git a/core/src/zstd_codec.h b/core/src/zstd_codec.h new file mode 100644 index 0000000..62cae56 --- /dev/null +++ b/core/src/zstd_codec.h @@ -0,0 +1,46 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-only + * Copyright (C) 2026 D-Modem Authors + * + * zstd_codec.h - Zstandard (RFC 8878), whole frames, in plain C: the + * encoder makes one frame of a chunk (single segment, its + * content size and checksum in it, no dictionary), as + * ZMODEM with zstd sends a file (docs/zmodem-zstd.md of + * D-Modem); the decoder takes any frame up to its limit. + * A port of D-Modem's link/zstd_codec.cpp (and of the + * app's Zstd.kt): a hash chain over the chunk with a lazy + * match, the repeat offsets, literals raw, RLE or Huffman + * coded, each sequence table the predefined or a new one. + * Named so that it does not hide the system's . + */ +#ifndef DMC_ZSTD_CODEC_H +#define DMC_ZSTD_CODEC_H + +#include +#include + +#define ZC_MAGIC 0xFD2FB528u + +/* data[0..n) as one frame (malloc'd, its length in *out_n); NULL when + memory ran out */ +unsigned char *zc_encode(const unsigned char *data, int n, int *out_n); + +/* the content of the frame frame[0..n) (all of it, no more), malloc'd, + its length in *out_n (a frame of no content gives a block of 1 byte + that is not part of it); NULL if it is not a frame, has a dictionary, + a window or content over max, bad data or a bad checksum (why, if + not NULL, says which) */ +unsigned char *zc_decode(const unsigned char *frame, int n, int max, int *out_n, + const char **why); + +/* the length of the frame at the start of b[0..n) from its headers (RFC + 8878 3.1.1.1 and 3.1.1.2): 0 while not all of it is there, -1 if it is + not a frame that ZMODEM with zstd takes (a frame of no more than max + bytes of content, without a dictionary, with its content size and + checksum) */ +int zc_frame_len(const unsigned char *b, int n, int max); + +/* XXH64 (seed 0), Zstandard's content checksum */ +uint64_t zc_xxh64(const unsigned char *b, size_t n); + +#endif diff --git a/core/test/xfer_test.c b/core/test/xfer_test.c index cdfe4d8..763a608 100644 --- a/core/test/xfer_test.c +++ b/core/test/xfer_test.c @@ -28,6 +28,7 @@ #include "dmodemctl.h" #include "xfer.h" +#include "zstd_codec.h" static int failures; @@ -85,9 +86,12 @@ static void empty_dir(const char *dir) /* the two transfers' line, until both end: every noise-th byte from a damaged (0 none) */ +static long long line_bytes; /* what a sent in the last link2 */ + static void link2(dmc_xfer *a, dmc_xfer *b, int noise) { char buf[4096]; + line_bytes = 0; long long count = 0, end = xfer_now() + 180000; for (;;) { dmc_xfer_status sa, sb; @@ -106,6 +110,7 @@ static void link2(dmc_xfer *a, dmc_xfer *b, int noise) if (++count % noise == 0) buf[i] ^= 0x55; dmc_xfer_feed(b, buf, n); + line_bytes += n; moved = 1; } while ((n = dmc_xfer_output(b, buf, sizeof(buf))) > 0) { @@ -375,6 +380,206 @@ static void resume(void) dmc_xfer_free(r); } +/* ------------------------------------------------------------------ */ +/* ZMODEM with zstd */ + +static int have(const char *prog); + +/* n bytes of text that compresses, as a BBS's text files do */ +static unsigned char *text(size_t n, unsigned seed) +{ + static const char *const words[] = { + "modem", "carrier", "the", "BBS", "file", "area", "sysop", + "message", "ZMODEM", "of", "and", "a", "upload", "download", + "baud", "line", "\r\n" + }; + unsigned char *d = (unsigned char *)malloc(n + 16); + size_t at = 0; + unsigned r = seed * 2654435761u + 1; + while (at < n) { + r = r * 1103515245u + 12345u; + const char *w = words[(r >> 16) % (sizeof(words) / sizeof(words[0]))]; + size_t l = strlen(w); + for (size_t i = 0; i < l && at < n; i++) + d[at++] = (unsigned char)w[i]; + if (at < n) + d[at++] = ' '; + } + return d; +} + +/* the codec: the specification's frame, there and back, against the + reference zstd (where it is installed) */ +static void zstd_codec(void) +{ + static const unsigned char vec[55] = { + 0x28, 0xb5, 0x2f, 0xfd, 0x24, 0x66, 0x55, 0x01, 0x00, 0x24, 0x02, 0x44, 0x2d, 0x4d, + 0x6f, 0x64, 0x65, 0x6d, 0x20, 0x5a, 0x4d, 0x4f, 0x44, 0x45, 0x4d, 0x20, 0x7a, 0x73, + 0x74, 0x64, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x76, 0x65, 0x63, 0x74, 0x6f, 0x72, + 0x2e, 0x0d, 0x0a, 0x01, 0x00, 0x8a, 0x82, 0xaa, 0x27, 0x32, 0x21, 0x69, 0x9d + }; + const char *line = "D-Modem ZMODEM zstd test vector.\r\n"; + char want[103]; + snprintf(want, sizeof(want), "%s%s%s", line, line, line); + int n; + const char *why; + unsigned char *d = zc_decode(vec, 55, 1024, &n, &why); + CHECK(d && n == 102 && !memcmp(d, want, 102), "zstd: the vector: %s", why ? why : "differs"); + free(d); + CHECK(zc_frame_len(vec, 55, 1024) == 55 && zc_frame_len(vec, 54, 1024) == 0, + "zstd: the vector's length"); + unsigned char bad[55]; + memcpy(bad, vec, 55); + bad[20] ^= 1; + d = zc_decode(bad, 55, 1024, &n, &why); + CHECK(!d, "zstd: a byte wrong, taken"); + free(d); + d = zc_decode(vec, 55, 100, &n, &why); + CHECK(!d, "zstd: over the limit, taken"); + free(d); + CHECK(zc_xxh64(NULL, 0) == 0xEF46DB3751D8E999ULL && + zc_xxh64((const unsigned char *)"a", 1) == 0xD24EC4F1A98C6E5BULL && + zc_xxh64((const unsigned char *)"Nobody inspects the spammish repetition", 39) == + 0xFBCEA83C8A378BF1ULL, "zstd: XXH64"); + + int ref = have("zstd"); + size_t sizes[] = { 0, 1, 255, 256, 65535, 65791, 65792, 200000 }; + for (size_t i = 0; i < sizeof(sizes) / sizeof(sizes[0]); i++) { + for (int kind = 0; kind < 3; kind++) { + size_t sz = sizes[i]; + unsigned char *t = kind == 0 ? text(sz, (unsigned)i) : (unsigned char *)malloc(sz + 1); + for (size_t k = 0; kind > 0 && k < sz; k++) + t[k] = kind == 1 ? big[k % sizeof(big)] : (unsigned char)(k / 1000); + int fn = 0, back = 0; + unsigned char *f = zc_encode(t, (int)sz, &fn); + d = f ? zc_decode(f, fn, 256 * 1024, &back, &why) : NULL; + CHECK(d && (size_t)back == sz && !memcmp(d, t, sz), + "zstd: %zu bytes (%d) there and back: %s", sz, kind, why ? why : "differs"); + CHECK(f && zc_frame_len(f, fn, 256 * 1024) == fn, "zstd: %zu bytes: its length", sz); + if (kind == 0 && sz == 65535) + CHECK(fn * 3 < (int)sz, "zstd: 64 KB of text in %d bytes", fn); + /* the reference zstd: ours decoded, and its frame decoded */ + if (sz > 0 && ref && f) { + char a[700], b[700], cmd[1500]; + snprintf(a, sizeof(a), "%s/z.raw", tmp); + snprintf(b, sizeof(b), "%s/z.zst", tmp); + write_file(b, f, (size_t)fn); + snprintf(cmd, sizeof(cmd), "zstd -q -d -f -o '%s' '%s'", a, b); + CHECK(system(cmd) == 0, "zstd -d: our frame of %zu bytes", sz); + check_same(a, t, sz, 0, "zstd -d"); + write_file(a, t, sz); + snprintf(cmd, sizeof(cmd), "zstd -q -19 --check -f -o '%s' '%s'", b, a); + CHECK(system(cmd) == 0, "zstd -19: %zu bytes", sz); + size_t rn; + unsigned char *r = read_file(b, &rn); + unsigned char *rd = r ? zc_decode(r, (int)rn, 1 << 23, &back, &why) : NULL; + CHECK(rd && (size_t)back == sz && !memcmp(rd, t, sz), + "zstd: the reference's frame of %zu bytes: %s", sz, why ? why : "differs"); + free(r); + free(rd); + } + free(d); + free(f); + free(t); + } + } + if (ref) + printf("zstd: against the reference zstd\n"); +} + +/* one ZMODEM transfer of the files (paths) to dst with the two sides' + options: both ends' results checked */ +static void zstd_link(const char *const *paths, int n, const char *dst, + const dmc_xfer_options *so, const dmc_xfer_options *ro, + int noise, const char *what) +{ + dmc_xfer *r = dmc_xfer_receive_opt(DMC_XFER_ZMODEM, dst, NULL, ro); + dmc_xfer *s = dmc_xfer_send_opt(DMC_XFER_ZMODEM, paths, n, so); + link2(s, r, noise); + dmc_xfer_status ss, rs; + dmc_xfer_get_status(s, &ss); + dmc_xfer_get_status(r, &rs); + CHECK(!ss.result[0], "%s: the sender: %s", what, ss.result); + CHECK(!rs.result[0], "%s: the receiver: %s", what, rs.result); + if (noise) + CHECK(rs.errors + ss.errors > 0, "%s: no errors on a noisy line", what); + dmc_xfer_free(s); + dmc_xfer_free(r); +} + +/* ZMODEM with zstd: smaller on the line, whole after errors, resumed, + plain when one side doesn't take it or the file is compressed */ +static void zstd_transfers(void) +{ + char src[600], dst[600], p[5][700], got[700]; + const char *paths[5]; + size_t sizes[5] = { 0, 1, 65536, 65537, 300001 }; + unsigned char *d[5]; + long long total = 0; + dmc_xfer_options on, off; + memset(&on, 0, sizeof(on)); + memset(&off, 0, sizeof(off)); + off.no_zstd = 1; + snprintf(src, sizeof(src), "%s/src", tmp); + snprintf(dst, sizeof(dst), "%s/dst", tmp); + empty_dir(src); + empty_dir(dst); + for (int i = 0; i < 5; i++) { + d[i] = text(sizes[i], (unsigned)i + 1); + snprintf(p[i], sizeof(p[i]), "%s/f%d.txt", src, i); + write_file(p[i], d[i], sizes[i]); + paths[i] = p[i]; + total += (long long)sizes[i]; + } + zstd_link(paths, 5, dst, &on, &on, 0, "zstd"); + for (int i = 0; i < 5; i++) { + snprintf(got, sizeof(got), "%s/f%d.txt", dst, i); + check_same(got, d[i], sizes[i], 0, "zstd"); + } + CHECK(line_bytes * 2 < total, "zstd: %lld bytes on the line for %lld", line_bytes, total); + printf("ZMODEM with zstd: %lld bytes on the line for %lld\n", line_bytes, total); + + /* on a noisy line */ + empty_dir(dst); + zstd_link(paths + 4, 1, dst, &on, &on, 3001, "zstd (noisy)"); + snprintf(got, sizeof(got), "%s/f4.txt", dst); + check_same(got, d[4], sizes[4], 0, "zstd (noisy)"); + + /* zstd stopped on either side, or a compressed file: plain */ + for (int k = 0; k < 3; k++) { + char zip[700]; + const char *one[1] = { paths[4] }; + empty_dir(dst); + if (k == 2) { + snprintf(zip, sizeof(zip), "%s/f4.zip", src); + write_file(zip, d[4], sizes[4]); + one[0] = zip; + } + zstd_link(one, 1, dst, k == 0 ? &off : &on, k == 1 ? &off : &on, 0, "zstd off"); + snprintf(got, sizeof(got), "%s/f4.%s", dst, k == 2 ? "zip" : "txt"); + check_same(got, d[4], sizes[4], 0, "zstd off"); + CHECK(line_bytes >= (long long)sizes[4], + "zstd off (%d): %lld bytes on the line: compressed", k, line_bytes); + } + + /* crash recovery with zstd: from the end of the part (fewer bytes on + the line than for the whole file) */ + dmc_xfer_options res = on; + res.resume = 1; + empty_dir(dst); + zstd_link(paths + 4, 1, dst, &on, &on, 0, "zstd (whole)"); + long long whole = line_bytes; + empty_dir(dst); + snprintf(got, sizeof(got), "%s/f4.txt", dst); + write_file(got, d[4], 123457); + zstd_link(paths + 4, 1, dst, &on, &res, 0, "zstd (resume)"); + check_same(got, d[4], sizes[4], 0, "zstd (resume)"); + CHECK(line_bytes * 4 < whole * 3, + "zstd (resume): %lld bytes on the line, %lld for all: not resumed", line_bytes, whole); + for (int i = 0; i < 5; i++) + free(d[i]); +} + /* plain text with the waits of ASCII Setup */ static void text_delays(void) { @@ -719,6 +924,9 @@ int main(void) printf("skip file\n"); resume(); printf("ZMODEM crash recovery\n"); + zstd_codec(); + printf("zstd\n"); + zstd_transfers(); cancel(); detect(); interop(); diff --git a/docs/design.md b/docs/design.md index 8cf0043..e849d8a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -235,6 +235,23 @@ protocols are: ZF0 to ZCRECOV (`sz -r`). If the file is there whole, the receiver sends ZSKIP. When a transfer stops, the receiver keeps the part that it received. The sender with this option sets ZF0 to ZCRECOV. +- ZMODEM with zstd (the specification is `docs/zmodem-zstd.md` in the + D-Modem repository). The D-Modem BBS, GUI and app use this mode. The + receiver sets `CANZSTD` (0x40) in ZF1 of its ZRINIT. The sender sets + `ZTZSTD` (8) in ZF2 of the ZFILE for each file that it compresses. Then + the sender sends the file as independent zstd frames, one frame for each + chunk of 64 KB. After a ZRPOS, the chunk is half as large (minimum 1 KB). + After an ACK, the chunk is two times as large (maximum 64 KB). The + receiver writes only complete frames. All positions are file offsets, + thus ZRPOS and crash recovery operate as without zstd. The sender does + not compress a file of 0 bytes, a file with a compressed extension (for + example `.zip`, `.gz` or `.jpg`), or a file whose first 64 KB do not + become 5% smaller. When the other side does not use this mode, the + transfer is normal ZMODEM. To stop zstd, set `dmc_xfer_options.no_zstd` + (the Windows app: Transfer, ZMODEM Compression (zstd)). + `dmc_xfer_zstd` tells if the file now goes with zstd. The zstd encoder + and decoder are in `core/src/zstd_codec.c`. They are a C port of the + codec of the D-Modem app (`Zstd.kt`), and they do not use libzstd. - YMODEM, XMODEM and XMODEM-1K. - YMODEM-G: the receiver asks with G. The sender sends the blocks and does not wait for an ACK. Use it only on a line that corrects its errors (V.42). diff --git a/windows/res/app.rc b/windows/res/app.rc index 46c122f..2ab43f2 100644 --- a/windows/res/app.rc +++ b/windows/res/app.rc @@ -47,6 +47,7 @@ BEGIN MENUITEM "&Receive File...", IDM_RECEIVE MENUITEM SEPARATOR MENUITEM "&Automatic Receive (ZMODEM, Kermit)", IDM_AUTORECV + MENUITEM "ZMODEM Compression (&zstd)", IDM_XZSTD MENUITEM SEPARATOR MENUITEM "&Cancel Transfer", IDM_XCANCEL MENUITEM SEPARATOR diff --git a/windows/src/app.h b/windows/src/app.h index d092892..d6500f4 100644 --- a/windows/src/app.h +++ b/windows/src/app.h @@ -251,6 +251,10 @@ bool xfer_running(); bool xfer_busy(XferLine *l); bool xfer_auto(); void xfer_set_auto(bool on); +/* ZMODEM with zstd (where the other side has it too: D-Modem's BBS, GUI + and app) */ +bool xfer_zstd(); +void xfer_set_zstd(bool on); /* the transfer's dialog's keys (IsDialogMessage) */ bool xfer_dialog_key(MSG *m); diff --git a/windows/src/main.cpp b/windows/src/main.cpp index 1c7b957..509cc95 100644 --- a/windows/src/main.cpp +++ b/windows/src/main.cpp @@ -423,6 +423,9 @@ static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp) case IDM_AUTORECV: xfer_set_auto(!xfer_auto()); return 0; + case IDM_XZSTD: + xfer_set_zstd(!xfer_zstd()); + return 0; case IDM_XCANCEL: xfer_cancel(); return 0; @@ -481,6 +484,8 @@ static LRESULT CALLBACK main_proc(HWND w, UINT m, WPARAM wp, LPARAM lp) } CheckMenuItem(m, IDM_AUTORECV, MF_BYCOMMAND | (xfer_auto() ? MF_CHECKED : MF_UNCHECKED)); + CheckMenuItem(m, IDM_XZSTD, MF_BYCOMMAND | + (xfer_zstd() ? MF_CHECKED : MF_UNCHECKED)); HWND v = view_now(); UINT has_view = v ? MF_ENABLED : MF_GRAYED; EnableMenuItem(m, IDM_EDCOPY, MF_BYCOMMAND | diff --git a/windows/src/resource.h b/windows/src/resource.h index 4d62cc3..80aaf38 100644 --- a/windows/src/resource.h +++ b/windows/src/resource.h @@ -33,6 +33,7 @@ #define IDM_CALL 220 #define IDM_WAITCALL 221 #define IDM_DISCONNECT 222 +#define IDM_XZSTD 223 #define IDC_STATUS 300 #define IDC_TABS 301 diff --git a/windows/src/xfer.cpp b/windows/src/xfer.cpp index 284ce5d..40aa58c 100644 --- a/windows/src/xfer.cpp +++ b/windows/src/xfer.cpp @@ -141,6 +141,16 @@ void xfer_set_auto(bool on) ini_set_int("auto", on ? 1 : 0); } +bool xfer_zstd() +{ + return ini_int("zmodem_zstd", 1) != 0; +} + +void xfer_set_zstd(bool on) +{ + ini_set_int("zmodem_zstd", on ? 1 : 0); +} + bool xfer_running() { return cur != NULL; @@ -190,6 +200,12 @@ static void show_status(const dmc_xfer_status *st, bool force) char a[300], b[64], c[64]; to_ansi(st->file[0] ? st->file : "(waiting for the other side)", a, sizeof(a)); + /* (a file that goes compressed: ZMODEM with zstd) */ + if (st->running && cur && dmc_xfer_zstd(cur)) { + size_t al = strlen(a); + _snprintf(a + al, sizeof(a) - al, " (zstd)"); + a[sizeof(a) - 1] = '\0'; + } set_text(IDC_X_FILE, a); if (st->files > last_files) { done_bytes += st->size > 0 ? st->size : st->bytes; @@ -443,6 +459,7 @@ static bool start_receive(XferLine *l, int protocol, const char *name, bool resu dmc_xfer_options o; memset(&o, 0, sizeof(o)); o.resume = resume && protocol == DMC_XFER_ZMODEM; + o.no_zstd = !xfer_zstd(); return start(l, dmc_xfer_receive_opt(protocol, where, name, &o), protocol, false, 0, o.resume != 0); } @@ -791,6 +808,7 @@ void xfer_send_dialog(XferLine *l, int protocol) dmc_xfer_options o; memset(&o, 0, sizeof(o)); o.resume = a.resume; + o.no_zstd = !xfer_zstd(); AsciiSetup as; ascii_load(&as); o.line_delay_ms = as.line_delay;