54#define fseeko _fseeki64
55#define ftello _ftelli64
62#define ZXC_STREAM_PREAD_MIN_BLOCK ((size_t)64 * 1024)
65#define ZXC_STREAM_RING_BATCHED 2U
67#define ZXC_STREAM_RING_UNBATCHED 4U
135 uint64_t block_index;
235 zxc_stream_job_t* jobs;
241 pthread_mutex_t lock;
242 pthread_cond_t cond_reader;
243 pthread_cond_t cond_worker;
244 pthread_cond_t cond_writer;
245 int shutdown_workers;
246 int compression_mode;
251 int compression_level;
253 int checksum_enabled;
254 int file_has_checksum;
258 void* progress_user_data;
259 uint64_t total_input_bytes;
262 const uint8_t* dict_huf;
276 return (
int)(((size_t)idx + 1) % ctx->ring_size);
310 zxc_stream_ctx_t* ctx;
314 uint64_t bytes_processed;
325 zxc_stream_ctx_t ctx;
332} zxc_stream_engine_t;
341static int64_t
zxc_pread_full(
const int fd,
void* dst,
const size_t len,
const uint64_t offset) {
342 if (
sizeof(off_t) <
sizeof(uint64_t) && (offset > INT32_MAX || len > INT32_MAX - offset))
346 const ssize_t r = pread(fd, (uint8_t*)dst + done, len - done, (off_t)(offset + done));
351 else if (errno != EINTR)
354 return (int64_t)done;
362 const int fd = _fileno(f);
363 if (fd < 0)
return -1;
364 const intptr_t handle = _get_osfhandle(fd);
365 return (handle != -1 && GetFileType((HANDLE)handle) == FILE_TYPE_DISK) ? fd : -1;
369 const int fd = fileno(f);
370 return (fd >= 0 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) ? fd : -1;
381 if (
sizeof(off_t) <
sizeof(uint64_t))
return;
382 const long long pos = ftello(f_in);
383 if (UNLIKELY(pos < 0))
return;
385 ctx->in_pos = (uint64_t)pos;
396 const uint64_t offset) {
420 if (ctx && ctx->in_fd >= 0) {
422 if (LIKELY(r > 0)) ctx->in_pos += (uint64_t)r;
425 const size_t got = fread(dst, 1, len, f);
428 if (UNLIKELY(got < len && !feof(f)))
return ZXC_ERROR_IO;
434 pthread_mutex_lock(&ctx->lock);
435 if (code && !ctx->fail_code) ctx->fail_code = code;
437 pthread_mutex_unlock(&ctx->lock);
447 const uint8_t* in,
const size_t in_sz, uint8_t* out,
448 const size_t out_cap,
const uint64_t block_index) {
449 return ctx->compression_mode
463 const zxc_stream_job_t* job,
const uint8_t* in,
464 uint8_t* dict_work) {
469 uint8_t*
const scratch = dict_work ? dict_work + ctx->dict_size : NULL;
470 uint64_t block_index = job->block_index;
474 while (ip < job->in_sz) {
475 const size_t rem = job->in_sz - ip;
485 scratch ? scratch : job->out_buf + op, room, block_index++);
486 if (UNLIKELY(res < 0))
return res;
487 if (scratch) ZXC_MEMCPY(job->out_buf + op, scratch, (
size_t)res);
488 ip += (size_t)block_sz;
510 zxc_stream_ctx_t*
const ctx = (zxc_stream_ctx_t*)arg;
513 const int unified_chk = (ctx->compression_mode == 1)
514 ? ctx->checksum_enabled
515 : (ctx->file_has_checksum && ctx->checksum_enabled);
517 const size_t eff_chunk = (ctx->dict_size > 0 && ctx->compression_mode == 1)
521 uint8_t*
const in_work = ctx->in_fd >= 0 ? (uint8_t*)
ZXC_MALLOC(ctx->in_alloc) : NULL;
522 if (UNLIKELY(
zxc_cctx_init(&cctx, eff_chunk, ctx->compression_mode, ctx->compression_level,
523 unified_chk, ctx->dict_size) !=
ZXC_OK ||
525 (ctx->in_fd >= 0 && !in_work))) {
529 pthread_mutex_lock(&ctx->lock);
531 ctx->workers_lost = 1;
532 pthread_cond_broadcast(&ctx->cond_writer);
533 pthread_cond_broadcast(&ctx->cond_reader);
534 pthread_mutex_unlock(&ctx->lock);
542 const size_t dsz = ctx->dict_size;
544 if (dict_work) ZXC_MEMCPY(dict_work, ctx->dict, dsz);
547 zxc_stream_job_t* job = NULL;
548 pthread_mutex_lock(&ctx->lock);
549 while (ctx->wq_count == 0 && !ctx->shutdown_workers) {
550 pthread_cond_wait(&ctx->cond_worker, &ctx->lock);
552 if (ctx->shutdown_workers && ctx->wq_count == 0) {
553 pthread_mutex_unlock(&ctx->lock);
556 const int jid = ctx->worker_queue[ctx->wq_tail];
559 job = &ctx->jobs[jid];
560 pthread_mutex_unlock(&ctx->lock);
563 const uint8_t*
const in = in_work ? in_work : job->in_buf;
566 (int64_t)job->in_sz)) {
568 }
else if (ctx->compression_mode == 0) {
570 }
else if (dict_work) {
571 ZXC_MEMCPY(dict_work + dsz, in, job->in_sz);
573 job->out_cap, job->block_index);
579 pthread_mutex_lock(&ctx->lock);
580 job->result_sz = UNLIKELY(res < 0) ? 0 : (size_t)res;
581 job->fail_code = UNLIKELY(res < 0) ? res : 0;
583 if (UNLIKELY(res < 0)) {
585 if (!ctx->fail_code) ctx->fail_code = res;
587 pthread_cond_broadcast(&ctx->cond_writer);
588 pthread_cond_broadcast(&ctx->cond_reader);
589 }
else if (jid == ctx->write_idx) {
590 pthread_cond_signal(&ctx->cond_writer);
592 pthread_mutex_unlock(&ctx->lock);
629 writer_args_t*
const args = (writer_args_t*)arg;
630 zxc_stream_ctx_t*
const ctx = args->ctx;
632 zxc_stream_job_t*
const job = &ctx->jobs[ctx->write_idx];
633 pthread_mutex_lock(&ctx->lock);
636 pthread_cond_wait(&ctx->cond_writer, &ctx->lock);
638 pthread_mutex_unlock(&ctx->lock);
641 if (UNLIKELY(job->fail_code)) {
643 ctx->fail_code = job->fail_code;
645 pthread_cond_signal(&ctx->cond_reader);
646 pthread_mutex_unlock(&ctx->lock);
650 const size_t result_sz = job->result_sz;
651 const size_t in_sz = job->in_sz;
652 pthread_mutex_unlock(&ctx->lock);
654 if (result_sz == (
size_t)-1)
break;
656 if (args->f && result_sz > 0) {
657 if (fwrite(job->out_buf, 1, result_sz, args->f) != result_sz) {
658 pthread_mutex_lock(&ctx->lock);
662 pthread_cond_signal(&ctx->cond_reader);
663 pthread_mutex_unlock(&ctx->lock);
667 args->total_bytes += (int64_t)result_sz;
668 if (ctx->checksum_enabled && ctx->compression_mode == 1 &&
674 if (args->seek_comp && ctx->compression_mode == 1) {
675 if (UNLIKELY(args->seek_count >= args->seek_cap)) {
676 const uint64_t max_cap = SIZE_MAX /
sizeof(uint32_t);
678 if (LIKELY(args->seek_cap < max_cap)) {
679 args->seek_cap = args->seek_cap < max_cap / 2 ? args->seek_cap * 2 : max_cap;
681 (
size_t)args->seek_cap *
sizeof(uint32_t));
685 pthread_mutex_lock(&ctx->lock);
689 pthread_cond_signal(&ctx->cond_reader);
690 pthread_mutex_unlock(&ctx->lock);
694 args->seek_comp = nc;
696 args->seek_comp[args->seek_count++] = (uint32_t)result_sz;
699 if (ctx->progress_cb) {
701 args->bytes_processed += ctx->compression_mode == 1 ? in_sz : result_sz;
702 ctx->progress_cb(args->bytes_processed, ctx->total_input_bytes,
703 ctx->progress_user_data);
707 pthread_mutex_lock(&ctx->lock);
710 pthread_cond_signal(&ctx->cond_reader);
711 pthread_mutex_unlock(&ctx->lock);
724 zxc_stream_ctx_t*
const ctx = &e->ctx;
725 if (writer_started) {
726 zxc_stream_job_t*
const end_job = &ctx->jobs[e->read_idx];
727 pthread_mutex_lock(&ctx->lock);
729 pthread_cond_wait(&ctx->cond_reader, &ctx->lock);
731 end_job->result_sz = (size_t)-1;
732 end_job->fail_code = 0;
735 pthread_cond_broadcast(&ctx->cond_writer);
736 pthread_mutex_unlock(&ctx->lock);
737 pthread_join(e->writer, NULL);
739 pthread_mutex_lock(&ctx->lock);
740 ctx->shutdown_workers = 1;
741 pthread_cond_broadcast(&ctx->cond_worker);
742 pthread_mutex_unlock(&ctx->lock);
743 for (
int i = 0; i < e->n_workers; i++) pthread_join(e->workers[i], NULL);
745 pthread_cond_destroy(&ctx->cond_writer);
746 pthread_cond_destroy(&ctx->cond_worker);
747 pthread_cond_destroy(&ctx->cond_reader);
748 pthread_mutex_destroy(&ctx->lock);
785 zxc_stream_ctx_t*
const ctx = &e->ctx;
786 const int mode = ctx->compression_mode;
787 const size_t chunk = ctx->chunk_size;
789 const int explicit_threads = n_threads > 0;
790 int num_threads = explicit_threads ? n_threads :
zxc_num_procs();
796 if (in_fd >= 0 && num_threads > 1 && chunk >= ZXC_STREAM_PREAD_MIN_BLOCK)
800 const int num_workers = (explicit_threads || ctx->in_fd >= 0) ? num_threads
801 : (num_threads > 1) ? num_threads - 1
804 ctx->ring_size = (size_t)num_workers *
805 (ctx->batch > 1 ? ZXC_STREAM_RING_BATCHED : ZXC_STREAM_RING_UNBATCHED);
808 const size_t raw_alloc_in =
809 (size_t)((mode ? chunk : max_out * (uint64_t)ctx->batch) +
ZXC_PAD_SIZE);
811 ctx->in_alloc = alloc_in;
813 const size_t raw_alloc_out =
819 const size_t ring_in = ctx->in_fd >= 0 ? 0 : alloc_in;
820 const size_t per_job_sz =
sizeof(zxc_stream_job_t) +
sizeof(
int) + ring_in + alloc_out;
821 if (UNLIKELY(per_job_sz > SIZE_MAX / ctx->ring_size))
826 e->mem_block = mem_block;
828 uint8_t* ptr = mem_block;
829 ctx->jobs = (zxc_stream_job_t*)ptr;
830 ptr += ctx->ring_size *
sizeof(zxc_stream_job_t);
831 ctx->worker_queue = (
int*)ptr;
832 ptr += ctx->ring_size *
sizeof(int);
833 uint8_t* buf_in = ptr;
834 ptr += ctx->ring_size * ring_in;
835 uint8_t* buf_out = ptr;
837 ZXC_MEMSET(mem_block, 0, ctx->ring_size * (
sizeof(zxc_stream_job_t) +
sizeof(
int)));
839 for (
size_t i = 0; i < ctx->ring_size; i++) {
840 ctx->jobs[i].job_id = (int)i;
842 ctx->jobs[i].in_buf = ring_in ? buf_in + (i * ring_in) : NULL;
844 ctx->jobs[i].in_sz = 0;
845 ctx->jobs[i].out_buf = buf_out + (i * alloc_out);
847 ctx->jobs[i].result_sz = 0;
850 pthread_mutex_init(&ctx->lock, NULL);
851 pthread_cond_init(&ctx->cond_reader, NULL);
852 pthread_cond_init(&ctx->cond_worker, NULL);
853 pthread_cond_init(&ctx->cond_writer, NULL);
855 e->workers =
ZXC_MALLOC((
size_t)num_workers *
sizeof(pthread_t));
856 if (LIKELY(e->workers)) {
857 while (e->n_workers < num_workers &&
862 if (UNLIKELY(e->n_workers == 0 ||
873 if (e->ctx.in_fd < 0)
return ZXC_OK;
880 zxc_stream_ctx_t*
const ctx = &e->ctx;
882 const zxc_stream_job_t*
const last =
883 &ctx->jobs[((size_t)e->read_idx + ctx->ring_size - 1) % ctx->ring_size];
884 pthread_mutex_lock(&ctx->lock);
886 pthread_cond_wait(&ctx->cond_reader, &ctx->lock);
887 const int failed = ctx->io_error;
888 pthread_mutex_unlock(&ctx->lock);
900 int* n_blocks,
int* eof) {
901 const int positioned = ctx->in_fd >= 0;
905 const int fold = ctx->file_has_checksum && ctx->checksum_enabled;
909 for (*n_blocks = 0; *n_blocks < ctx->batch; (*n_blocks)++) {
911 const uint64_t block_off = ctx->in_pos;
913 if (positioned && ctx->ahead_len >= 0) {
914 h_read = ctx->ahead_len;
915 ZXC_MEMCPY(bh_buf, ctx->ahead, (
size_t)h_read);
917 }
else if (positioned) {
922 if (UNLIKELY(h_read < 0))
goto _failed;
923 if (positioned) ctx->in_pos += (uint64_t)h_read;
949 if (UNLIKELY((uint64_t)bh.
comp_size > (uint64_t)ctx->chunk_size)) {
954 const size_t body_total = (size_t)bh.
comp_size + checksum_sz;
956 if (UNLIKELY(total_len > (uint64_t)(job->in_cap - fill)))
goto _failed;
959 const uint8_t* stored = tail;
965 if (fill == 0) job->in_off = block_off;
966 ctx->in_pos += body_total;
977 uint8_t*
const block = job->in_buf + fill;
985 if (UNLIKELY(!got))
goto _failed;
987 fill += (size_t)total_len;
988 ctx->frame_in += total_len;
1001 const size_t got = fread(job->in_buf, 1, ctx->chunk_size, f_in);
1002 ctx->src_total += got;
1003 if (got < ctx->chunk_size) {
1005 if (UNLIKELY(!feof(f_in))) {
1020 uint64_t block_index = 0;
1023 zxc_stream_job_t*
const job = &ctx->jobs[read_idx];
1024 pthread_mutex_lock(&ctx->lock);
1026 pthread_cond_wait(&ctx->cond_reader, &ctx->lock);
1027 const int failed = ctx->io_error;
1028 pthread_mutex_unlock(&ctx->lock);
1030 if (UNLIKELY(failed))
break;
1033 const size_t read_sz = ctx->compression_mode
1036 if (UNLIKELY(read_eof && read_sz == 0))
break;
1038 job->in_sz = read_sz;
1039 job->block_index = block_index;
1040 block_index += (uint64_t)n_blocks;
1041 pthread_mutex_lock(&ctx->lock);
1043 ctx->worker_queue[ctx->wq_head] = read_idx;
1047 pthread_cond_signal(&ctx->cond_worker);
1048 pthread_mutex_unlock(&ctx->lock);
1062 .block_type = ZXC_BLOCK_EOF, .block_flags = 0, .reserved = 0, .comp_size = 0};
1064 if (UNLIKELY(f_out &&
1071 if (!ctx->io_error && w->seek_comp) {
1075 if (UNLIKELY(h < 0 || (f_out && fwrite(st_buf, 1, (
size_t)h, f_out) != (
size_t)h)))
1078 w->total_bytes += h;
1081 for (uint64_t i = 0; i < w->seek_count && !ctx->io_error; i +=
ZXC_SEEK_GROUP) {
1082 const size_t bytes =
1085 if (UNLIKELY(f_out && fwrite(st_buf, 1, bytes, f_out) != bytes))
1088 w->total_bytes += (int64_t)bytes;
1094 const size_t footer_len =
1096 ctx->src_total, w->digest, ctx->checksum_enabled);
1097 if (UNLIKELY(f_out && fwrite(footer_buf, 1, footer_len, f_out) != footer_len))
1100 w->total_bytes += (int64_t)footer_len;
1113 if (ctx->file_has_seek) {
1115 uint64_t remaining = 0;
1116 uint64_t sek_bytes = 0;
1121 ctx->chunk_size, &remaining);
1122 if (UNLIKELY(src_rc !=
ZXC_OK)) {
1126 sek_bytes = remaining;
1128 if (ctx->in_fd >= 0) {
1129 ctx->in_pos += remaining;
1132 uint8_t discard[512];
1133 while (remaining > 0 && !failed) {
1134 const size_t chunk = remaining <
sizeof(discard) ? (
size_t)remaining :
sizeof(discard);
1135 if (UNLIKELY(fread(discard, 1, chunk, f_in) != chunk)) failed = 1;
1142 uint64_t stored_digest = 0;
1149 if (UNLIKELY(frc !=
ZXC_OK)) {
1154 if (!failed && ctx->file_has_checksum && ctx->checksum_enabled &&
1155 UNLIKELY(stored_digest != ctx->digest)) {
1176 const int short_code) {
1178 if (LIKELY(got == (int64_t)len))
return ZXC_OK;
1180 return got == 0 ? 1 : short_code;
1198 const int has_dict,
const uint32_t dict_id,
size_t* chunk,
1199 int* has_checksum,
int* has_seek,
int* frame_dict) {
1201 int header_has_dict = 0;
1202 uint32_t header_dict_id = 0;
1203 ZXC_MEMCPY(h, magic,
sizeof(uint32_t));
1210 &header_has_dict, &header_dict_id, has_seek);
1211 if (UNLIKELY(hrc !=
ZXC_OK))
return hrc;
1212 *frame_dict = header_has_dict;
1213 if (header_has_dict) {
1229 zxc_stream_ctx_t*
const ctx = &e->ctx;
1230 const int64_t base = e->w.total_bytes;
1231 ctx->file_has_seek = has_seek;
1234 ctx->ahead_len = -1;
1241 pthread_mutex_lock(&ctx->lock);
1242 const int failed = ctx->io_error;
1243 const int code = ctx->fail_code;
1244 pthread_mutex_unlock(&ctx->lock);
1245 if (UNLIKELY(failed))
return code ? code :
ZXC_ERROR_IO;
1246 return e->w.total_bytes - base;
1252 if (UNLIKELY(*saved < 0 || fseeko(f, 0, SEEK_END) != 0))
return ZXC_ERROR_IO;
1253 const long long n = ftello(f);
1254 if (UNLIKELY(n < 0)) {
1256 fseeko(f, *saved, SEEK_SET);
1260 *size = (uint64_t)n;
1275 const int n_threads = opts ? opts->n_threads : 0;
1276 const int checksum_enabled = opts ? opts->checksum_enabled : 0;
1277 const int seekable = opts ? opts->seekable : 0;
1280 const uint8_t* dict = opts ? (
const uint8_t*)opts->dict : NULL;
1283 void* ud = opts ? opts->user_data : NULL;
1286 zxc_stream_engine_t e;
1287 ZXC_MEMSET(&e, 0,
sizeof(e));
1288 zxc_stream_ctx_t*
const ctx = &e.ctx;
1289 ctx->compression_mode = 1;
1290 ctx->compression_level = level;
1291 ctx->chunk_size = block_size;
1292 ctx->checksum_enabled = checksum_enabled;
1293 ctx->file_has_checksum = checksum_enabled;
1294 ctx->progress_cb = cb;
1295 ctx->progress_user_data = ud;
1297 ctx->dict_size = dict_size;
1298 ctx->dict_huf = dict_huf;
1301 long long saved_pos = 0;
1302 uint64_t in_size = 0;
1304 ctx->total_input_bytes = in_size;
1305 fseeko(f_in, saved_pos, SEEK_SET);
1311 e.w.seek_comp = (uint32_t*)
ZXC_MALLOC(e.w.seek_cap *
sizeof(uint32_t));
1316 if (UNLIKELY(src !=
ZXC_OK)) {
1339 if (UNLIKELY(!ctx->io_error && f_out && fflush(f_out) != 0)) ctx->io_error = 1;
1342 if (UNLIKELY(ctx->io_error))
return ctx->fail_code ? ctx->fail_code :
ZXC_ERROR_IO;
1343 return e.w.total_bytes;
1356 const zxc_dparams_t*
const opts = cfg ? zxc_dctx_params(cfg) : NULL;
1358 const int n_threads = opts ? opts->n_threads : 0;
1359 const int checksum_enabled = opts ? opts->checksum_enabled : 0;
1360 const uint8_t* dict = opts ? (
const uint8_t*)opts->dict : NULL;
1365 zxc_stream_engine_t e;
1367 uint8_t magic[
sizeof(uint32_t)];
1371 for (
int frames = 0;; frames++) {
1377 if (UNLIKELY(rc !=
ZXC_OK))
break;
1383 int has_checksum = 0;
1387 dict_id, &chunk, &has_checksum, &has_seek, &frame_dict);
1388 if (UNLIKELY(rc !=
ZXC_OK))
break;
1390 const size_t frame_dict_size = frame_dict ? dict_size : 0;
1393 if (running && (e.ctx.chunk_size != chunk || e.ctx.file_has_checksum != has_checksum ||
1394 e.ctx.dict_size != frame_dict_size)) {
1397 if (UNLIKELY(rc !=
ZXC_OK))
break;
1400 ZXC_MEMSET(&e, 0,
sizeof(e));
1401 e.ctx.chunk_size = chunk;
1402 e.ctx.checksum_enabled = checksum_enabled;
1403 e.ctx.file_has_checksum = has_checksum;
1404 e.ctx.progress_cb = opts ? opts->progress_cb : NULL;
1405 e.ctx.progress_user_data = opts ? opts->user_data : NULL;
1406 e.ctx.dict = frame_dict ? dict : NULL;
1407 e.ctx.dict_size = frame_dict_size;
1408 e.ctx.dict_huf = frame_dict ? dict_huf : NULL;
1410 e.w.bytes_processed = (uint64_t)total;
1412 if (UNLIKELY(rc !=
ZXC_OK))
break;
1417 if (UNLIKELY(r < 0)) {
1426 if (rc ==
ZXC_OK) rc = crc;
1428 else if (e.ctx.fail_code)
1429 rc = e.ctx.fail_code;
1433 return rc !=
ZXC_OK ? rc : total;
1439 FILE*
const f = (FILE*)src->ctx;
1440 if (UNLIKELY(fseeko(f, (
long long)off, SEEK_SET) != 0 || fread(dst, 1, len, f) != len))
1450 long long saved = 0;
1453 if (UNLIKELY(rc !=
ZXC_OK))
return rc;
1456 fseeko(f_in, saved, SEEK_SET);
1468 long long saved = 0;
1471 if (UNLIKELY(rc !=
ZXC_OK))
return rc;
1475 fseeko(f_in, saved, SEEK_SET);
1476 if (UNLIKELY(rc !=
ZXC_OK))
return rc;
1478 return (int64_t)info.
dsize;
1502 const size_t info_size) {
1504 long long saved = 0;
1507 if (UNLIKELY(rc !=
ZXC_OK))
return rc;
1509 if (UNLIKELY(end > size)) {
1516 fseeko(f_in, saved, SEEK_SET);
1548static int64_t
zxc_stdio_read_at(
void* vctx,
void* dst,
size_t len, uint64_t offset) {
1549 zxc_stdio_ctx_t*
const ctx = (zxc_stdio_ctx_t*)vctx;
1551 ZXC_MEMSET(&ov, 0,
sizeof(ov));
1552 ov.Offset = (DWORD)(offset & 0xFFFFFFFFU);
1553 ov.OffsetHigh = (DWORD)(offset >> 32);
1554 DWORD bytes_read = 0;
1555 if (!ReadFile(ctx->handle, dst, (DWORD)len, &bytes_read, &ov))
return ZXC_ERROR_IO;
1556 return (bytes_read == (DWORD)len) ? (int64_t)len :
ZXC_ERROR_IO;
1581 const zxc_stdio_ctx_t*
const ctx = (
const zxc_stdio_ctx_t*)vctx;
1597 if (UNLIKELY(!f))
return NULL;
1600 const long long saved_pos = ftello(f);
1601 if (UNLIKELY(saved_pos < 0))
return NULL;
1604 if (UNLIKELY(fseeko(f, 0, SEEK_END) != 0))
return NULL;
1605 const long long file_size = ftello(f);
1606 (void)fseeko(f, saved_pos, SEEK_SET);
1607 if (UNLIKELY(file_size <= 0))
return NULL;
1610 zxc_stdio_ctx_t*
const ctx = (zxc_stdio_ctx_t*)
ZXC_MALLOC(
sizeof(*ctx));
1611 if (UNLIKELY(!ctx))
return NULL;
1614 ctx->handle = (HANDLE)(intptr_t)_get_osfhandle(_fileno(f));
1616 ctx->fd = fileno(f);
1618 ctx->size = (uint64_t)file_size;
struct zxc_cctx_s zxc_cctx
Opaque reusable compression context (see zxc_create_cctx).
struct zxc_dctx_s zxc_dctx
Opaque reusable decompression context (see zxc_create_dctx).
#define ZXC_BLOCK_SIZE_DEFAULT
Default block size (512 KB).
size_t zxc_compress_bound(const size_t input_size)
Maximum compressed size for an input of input_size bytes.
uint32_t zxc_dict_compute_id(const void *dict, size_t dict_size, const void *huf_lengths)
Computes the dictionary ID from content, and optionally its table.
@ ZXC_ERROR_BAD_MAGIC
Invalid magic word in file header.
@ ZXC_ERROR_CORRUPT_DATA
Corrupted compressed data.
@ ZXC_ERROR_NULL_INPUT
Required input pointer is NULL.
@ ZXC_ERROR_IO
Read/write/seek failure on file.
@ ZXC_ERROR_DICT_MISMATCH
Provided dictionary ID does not match the file header.
@ ZXC_ERROR_MEMORY
Memory allocation failure.
@ ZXC_ERROR_BAD_HEADER
Corrupted or invalid header (checksum mismatch).
@ ZXC_ERROR_SRC_TOO_SMALL
Source buffer too small or truncated input.
@ ZXC_ERROR_DICT_REQUIRED
File requires a dictionary but none was provided.
@ ZXC_ERROR_DICT_UNSUPPORTED
Dictionary not supported by this context's workspace, or library built without dictionary support.
@ ZXC_ERROR_BAD_CHECKSUM
A block's decoded bytes fail its checksum, or the archive digest mismatches.
@ ZXC_OK
Success (no error).
@ ZXC_ERROR_BAD_BLOCK_SIZE
Invalid block size.
#define ZXC_MALLOC(size)
Heap allocator.
static uint32_t zxc_seek_group_len(const uint64_t nblocks, const uint64_t g)
Blocks in group g of nblocks: ZXC_SEEK_GROUP, fewer for the last.
#define ZXC_SEEK_GROUP
Blocks per group.
#define ZXC_ALWAYS_INLINE
Forces a function to be inlined (fallback for non-GCC/Clang/MSVC compilers).
#define ZXC_ALIGNED_FREE(ptr)
Counterpart deallocator for ZXC_ALIGNED_MALLOC.
#define ZXC_ALIGNMENT_MASK
Bitmask for cache-line alignment checks.
#define ZXC_ALIGNED_MALLOC(size, alignment)
Cache-line-aligned allocator.
#define ZXC_SEEK_GROUP_BYTES
Full group: anchor + ZXC_SEEK_GROUP sizes.
#define ZXC_FREE(ptr)
Heap deallocator.
#define ZXC_PAD_SIZE
Safety padding appended to buffers to tolerate overruns.
#define ZXC_BLOCK_HEADER_SIZE
Block header size: Type(1)+Flags(1)+Reserved(1)+Checksum(1)+CompSize(4).
#define ZXC_REALLOC(ptr, size)
In-place / move heap reallocator.
#define ZXC_MT_BATCH_BYTES
Output per multi-threaded decode job: smaller blocks travel several to a job, paying the thread hando...
#define ZXC_BLOCK_CHECKSUM_SIZE
Size of the per-block checksum field in bytes.
#define ZXC_CACHE_LINE_SIZE
Assumed CPU cache line size for alignment.
#define ZXC_DECOMPRESS_TAIL_PAD
Tail padding required on the decompression destination buffer.
@ ZXC_LEVEL_DEFAULT
Recommended default: better ratio and decode speed than LZ4.
zxc_seekable * zxc_seekable_open_reader(const zxc_reader_t *r)
Opens a seekable archive through a user-supplied reader.
struct zxc_seekable_s zxc_seekable
Opaque handle for a seekable ZXC archive.
int64_t zxc_stream_decompress(FILE *f_in, FILE *f_out, const zxc_dctx *cfg)
Decompresses a FILE* stream to another FILE* stream.
zxc_seekable * zxc_seekable_open_file(FILE *f)
Opens a seekable archive backed by an open FILE*.
int64_t zxc_stream_compress(FILE *f_in, FILE *f_out, const zxc_cctx *cfg)
Compresses a FILE* stream to another FILE* stream.
int64_t zxc_stream_get_decompressed_size(FILE *f_in)
Reads the total decompressed size from the footers of a file.
int zxc_stream_get_frame_info(FILE *f_in, zxc_frame_info_t *info, const size_t info_size)
Reads a file's frame header and footer, without decoding.
int zxc_stream_get_last_frame_info(FILE *f_in, const uint64_t end, zxc_frame_info_t *info, const size_t info_size)
Reads the frame that ends at offset end of a file, without decoding.
#define ZXC_MAX_THREADS
Thread cap, a guard against memory exhaustion: each worker of the FILE* pipeline holds up to four job...
Compression / decompression context.
int compression_level
Compression level.
uint8_t * dict_buffer
[dict | data] concat scratch carved from memory_block when dict_size > 0 (NULL otherwise).
What zxc_scan_container learns about a container.
uint64_t dsize
Sum of the stored decompressed sizes.
Compression parameters of a zxc_cctx, the private form of what zxc_cctx_set_param() / zxc_cctx_set_di...
Decompression parameters of a zxc_dctx; see zxc_cparams_t.
What a frame's header and footer declare, read without decoding.
Storage-agnostic reader interface for seekable archives.
Where a container scan reads from: memory, or a positioned callback (the FILE* size query).
One-shot buffer compression and decompression.
int zxc_read_block_header(const uint8_t *src, const size_t src_size, zxc_block_header_t *bh)
Parses and validates a block header from src.
void zxc_cctx_free(zxc_cctx_t *ctx)
Releases all resources owned by a compression context.
int zxc_write_block_header(uint8_t *dst, const size_t dst_capacity, const zxc_block_header_t *bh)
Serialises a block header (8 bytes) into dst.
int zxc_scan_container(const zxc_scan_src_t *src, const size_t req_chunk, zxc_container_info_t *info)
Measures a whole container without decoding: frames from the last back to the first through zxc_scan_...
int zxc_seek_table_header(uint8_t *dst, const size_t dst_capacity, const uint64_t num_blocks)
Writes a seek table's block header for num_blocks entries.
int zxc_scan_frame(const zxc_scan_src_t *src, const uint64_t end, uint64_t *start, zxc_frame_info_t *info, size_t *footer_len, int *has_dict)
Measures the frame ending at end without decoding: its footer's compressed size gives where it starts...
int zxc_scan_whole_frame(const zxc_scan_src_t *src, zxc_frame_info_t *info, size_t *footer_len)
The frame that must span all of src: zxc_get_frame_info() and its FILE* twin.
size_t zxc_seek_write_group(uint8_t *dst, uint64_t *anchor, const uint32_t *sizes, const uint32_t cnt)
Writes one group (*anchor, then cnt sizes) into dst, which holds ZXC_SEEK_GROUP_BYTES,...
int zxc_check_eof_header(const uint8_t *hdr)
Checks an EOF block header against its one valid form: type 255, every other field zero,...
int zxc_cctx_init(zxc_cctx_t *ctx, const size_t chunk_size, const int mode, const int level, const int checksum_enabled, const size_t dict_size)
Initialises a compression / decompression context, allocating the persistent buffer with ZXC_ALIGNED_...
int zxc_read_file_header(const uint8_t *src, const size_t src_size, size_t *out_block_size, int *out_has_checksum, int *out_has_dict, uint32_t *out_dict_id, int *out_has_seek)
Parses and validates a ZXC file header from src.
int zxc_write_file_footer(uint8_t *dst, const size_t dst_capacity, const uint64_t prefix, const uint64_t src_size, const uint64_t digest, const int checksum_enabled)
Writes the file footer: the archive digest when checksum_enabled, then the two sizes and their length...
int zxc_write_file_header(uint8_t *dst, const size_t dst_capacity, const size_t chunk_size, const int has_checksum, const int has_dict, const uint32_t dict_id, const int has_seek)
Serialises a ZXC file header into dst.
int zxc_cctx_attach_dict_huf(zxc_cctx_t *ctx, const uint8_t *lengths)
Attach the shared dictionary literal Huffman table to a context.
int zxc_check_file_footer(const uint8_t *footer, const size_t avail, const zxc_footer_layout_t *l, const uint64_t src_size, uint64_t *digest)
Checks a footer against the one the frame implies.
int zxc_check_seek_header(const uint8_t *hdr, const size_t avail, const uint64_t total_out, const size_t block_size, uint64_t *sek_bytes)
Checks the SEK block header the file header announced, on the avail bytes present.
int zxc_compress_chunk_wrapper(zxc_cctx_t *ctx, const uint8_t *chunk, const size_t src_sz, uint8_t *dst, const size_t dst_cap, const uint64_t block_index)
Compresses one chunk into a single ZXC block (the compression hot path).
int zxc_decompress_chunk_wrapper(const zxc_cctx_t *ctx, const uint8_t *src, const size_t src_sz, uint8_t *dst, const size_t dst_cap, const uint64_t block_index)
Public no-dict chunk decoder (decompression hot path).
Pre-trained dictionary API for ZXC compression.
const zxc_cparams_t * zxc_cctx_params(const zxc_cctx *cctx)
Parameters a public context carries, for the FILE* and push paths.
static int zxc_stream_engine_drain(zxc_stream_engine_t *e)
Waits until the writer has written every job queued so far; returns io_error.
static int zxc_stream_regular_fd(FILE *f)
Descriptor of a regular-file stream, -1 for anything else (may be live).
static void zxc_stream_engine_stop(zxc_stream_engine_t *e, const int writer_started)
Stops the threads, then frees the ring and its synchronisation objects.
static void zxc_stream_finish_decompress(zxc_stream_ctx_t *ctx, const uint64_t frame_out, FILE *f_in)
Consumes and validates the trailer of a decompressed stream.
static size_t zxc_stream_read_blocks(zxc_stream_ctx_t *ctx, FILE *f_in, zxc_stream_job_t *job, int *n_blocks, int *eof)
Fills a decompression job with up to ctx->batch consecutive blocks.
static int64_t zxc_stdio_read_at(void *vctx, void *dst, size_t len, uint64_t offset)
Thread-safe positioned read backing the seekable FILE* reader.
static void zxc_stream_reader_fail(zxc_stream_ctx_t *ctx, const int code)
Records a reader failure; workers write fail_code under the same lock.
static int zxc_stream_read_frame_header(zxc_stream_ctx_t *ctx, FILE *f_in, const uint8_t *magic, const int has_dict, const uint32_t dict_id, size_t *chunk, int *has_checksum, int *has_seek, int *frame_dict)
Reads and checks a frame header whose magic word is already read.
static int64_t zxc_stream_read_at(const zxc_stream_ctx_t *ctx, void *dst, const size_t len, const uint64_t offset)
Positioned read of the input, safe from any thread.
static void zxc_stream_open_positioned(zxc_stream_ctx_t *ctx, FILE *f_in, const int fd)
Switches a regular file to positioned reads from its current position.
static int64_t zxc_stream_in_read(zxc_stream_ctx_t *ctx, FILE *f, void *dst, const size_t len)
Reads up to len input bytes on the reader thread: by position while the engine reads positioned,...
static int zxc_stream_read_frame_info(FILE *f_in, zxc_frame_info_t *info)
Reads the header and the end of the file in f_in, from offset 0, and validates the frame they describ...
static int zxc_file_span(FILE *f, long long *saved, uint64_t *size)
The size of f; its position goes to saved, for the caller to restore.
static int zxc_stream_process(const zxc_stream_ctx_t *ctx, zxc_cctx_t *cctx, const uint8_t *in, const size_t in_sz, uint8_t *out, const size_t out_cap, const uint64_t block_index)
Runs one chunk through the codec the stream's mode selects.
static int64_t zxc_stream_decode_frame(zxc_stream_engine_t *e, FILE *f_in, const int has_seek)
Decodes one frame's blocks, SEK block and footer through a started engine.
static size_t zxc_stream_read_chunk(zxc_stream_ctx_t *ctx, FILE *f_in, zxc_stream_job_t *job, int *eof)
Fills a compression job with the next chunk of the source.
static int zxc_ring_next(const zxc_stream_ctx_t *ctx, const int idx)
The ring slot after idx.
static int zxc_stream_engine_close(zxc_stream_engine_t *e, FILE *f_in)
Stops a decompression engine; moves the FILE* to where positioned reads ended.
static int64_t zxc_pread_full(const int fd, void *dst, const size_t len, const uint64_t offset)
Thread-safe pread of len bytes, retrying EINTR and partial transfers.
static int zxc_stream_read_exact(zxc_stream_ctx_t *ctx, FILE *f, void *dst, const size_t len, const int short_code)
Reads exactly len bytes, telling a clean end from a short read.
static int zxc_stream_engine_start(zxc_stream_engine_t *e, FILE *f_in, const int n_threads)
Allocates the job ring and starts the workers and the writer.
static void * zxc_stream_worker(void *arg)
Worker thread: pull a job, process it, hand it to the writer.
static int zxc_file_scan_read(const zxc_scan_src_t *src, const uint64_t off, void *dst, const size_t len)
zxc_scan_src_t over a FILE*.
static void * zxc_async_writer(void *arg)
Asynchronous writer thread function.
job_status_t
Represents the lifecycle states of a processing job within the ring buffer.
@ JOB_STATUS_FREE
The job slot is empty and available to be filled with new data by the writer.
@ JOB_STATUS_FILLED
The job slot has been populated with input data and is ready for processing by a worker.
@ JOB_STATUS_PROCESSED
The worker has finished processing the data; the result is ready to be consumed/written out.
static int zxc_stream_read_loop(zxc_stream_ctx_t *ctx, FILE *f_in, int read_idx)
Reads the input and feeds the ring until the stream ends.
static int zxc_stream_decode_job(const zxc_stream_ctx_t *ctx, zxc_cctx_t *cctx, const zxc_stream_job_t *job, const uint8_t *in, uint8_t *dict_work)
Decodes a job's blocks into its output.
static void zxc_stream_finish_compress(zxc_stream_ctx_t *ctx, writer_args_t *w, FILE *f_out)
Closes a compressed stream: EOF block, optional seek table, footer.
Error codes and error-name lookup for the ZXC library.
Internal definitions, constants, SIMD helpers, and utility functions.
static uint32_t zxc_le32(const void *p)
Reads a little-endian 32-bit value from a possibly unaligned address.
static void zxc_frame_info_copy(zxc_frame_info_t *info, const size_t info_size, const zxc_frame_info_t *got)
Copies the fields of got that fit the caller's info_size bytes.
void zxc_seekable_attach_owned_ctx(zxc_seekable *s, void *ctx)
Hands ownership of a heap-allocated reader context to a seekable handle.
static uint64_t zxc_digest_combine(const uint64_t acc, const uint32_t block_checksum)
Folds a data block's 32-bit checksum into the running archive digest.
static size_t zxc_block_size_ceil(const size_t v)
Branchless bit_ceil: smallest power of two >= v, clamped to ZXC_BLOCK_SIZE_MIN.
#define ZXC_OPTS_DICT_HUF(o)
Shared literal Huffman table, gated on dict the same way.
#define ZXC_OPTS_LEVEL(o, dflt)
Compression level, 0 meaning the default.
static uint8_t zxc_hash8(const uint8_t *p)
Computes the 1-byte checksum for block headers.
#define ZXC_FOOTER_MAX_SIZE_WITH_DIGEST
Most bytes a footer spans: the digest and the two longest sizes.
#define ZXC_OPTS_DICT_SIZE(o)
Dictionary length from a (possibly NULL) parameter struct.
#define ZXC_OPTS_BLOCK_SIZE(o, dflt)
Block size, 0 meaning the default.
static zxc_footer_layout_t zxc_footer_layout(const uint64_t prefix, const uint64_t src_size, const int checksum_enabled)
The footer of a frame whose first prefix bytes precede it.
void(* zxc_progress_callback_t)(uint64_t bytes_processed, uint64_t bytes_total, const void *user_data)
Progress callback function type.
Seekable compression and random-access decompression API.
FILE*-flavored variants of the ZXC API.
POSIX-shaped threading layer shared by the stream engine (zxc_driver.c) and the seekable reader (zxc_...
static int zxc_num_procs(void)
Returns the number of online logical processors.