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

Some optimizations on image.c buffer and stb_image to use less memory. #422

Merged
merged 1 commit into from
Sep 2, 2019
Merged
Show file tree
Hide file tree
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
12 changes: 12 additions & 0 deletions Sources/kinc/image.c
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,17 @@
#define BUFFER_SIZE 4096 * 4096 * 4
uint8_t buffer[BUFFER_SIZE];
size_t buffer_offset = 0;
uint8_t *last_allocated_pointer = 0;

static void *buffer_malloc(size_t size) {
uint8_t *current = &buffer[buffer_offset];
buffer_offset += size + sizeof(size_t);
if (buffer_offset > BUFFER_SIZE) {
kinc_log(KINC_LOG_LEVEL_ERROR, "Not enough memory on image.c Buffer.");
return NULL;
}
*(size_t*)current = size;
last_allocated_pointer = current + sizeof(size_t);
return current + sizeof(size_t);
}

Expand All @@ -38,7 +41,16 @@ static void *buffer_realloc(void *p, size_t size) {
return old_pointer;
}
else {
if (last_allocated_pointer == old_pointer){
size_t last_size = &buffer[buffer_offset] - old_pointer;
size_t size_diff = size - last_size;
buffer_offset += size_diff + sizeof(size_t);
return old_pointer;
}
uint8_t *new_pointer = (uint8_t *)buffer_malloc(size);
if (new_pointer == NULL){
return NULL;
}
memcpy(new_pointer, old_pointer, old_size < size ? old_size : size);
return new_pointer;
}
Expand Down
4 changes: 3 additions & 1 deletion Sources/kinc/libs/stb_image.h
Original file line number Diff line number Diff line change
Expand Up @@ -4894,7 +4894,9 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
stbi_uc *p;
if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
while (ioff + c.length > idata_limit)
idata_limit *= 2;
//Originally this was idata_limit *= 2. Changed to append a constant size on realloc instead of doubleing everytime.
//This saves some space on the image.c buffer.
idata_limit += 1 << 16;
STBI_NOTUSED(idata_limit_old);
p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
z->idata = p;
Expand Down