LibGd 2.4.0-dev
GD Graphics library
Loading...
Searching...
No Matches
gd_qoi.h
1/*
2
3Copyright (c) 2021, Dominic Szablewski - https://phoboslab.org
4SPDX-License-Identifier: MIT
5
6This copy is vendored for libgd's QOI codec. The upstream MIT license is
7also included in docs/QOI-LICENSE.
8
9
10QOI - The "Quite OK Image" format for fast, lossless image compression
11
12-- About
13
14QOI encodes and decodes images in a lossless format. Compared to stb_image and
15stb_image_write QOI offers 20x-50x faster encoding, 3x-4x faster decoding and
1620% better compression.
17
18
19-- Synopsis
20
21// Define `QOI_IMPLEMENTATION` in *one* C/C++ file before including this
22// library to create the implementation.
23
24#define QOI_IMPLEMENTATION
25#include "qoi.h"
26
27// Encode and store an RGBA buffer to the file system. The qoi_desc describes
28// the input pixel data.
29qoi_write("image_new.qoi", rgba_pixels, &(qoi_desc){
30 .width = 1920,
31 .height = 1080,
32 .channels = 4,
33 .colorspace = QOI_SRGB
34});
35
36// Load and decode a QOI image from the file system into a 32bbp RGBA buffer.
37// The qoi_desc struct will be filled with the width, height, number of channels
38// and colorspace read from the file header.
39qoi_desc desc;
40void *rgba_pixels = qoi_read("image.qoi", &desc, 4);
41
42
43
44-- Documentation
45
46This library provides the following functions;
47- qoi_read -- read and decode a QOI file
48- qoi_decode -- decode the raw bytes of a QOI image from memory
49- qoi_write -- encode and write a QOI file
50- qoi_encode -- encode an rgba buffer into a QOI image in memory
51
52See the function declaration below for the signature and more information.
53
54If you don't want/need the qoi_read and qoi_write functions, you can define
55QOI_NO_STDIO before including this library.
56
57This library uses malloc() and free(). To supply your own malloc implementation
58you can define QOI_MALLOC and QOI_FREE before including this library.
59
60This library uses memset() to zero-initialize the index. To supply your own
61implementation you can define QOI_ZEROARR before including this library.
62
63
64-- Data Format
65
66A QOI file has a 14 byte header, followed by any number of data "chunks" and an
678-byte end marker.
68
69struct qoi_header_t {
70 char magic[4]; // magic bytes "qoif"
71 uint32_t width; // image width in pixels (BE)
72 uint32_t height; // image height in pixels (BE)
73 uint8_t channels; // 3 = RGB, 4 = RGBA
74 uint8_t colorspace; // 0 = sRGB with linear alpha, 1 = all channels linear
75};
76
77Images are encoded row by row, left to right, top to bottom. The decoder and
78encoder start with {r: 0, g: 0, b: 0, a: 255} as the previous pixel value. An
79image is complete when all pixels specified by width * height have been covered.
80
81Pixels are encoded as
82 - a run of the previous pixel
83 - an index into an array of previously seen pixels
84 - a difference to the previous pixel value in r,g,b
85 - full r,g,b or r,g,b,a values
86
87The color channels are assumed to not be premultiplied with the alpha channel
88("un-premultiplied alpha").
89
90A running array[64] (zero-initialized) of previously seen pixel values is
91maintained by the encoder and decoder. Each pixel that is seen by the encoder
92and decoder is put into this array at the position formed by a hash function of
93the color value. In the encoder, if the pixel value at the index matches the
94current pixel, this index position is written to the stream as QOI_OP_INDEX.
95The hash function for the index is:
96
97 index_position = (r * 3 + g * 5 + b * 7 + a * 11) % 64
98
99Each chunk starts with a 2- or 8-bit tag, followed by a number of data bits. The
100bit length of chunks is divisible by 8 - i.e. all chunks are byte aligned. All
101values encoded in these data bits have the most significant bit on the left.
102
103The 8-bit tags have precedence over the 2-bit tags. A decoder must check for the
104presence of an 8-bit tag first.
105
106The byte stream's end is marked with 7 0x00 bytes followed a single 0x01 byte.
107
108
109The possible chunks are:
110
111
112.- QOI_OP_INDEX ----------.
113| Byte[0] |
114| 7 6 5 4 3 2 1 0 |
115|-------+-----------------|
116| 0 0 | index |
117`-------------------------`
1182-bit tag b00
1196-bit index into the color index array: 0..63
120
121A valid encoder must not issue 2 or more consecutive QOI_OP_INDEX chunks to the
122same index. QOI_OP_RUN should be used instead.
123
124
125.- QOI_OP_DIFF -----------.
126| Byte[0] |
127| 7 6 5 4 3 2 1 0 |
128|-------+-----+-----+-----|
129| 0 1 | dr | dg | db |
130`-------------------------`
1312-bit tag b01
1322-bit red channel difference from the previous pixel between -2..1
1332-bit green channel difference from the previous pixel between -2..1
1342-bit blue channel difference from the previous pixel between -2..1
135
136The difference to the current channel values are using a wraparound operation,
137so "1 - 2" will result in 255, while "255 + 1" will result in 0.
138
139Values are stored as unsigned integers with a bias of 2. E.g. -2 is stored as
1400 (b00). 1 is stored as 3 (b11).
141
142The alpha value remains unchanged from the previous pixel.
143
144
145.- QOI_OP_LUMA -------------------------------------.
146| Byte[0] | Byte[1] |
147| 7 6 5 4 3 2 1 0 | 7 6 5 4 3 2 1 0 |
148|-------+-----------------+-------------+-----------|
149| 1 0 | green diff | dr - dg | db - dg |
150`---------------------------------------------------`
1512-bit tag b10
1526-bit green channel difference from the previous pixel -32..31
1534-bit red channel difference minus green channel difference -8..7
1544-bit blue channel difference minus green channel difference -8..7
155
156The green channel is used to indicate the general direction of change and is
157encoded in 6 bits. The red and blue channels (dr and db) base their diffs off
158of the green channel difference and are encoded in 4 bits. I.e.:
159 dr_dg = (cur_px.r - prev_px.r) - (cur_px.g - prev_px.g)
160 db_dg = (cur_px.b - prev_px.b) - (cur_px.g - prev_px.g)
161
162The difference to the current channel values are using a wraparound operation,
163so "10 - 13" will result in 253, while "250 + 7" will result in 1.
164
165Values are stored as unsigned integers with a bias of 32 for the green channel
166and a bias of 8 for the red and blue channel.
167
168The alpha value remains unchanged from the previous pixel.
169
170
171.- QOI_OP_RUN ------------.
172| Byte[0] |
173| 7 6 5 4 3 2 1 0 |
174|-------+-----------------|
175| 1 1 | run |
176`-------------------------`
1772-bit tag b11
1786-bit run-length repeating the previous pixel: 1..62
179
180The run-length is stored with a bias of -1. Note that the run-lengths 63 and 64
181(b111110 and b111111) are illegal as they are occupied by the QOI_OP_RGB and
182QOI_OP_RGBA tags.
183
184
185.- QOI_OP_RGB ------------------------------------------.
186| Byte[0] | Byte[1] | Byte[2] | Byte[3] |
187| 7 6 5 4 3 2 1 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 |
188|-------------------------+---------+---------+---------|
189| 1 1 1 1 1 1 1 0 | red | green | blue |
190`-------------------------------------------------------`
1918-bit tag b11111110
1928-bit red channel value
1938-bit green channel value
1948-bit blue channel value
195
196The alpha value remains unchanged from the previous pixel.
197
198
199.- QOI_OP_RGBA ---------------------------------------------------.
200| Byte[0] | Byte[1] | Byte[2] | Byte[3] | Byte[4] |
201| 7 6 5 4 3 2 1 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 | 7 .. 0 |
202|-------------------------+---------+---------+---------+---------|
203| 1 1 1 1 1 1 1 1 | red | green | blue | alpha |
204`-----------------------------------------------------------------`
2058-bit tag b11111111
2068-bit red channel value
2078-bit green channel value
2088-bit blue channel value
2098-bit alpha channel value
210
211*/
212
213/* -----------------------------------------------------------------------------
214Header - Public functions */
215
216#ifndef GD_QOI_H
217#define GD_QOI_H
218
219#define QOI_NO_STDIO
220#define QOI_MALLOC(sz) gdMalloc(sz)
221#define QOI_FREE(p) gdFree(p)
222#define qoi_encode gdQoiEncode
223#define qoi_decode gdQoiDecode
224
225#ifdef __cplusplus
226extern "C" {
227#endif
228
229/* A pointer to a qoi_desc struct has to be supplied to all of qoi's functions.
230It describes either the input format (for qoi_write and qoi_encode), or is
231filled with the description read from the file header (for qoi_read and
232qoi_decode).
233
234The colorspace in this qoi_desc is an enum where
235 0 = sRGB, i.e. gamma scaled RGB channels and a linear alpha channel
236 1 = all channels are linear
237You may use the constants QOI_SRGB or QOI_LINEAR. The colorspace is purely
238informative. It will be saved to the file header, but does not affect
239how chunks are en-/decoded. */
240
241#define QOI_SRGB 0
242#define QOI_LINEAR 1
243
244typedef struct {
245 unsigned int width;
246 unsigned int height;
247 unsigned char channels;
248 unsigned char colorspace;
249} qoi_desc;
250
251#ifndef QOI_NO_STDIO
252
253/* Encode raw RGB or RGBA pixels into a QOI image and write it to the file
254system. The qoi_desc struct must be filled with the image width, height,
255number of channels (3 = RGB, 4 = RGBA) and the colorspace.
256
257The function returns 0 on failure (invalid parameters, or fopen or malloc
258failed) or the number of bytes written on success. */
259
260int qoi_write(const char *filename, const void *data, const qoi_desc *desc);
261
262/* Read and decode a QOI image from the file system. If channels is 0, the
263number of channels from the file header is used. If channels is 3 or 4 the
264output format will be forced into this number of channels.
265
266The function either returns NULL on failure (invalid data, or malloc or fopen
267failed) or a pointer to the decoded pixels. On success, the qoi_desc struct
268will be filled with the description from the file header.
269
270The returned pixel data should be free()d after use. */
271
272void *qoi_read(const char *filename, qoi_desc *desc, int channels);
273
274#endif /* QOI_NO_STDIO */
275
276/* Encode raw RGB or RGBA pixels into a QOI image in memory.
277
278The function either returns NULL on failure (invalid parameters or malloc
279failed) or a pointer to the encoded data on success. On success the out_len
280is set to the size in bytes of the encoded data.
281
282The returned qoi data should be free()d after use. */
283
284void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len);
285
286/* Decode a QOI image from memory.
287
288The function either returns NULL on failure (invalid parameters or malloc
289failed) or a pointer to the decoded pixels. On success, the qoi_desc struct
290is filled with the description from the file header.
291
292The returned pixel data should be free()d after use. */
293
294void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels);
295
296#ifdef __cplusplus
297}
298#endif
299#endif /* GD_QOI_H */
300
301/* -----------------------------------------------------------------------------
302Implementation */
303
304#ifdef QOI_IMPLEMENTATION
305#include <stdlib.h>
306#include <string.h>
307
308#ifndef QOI_MALLOC
309#define QOI_MALLOC(sz) gdMalloc(sz)
310#define QOI_FREE(p) gdFree(p)
311#endif
312#ifndef QOI_ZEROARR
313#define QOI_ZEROARR(a) memset((a), 0, sizeof(a))
314#endif
315
316#define QOI_OP_INDEX 0x00 /* 00xxxxxx */
317#define QOI_OP_DIFF 0x40 /* 01xxxxxx */
318#define QOI_OP_LUMA 0x80 /* 10xxxxxx */
319#define QOI_OP_RUN 0xc0 /* 11xxxxxx */
320#define QOI_OP_RGB 0xfe /* 11111110 */
321#define QOI_OP_RGBA 0xff /* 11111111 */
322
323#define QOI_MASK_2 0xc0 /* 11000000 */
324
325#define QOI_COLOR_HASH(C) (C.rgba.r * 3 + C.rgba.g * 5 + C.rgba.b * 7 + C.rgba.a * 11)
326#define QOI_MAGIC \
327 (((unsigned int)'q') << 24 | ((unsigned int)'o') << 16 | ((unsigned int)'i') << 8 | \
328 ((unsigned int)'f'))
329#define QOI_HEADER_SIZE 14
330
331/* 2GB is the max file size that this implementation can safely handle. We guard
332against anything larger than that, assuming the worst case with 5 bytes per
333pixel, rounded down to a nice clean value. 400 million pixels ought to be
334enough for anybody. */
335#define QOI_PIXELS_MAX ((unsigned int)400000000)
336
337typedef union {
338 struct {
339 unsigned char r, g, b, a;
340 } rgba;
341 unsigned int v;
342} qoi_rgba_t;
343
344static const unsigned char qoi_padding[8] = {0, 0, 0, 0, 0, 0, 0, 1};
345
346static void qoi_write_32(unsigned char *bytes, int *p, unsigned int v)
347{
348 bytes[(*p)++] = (0xff000000 & v) >> 24;
349 bytes[(*p)++] = (0x00ff0000 & v) >> 16;
350 bytes[(*p)++] = (0x0000ff00 & v) >> 8;
351 bytes[(*p)++] = (0x000000ff & v);
352}
353
354static unsigned int qoi_read_32(const unsigned char *bytes, int *p)
355{
356 unsigned int a = bytes[(*p)++];
357 unsigned int b = bytes[(*p)++];
358 unsigned int c = bytes[(*p)++];
359 unsigned int d = bytes[(*p)++];
360 return a << 24 | b << 16 | c << 8 | d;
361}
362
363void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len)
364{
365 int i, max_size, p, run;
366 int px_len, px_end, px_pos, channels;
367 unsigned char *bytes;
368 const unsigned char *pixels;
369 qoi_rgba_t index[64];
370 qoi_rgba_t px, px_prev;
371
372 if (data == NULL || out_len == NULL || desc == NULL || desc->width == 0 || desc->height == 0 ||
373 desc->channels < 3 || desc->channels > 4 || desc->colorspace > 1 ||
374 desc->height >= QOI_PIXELS_MAX / desc->width) {
375 return NULL;
376 }
377
378 max_size =
379 desc->width * desc->height * (desc->channels + 1) + QOI_HEADER_SIZE + sizeof(qoi_padding);
380
381 p = 0;
382 bytes = (unsigned char *)QOI_MALLOC(max_size);
383 if (!bytes) {
384 return NULL;
385 }
386
387 qoi_write_32(bytes, &p, QOI_MAGIC);
388 qoi_write_32(bytes, &p, desc->width);
389 qoi_write_32(bytes, &p, desc->height);
390 bytes[p++] = desc->channels;
391 bytes[p++] = desc->colorspace;
392
393 pixels = (const unsigned char *)data;
394
395 QOI_ZEROARR(index);
396
397 run = 0;
398 px_prev.rgba.r = 0;
399 px_prev.rgba.g = 0;
400 px_prev.rgba.b = 0;
401 px_prev.rgba.a = 255;
402 px = px_prev;
403
404 px_len = desc->width * desc->height * desc->channels;
405 px_end = px_len - desc->channels;
406 channels = desc->channels;
407
408 for (px_pos = 0; px_pos < px_len; px_pos += channels) {
409 px.rgba.r = pixels[px_pos + 0];
410 px.rgba.g = pixels[px_pos + 1];
411 px.rgba.b = pixels[px_pos + 2];
412
413 if (channels == 4) {
414 px.rgba.a = pixels[px_pos + 3];
415 }
416
417 if (px.v == px_prev.v) {
418 run++;
419 if (run == 62 || px_pos == px_end) {
420 bytes[p++] = QOI_OP_RUN | (run - 1);
421 run = 0;
422 }
423 } else {
424 int index_pos;
425
426 if (run > 0) {
427 bytes[p++] = QOI_OP_RUN | (run - 1);
428 run = 0;
429 }
430
431 index_pos = QOI_COLOR_HASH(px) & (64 - 1);
432
433 if (index[index_pos].v == px.v) {
434 bytes[p++] = QOI_OP_INDEX | index_pos;
435 } else {
436 index[index_pos] = px;
437
438 if (px.rgba.a == px_prev.rgba.a) {
439 signed char vr = px.rgba.r - px_prev.rgba.r;
440 signed char vg = px.rgba.g - px_prev.rgba.g;
441 signed char vb = px.rgba.b - px_prev.rgba.b;
442
443 signed char vg_r = vr - vg;
444 signed char vg_b = vb - vg;
445
446 if (vr > -3 && vr < 2 && vg > -3 && vg < 2 && vb > -3 && vb < 2) {
447 bytes[p++] = QOI_OP_DIFF | (vr + 2) << 4 | (vg + 2) << 2 | (vb + 2);
448 } else if (vg_r > -9 && vg_r < 8 && vg > -33 && vg < 32 && vg_b > -9 &&
449 vg_b < 8) {
450 bytes[p++] = QOI_OP_LUMA | (vg + 32);
451 bytes[p++] = (vg_r + 8) << 4 | (vg_b + 8);
452 } else {
453 bytes[p++] = QOI_OP_RGB;
454 bytes[p++] = px.rgba.r;
455 bytes[p++] = px.rgba.g;
456 bytes[p++] = px.rgba.b;
457 }
458 } else {
459 bytes[p++] = QOI_OP_RGBA;
460 bytes[p++] = px.rgba.r;
461 bytes[p++] = px.rgba.g;
462 bytes[p++] = px.rgba.b;
463 bytes[p++] = px.rgba.a;
464 }
465 }
466 }
467 px_prev = px;
468 }
469
470 for (i = 0; i < (int)sizeof(qoi_padding); i++) {
471 bytes[p++] = qoi_padding[i];
472 }
473
474 *out_len = p;
475 return bytes;
476}
477
478void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels)
479{
480 const unsigned char *bytes;
481 unsigned int header_magic;
482 unsigned char *pixels;
483 qoi_rgba_t index[64];
484 qoi_rgba_t px;
485 int px_len, chunks_len, px_pos;
486 int p = 0, run = 0;
487
488 if (data == NULL || desc == NULL || (channels != 0 && channels != 3 && channels != 4) ||
489 size < QOI_HEADER_SIZE + (int)sizeof(qoi_padding)) {
490 return NULL;
491 }
492
493 bytes = (const unsigned char *)data;
494
495 if (memcmp(bytes + size - sizeof(qoi_padding), qoi_padding, sizeof(qoi_padding)) != 0) {
496 return NULL;
497 }
498
499 header_magic = qoi_read_32(bytes, &p);
500 desc->width = qoi_read_32(bytes, &p);
501 desc->height = qoi_read_32(bytes, &p);
502 desc->channels = bytes[p++];
503 desc->colorspace = bytes[p++];
504
505 if (desc->width == 0 || desc->height == 0 || desc->channels < 3 || desc->channels > 4 ||
506 desc->colorspace > 1 || header_magic != QOI_MAGIC ||
507 desc->height >= QOI_PIXELS_MAX / desc->width) {
508 return NULL;
509 }
510
511 if (channels == 0) {
512 channels = desc->channels;
513 }
514
515 px_len = desc->width * desc->height * channels;
516 pixels = (unsigned char *)QOI_MALLOC(px_len);
517 if (!pixels) {
518 return NULL;
519 }
520
521 QOI_ZEROARR(index);
522 px.rgba.r = 0;
523 px.rgba.g = 0;
524 px.rgba.b = 0;
525 px.rgba.a = 255;
526
527 chunks_len = size - (int)sizeof(qoi_padding);
528 for (px_pos = 0; px_pos < px_len; px_pos += channels) {
529 if (run > 0) {
530 run--;
531 } else if (p < chunks_len) {
532 int b1 = bytes[p++];
533
534 if (b1 == QOI_OP_RGB) {
535 if (p + 3 > chunks_len) {
536 QOI_FREE(pixels);
537 return NULL;
538 }
539 px.rgba.r = bytes[p++];
540 px.rgba.g = bytes[p++];
541 px.rgba.b = bytes[p++];
542 } else if (b1 == QOI_OP_RGBA) {
543 if (p + 4 > chunks_len) {
544 QOI_FREE(pixels);
545 return NULL;
546 }
547 px.rgba.r = bytes[p++];
548 px.rgba.g = bytes[p++];
549 px.rgba.b = bytes[p++];
550 px.rgba.a = bytes[p++];
551 } else if ((b1 & QOI_MASK_2) == QOI_OP_INDEX) {
552 px = index[b1];
553 } else if ((b1 & QOI_MASK_2) == QOI_OP_DIFF) {
554 px.rgba.r += ((b1 >> 4) & 0x03) - 2;
555 px.rgba.g += ((b1 >> 2) & 0x03) - 2;
556 px.rgba.b += (b1 & 0x03) - 2;
557 } else if ((b1 & QOI_MASK_2) == QOI_OP_LUMA) {
558 if (p >= chunks_len) {
559 QOI_FREE(pixels);
560 return NULL;
561 }
562 int b2 = bytes[p++];
563 int vg = (b1 & 0x3f) - 32;
564 px.rgba.r += vg - 8 + ((b2 >> 4) & 0x0f);
565 px.rgba.g += vg;
566 px.rgba.b += vg - 8 + (b2 & 0x0f);
567 } else if ((b1 & QOI_MASK_2) == QOI_OP_RUN) {
568 run = (b1 & 0x3f);
569 }
570
571 index[QOI_COLOR_HASH(px) & (64 - 1)] = px;
572 } else {
573 QOI_FREE(pixels);
574 return NULL;
575 }
576
577 pixels[px_pos + 0] = px.rgba.r;
578 pixels[px_pos + 1] = px.rgba.g;
579 pixels[px_pos + 2] = px.rgba.b;
580
581 if (channels == 4) {
582 pixels[px_pos + 3] = px.rgba.a;
583 }
584 }
585
586 return pixels;
587}
588
589#ifndef QOI_NO_STDIO
590#include <stdio.h>
591
592int qoi_write(const char *filename, const void *data, const qoi_desc *desc)
593{
594 FILE *f = fopen(filename, "wb");
595 int size, err;
596 void *encoded;
597
598 if (!f) {
599 return 0;
600 }
601
602 encoded = qoi_encode(data, desc, &size);
603 if (!encoded) {
604 fclose(f);
605 return 0;
606 }
607
608 fwrite(encoded, 1, size, f);
609 fflush(f);
610 err = ferror(f);
611 fclose(f);
612
613 QOI_FREE(encoded);
614 return err ? 0 : size;
615}
616
617void *qoi_read(const char *filename, qoi_desc *desc, int channels)
618{
619 FILE *f = fopen(filename, "rb");
620 int size, bytes_read;
621 void *pixels, *data;
622
623 if (!f) {
624 return NULL;
625 }
626
627 fseek(f, 0, SEEK_END);
628 size = ftell(f);
629 if (size <= 0 || fseek(f, 0, SEEK_SET) != 0) {
630 fclose(f);
631 return NULL;
632 }
633
634 data = QOI_MALLOC(size);
635 if (!data) {
636 fclose(f);
637 return NULL;
638 }
639
640 bytes_read = fread(data, 1, size, f);
641 fclose(f);
642 pixels = (bytes_read != size) ? NULL : qoi_decode(data, bytes_read, desc, channels);
643 QOI_FREE(data);
644 return pixels;
645}
646
647#endif /* QOI_NO_STDIO */
648#endif /* QOI_IMPLEMENTATION */