phoboslab / qoa

The “Quite OK Audio Format” for fast, lossy audio compression
MIT License
769 stars 42 forks source link

Move memory allocations out of `qoa_encode/decode` #55

Closed DeeJayLSP closed 2 months ago

DeeJayLSP commented 2 months ago

Normally, both qoa_encode and qoa_decode allocate memory, doing the encode/decode process then returning a pointer to the result.

This assumes the user's program doesn't have a required custom implementation of memory allocation to store the result, so depending on how it is implemented, two buffers (the one created by qoa_encode/decode + the one in the program) end up being necessary, using twice as much memory needed in the process.

This change moves memory allocations out of qoa_encode and qoa_decode, modifying them to write to a buffer provided by the user. This way, no unfreed memory allocations are done within qoa.h.

To help with determining size for allocation outside of them, two functions (qoa_encode_size and qoa_decode_size) have been added.

qoaconv still works as intended. qoaplay doesn't get affected by this.

phoboslab commented 2 months ago

This is a solid idea, but I don't want to change the API anymore. There's other ways to achieve this.

I see qoa_decode() (and by extension qoa_read()) as a "convenience" API for users that don't care much about memory management. After all, allocating a buffer for the whole file is rarely what you want in a memory/performance conscious applications.

Users that do care about memory can drop to one level below and use qoa_decode_frame() instead, as demonstrated by qoaplay. For simpler cases with a custom allocator, you can define QOA_MALLOC and QOA_FREE.