Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encode: optimize image window bits #206

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions spng/spng.c
Original file line number Diff line number Diff line change
Expand Up @@ -1161,6 +1161,19 @@ static int discard_chunk_bytes(spng_ctx *ctx, uint32_t bytes)
return 0;
}

static int minimum_window_bits(size_t size)
{
if(size > 16384) return 15;
else if(size > 8192) return 14;
else if(size > 4096) return 13;
else if(size > 2048) return 12;
else if(size > 1024) return 11;
else if(size > 512) return 10;
else if(size > 256) return 9;

return 8;
}

static int spng__inflate_init(spng_ctx *ctx, int window_bits)
{
if(ctx->zstream.state) inflateEnd(&ctx->zstream);
Expand Down Expand Up @@ -4788,6 +4801,18 @@ int spng_encode_image(spng_ctx *ctx, const void *img, size_t len, int fmt, int f
ctx->image_options.strategy = Z_DEFAULT_STRATEGY;
}

#ifndef SPNG_USE_MINIZ
if(ctx->image_size && spng__optimize(SPNG_IMG_WINDOW_BITS))
{
int window_bits = minimum_window_bits(ctx->image_size);

/* Avoid degrading compression factor (https://zlib.net/zlib_tech.html). */
if(window_bits < 15) window_bits++;

ctx->image_options.window_bits = window_bits;
}
#endif

ret = spng__deflate_init(ctx, &ctx->image_options);
if(ret) return encode_err(ctx, ret);

Expand Down