summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/workflows/build.yaml76
-rw-r--r--.github/workflows/static-analysis.yaml61
-rw-r--r--COPYING1
-rw-r--r--Makefile9
-rw-r--r--README36
-rw-r--r--README.md147
-rw-r--r--include/libnsgif.h192
-rw-r--r--include/nsgif.h527
-rw-r--r--src/Makefile2
-rw-r--r--src/gif.c2076
-rw-r--r--src/libnsgif.c1228
-rw-r--r--src/lzw.c530
-rw-r--r--src/lzw.h100
-rw-r--r--src/utils/log.h21
-rw-r--r--test/Makefile2
-rw-r--r--test/cli.c827
-rw-r--r--test/cli.h99
-rw-r--r--test/decode_gif.c250
-rw-r--r--test/nsgif.c442
-rwxr-xr-xtest/runtest.sh60
20 files changed, 4743 insertions, 1943 deletions
diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml
new file mode 100644
index 0000000..629c048
--- /dev/null
+++ b/.github/workflows/build.yaml
@@ -0,0 +1,76 @@
+name: "Linux Build"
+
+on: [push]
+
+jobs:
+ linux:
+ name: '${{ matrix.os }}: ${{ matrix.compiler.vendor }}'
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - ubuntu-22.04
+ - ubuntu-20.04
+ compiler:
+ # The NetSurf build system can't find LLVM AR (it looks for it
+ # in /usr/lib instead of /usr/bin:
+ # `make: /usr/lib/llvm-ar: No such file or directory`).
+ # So we need to make it explicit for llvm.
+ - { vendor: gnu, CC: gcc, AR: ar }
+ - { vendor: llvm, CC: clang, AR: llvm-ar }
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ with:
+ fetch-depth: 1
+
+ - name: apt-get install packages
+ run: sudo apt-get update -qq &&
+ sudo apt-get install --no-install-recommends -y
+ bison
+ build-essential
+ check
+ clang
+ flex
+ git
+ gperf
+ llvm
+ pkg-config
+
+ - name: Get env.sh
+ run: |
+ mkdir projects
+ wget -O projects/env.sh https://git.netsurf-browser.org/netsurf.git/plain/docs/env.sh
+
+ - name: Build and install project deps
+ env:
+ CC: ${{ matrix.compiler.CC }}
+ AR: ${{ matrix.compiler.AR }}
+ TARGET: ${{ github.event.repository.name }}
+ run: |
+ export TARGET_WORKSPACE="$(pwd)/projects"
+ source projects/env.sh
+ ns-clone -d -s
+ ns-make-libs install
+
+ - name: Build Library
+ env:
+ CC: ${{ matrix.compiler.CC }}
+ AR: ${{ matrix.compiler.AR }}
+ TARGET: ${{ github.event.repository.name }}
+ run: |
+ export TARGET_WORKSPACE="$(pwd)/projects"
+ source projects/env.sh
+ make -j"$(nproc)"
+
+ - name: Unit Tests
+ env:
+ CC: ${{ matrix.compiler.CC }}
+ AR: ${{ matrix.compiler.AR }}
+ TARGET: ${{ github.event.repository.name }}
+ run: |
+ export TARGET_WORKSPACE="$(pwd)/projects"
+ source projects/env.sh
+ make test
diff --git a/.github/workflows/static-analysis.yaml b/.github/workflows/static-analysis.yaml
new file mode 100644
index 0000000..ec5171f
--- /dev/null
+++ b/.github/workflows/static-analysis.yaml
@@ -0,0 +1,61 @@
+name: "Static Analysis"
+
+on: [push]
+
+jobs:
+ codeql:
+ name: codeql
+ runs-on: ubuntu-22.04
+
+ strategy:
+ fail-fast: false
+ matrix:
+ language: ['cpp']
+
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v2
+ with:
+ fetch-depth: 1
+
+ - name: apt-get install packages
+ run: sudo apt-get update -qq &&
+ sudo apt-get install --no-install-recommends -y
+ bison
+ build-essential
+ check
+ clang
+ flex
+ git
+ gperf
+ llvm
+ pkg-config
+
+ - name: Get env.sh
+ run: |
+ mkdir projects
+ wget -O projects/env.sh https://git.netsurf-browser.org/netsurf.git/plain/docs/env.sh
+
+ - name: Build and install project deps
+ env:
+ TARGET: ${{ github.event.repository.name }}
+ run: |
+ export TARGET_WORKSPACE="$(pwd)/projects"
+ source projects/env.sh
+ ns-clone -d -s
+ ns-make-libs install
+
+ # Initializes the CodeQL tools for scanning.
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@v2
+ with:
+ languages: ${{ matrix.language }}
+
+ - name: Build Library
+ run: |
+ export TARGET_WORKSPACE="$(pwd)/projects"
+ source projects/env.sh
+ make -j"$(nproc)"
+
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@v2
diff --git a/COPYING b/COPYING
index c6e1688..9334b89 100644
--- a/COPYING
+++ b/COPYING
@@ -1,5 +1,6 @@
Copyright (C) 2004 Richard Wilson
Copyright (C) 2008 Sean Fox
+Copyright (C) 2013-2021 Michael Drake
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/Makefile b/Makefile
index c348e20..e02c073 100644
--- a/Makefile
+++ b/Makefile
@@ -6,7 +6,7 @@
# Component settings
COMPONENT := nsgif
-COMPONENT_VERSION := 0.2.1
+COMPONENT_VERSION := 1.0.0
# Default to a static library
COMPONENT_TYPE ?= lib-static
@@ -19,7 +19,7 @@ include $(NSSHARED)/makefiles/Makefile.tools
TESTRUNNER = test/runtest.sh $(BUILDDIR) $(EXEEXT)
# Toolchain flags
-WARNFLAGS := -Wall -W -Wundef -Wpointer-arith -Wcast-align \
+WARNFLAGS := -Wall -Wextra -W -Wundef -Wpointer-arith -Wcast-align \
-Wwrite-strings -Wstrict-prototypes -Wmissing-prototypes \
-Wmissing-declarations -Wnested-externs -pedantic
# BeOS/Haiku standard library headers create warnings
@@ -27,7 +27,8 @@ ifneq ($(BUILD),i586-pc-haiku)
WARNFLAGS := $(WARNFLAGS) -Werror
endif
-CFLAGS := -D_BSD_SOURCE -D_DEFAULT_SOURCE \
+CFLAGS := -DNSGIF_NAME=$(COMPONENT) \
+ -DNSGIF_VERSION=$(COMPONENT_VERSION) \
-I$(CURDIR)/include/ -I$(CURDIR)/src \
$(WARNFLAGS) $(CFLAGS)
ifneq ($(GCCVER),2)
@@ -44,6 +45,6 @@ include $(NSBUILD)/Makefile.top
# Extra installation rules
I := /$(INCLUDEDIR)
-INSTALL_ITEMS := $(INSTALL_ITEMS) $(I):include/libnsgif.h
+INSTALL_ITEMS := $(INSTALL_ITEMS) $(I):include/nsgif.h
INSTALL_ITEMS := $(INSTALL_ITEMS) /$(LIBDIR)/pkgconfig:lib$(COMPONENT).pc.in
INSTALL_ITEMS := $(INSTALL_ITEMS) /$(LIBDIR):$(OUTPUT)
diff --git a/README b/README
deleted file mode 100644
index 498ee46..0000000
--- a/README
+++ /dev/null
@@ -1,36 +0,0 @@
-libnsgif - Decoding GIF files
-=============================
-
-The functions provided by this library allow for efficient progressive
-GIF decoding. Whilst the initialisation does not ensure that there is
-sufficient image data to complete the entire frame, it does ensure
-that the information provided is valid. Any subsequent attempts to
-decode an initialised GIF are guaranteed to succeed, and any bytes of
-the image not present are assumed to be totally transparent.
-
-To begin decoding a GIF, the 'gif' structure must be initialised with
-the 'gif_data' and 'buffer_size' set to their initial values. The
-'buffer_position' should initially be 0, and will be internally
-updated as the decoding commences. The caller should then repeatedly
-call gif_initialise() with the structure until the function returns 1,
-or no more data is avaliable.
-
-Once the initialisation has begun, the decoder completes the variables
-'frame_count' and 'frame_count_partial'. The former being the total
-number of frames that have been successfully initialised, and the
-latter being the number of frames that a partial amount of data is
-available for. This assists the caller in managing the animation
-whilst decoding is continuing.
-
-To decode a frame, the caller must use gif_decode_frame() which
-updates the current 'frame_image' to reflect the desired frame. The
-required 'disposal_method' is also updated to reflect how the frame
-should be plotted. The caller must not assume that the current
-'frame_image' will be valid between calls if initialisation is still
-occuring, and should either always request that the frame is decoded
-(no processing will occur if the 'decoded_frame' has not been
-invalidated by initialisation) or perform the check itself.
-
-It should be noted that gif_finalise() should always be called, even
-if no frames were initialised. Additionally, it is the responsibility
-of the caller to free 'gif_data'.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..5007da9
--- /dev/null
+++ b/README.md
@@ -0,0 +1,147 @@
+LibNSGIF: NetSurf GIF decoder
+=============================
+
+LibNSGIF is a C library for decoding GIF format images and animations.
+It is licenced under the MIT licence.
+
+This library aims to provide a simple API for robust decoding of GIF files.
+
+Details
+-------
+
+The GIF source data is scanned prior to decoding, allowing for efficient
+decoding. The scanning phase will scan currently available data and will
+resume from where it left off when called with additional data.
+
+Only one frame is ever fully decoded to a bitmap at a time, reducing memory
+usage for large GIFs.
+
+Using
+-----
+
+LibNSGIF allows the client to allocate the bitmap into which the GIF is
+decoded. The client can have an arbitrary bitmap structure, that is simply
+a void pointer to LibNSGIF. The client must provide a callback table for
+interacting with bitmaps, and the required client bitmap pixel format.
+The bitmap table must include as a minimum functions to create and destroy
+bitmaps, and a function to get a pointer to the bitmap's pixel data buffer.
+
+LibNSGIF always decodes to a 32bpp, 8 bits per channel bitmap pixel format,
+however it allows the client to control the colour component ordering.
+
+To load a GIF, first create an nsgif object with `nsgif_create()`.
+
+```c
+ err = nsgif_create(&bitmap_callbacks, NSGIF_BITMAP_FMT_R8G8B8A8, &gif);
+ if (err != NSGIF_OK) {
+ fprintf(stderr, "%s\n", nsgif_strerror(err));
+ // Handle error
+ }
+```
+
+Now you can load the GIF source data into the nsgif object with
+`nsgif_data_scan()`:
+
+```c
+ err = nsgif_data_scan(gif, size, data);
+ if (err != NSGIF_OK) {
+ fprintf(stderr, "%s\n", nsgif_strerror(err));
+ // Handle error
+ }
+```
+
+This scans the source data and decodes information about each frame, however
+it doesn't decode any of the bitmap data for the frames. The client may call
+`nsgif_data_scan()` multiple times as source data is fetched. The early frames
+can be decoded before the later frames are scanned. Frames have to be scanned
+before they can be decoded.
+
+This function will sometimes return an error. That is OK, and even expected.
+It is fine to proceed to decoding any frames that are available after a scan.
+Some errors indicate that there is a flaw in the source GIF data (not at all
+uncommon, GIF is an ancient format that has had many broken encoders), or that
+it has reached the end of the source data.
+
+> **Note**: The client must not free the data until after calling
+> `nsgif_destroy()`. You can move the data, e.g. if you realloc to a bigger
+> buffer. Just be sure to call `nsgif_data_scan()` again with the new pointer
+> before making any other calls against that nsgif object.
+
+When all the source data has been provided to `nsgif_data_scan()` it is
+advisable to call `nsgif_data_complete()` (see below), although this is not
+necessary to start decoding frames.
+
+To decode the frames, you can call `nsgif_get_info()` to get the frame_count,
+and then call `nsgif_frame_decode()` for each frame, and manage the animation,
+and non-displayable frames yourself, or you can use the helper function,
+`nsgif_frame_prepare()`:
+
+```c
+ err = nsgif_frame_prepare(gif, &area, &delay_cs, &frame_new);
+ if (err != NSGIF_OK) {
+ fprintf(stderr, "%s\n", nsgif_strerror(err));
+ // Handle error
+ }
+
+ // Update our bitmap to know it should be showing `frame_new` now.
+ // Trigger redraw of `area` of image.
+
+ if (delay_cs != NSGIF_INFINITE) {
+ // Schedule next frame in delay_cs.
+ }
+```
+
+This will return the number of the next frame to be decoded, the delay in cs
+before the next frame should be decoded, and the area of the bitmap that needs
+to be redrawn.
+
+> **Note**: GIF frames may only occupy a portion of the overall bitmap, and only
+> redrawing the area that has changed may be more efficient than redrawing the
+> whole thing. The returned area comprises both any region that has been
+> changed in the disposal of the previous frame and the new frame.
+
+GIF files can limit the number of animation loops to a finite number or they
+may only have one frame. In either of these cases, the returned delay is
+`NSGIF_INFINITE` indicating that the animation is complete. Subsequent calls
+to `nsgif_frame_prepare()` will return `NSGIF_ERR_ANIMATION_END`.
+
+To force the repeat of an animation, call `nsgif_reset()`.
+
+One reason for the two-step decoding of frames is that it enables deferred
+decoding. You can call `nsgif_frame_prepare()` and cause a redraw of that
+portion of your document. If the GIF is off screen (another tab, or scrolled
+out of sight), there is no need to decode it at all.
+
+Once the bitmap is needed for a redraw, you can decode the correct frame
+on-demand with:
+
+```c
+ err = nsgif_frame_decode(gif, frame_new, &bitmap);
+ if (err != NSGIF_OK) {
+ fprintf(stderr, "%s\n", nsgif_strerror(err));
+ // Handle error
+ }
+```
+
+Note that this will be a no-op if the requested frame already happens to be
+the decoded frame.
+
+You can call `nsgif_frame_prepare()` and `nsgif_frame_decode()` before all
+of the GIF data has been provided using `nsgif_data_scan()` calls. For example
+if you want to make a start decoding and displaying the early frames of the GIF
+before the entire animation file has been downloaded.
+
+When you do this, `nsgif_frame_prepare()` will not loop the animation back to
+the start unless you call `nsgif_data_complete()` to indicate all of the data
+has been fetched. Calling `nsgif_data_complete()` also lets libnsgif display
+any trailing truncated frame.
+
+```c
+ nsgif_data_complete(gif);
+```
+
+Once you are done with the GIF, free up the nsgif object with:
+
+```c
+ nsgif_destroy(gif);
+```
diff --git a/include/libnsgif.h b/include/libnsgif.h
deleted file mode 100644
index 50dc688..0000000
--- a/include/libnsgif.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Copyright 2004 Richard Wilson <richard.wilson@netsurf-browser.org>
- * Copyright 2008 Sean Fox <dyntryx@gmail.com>
- *
- * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/
- * Licenced under the MIT License,
- * http://www.opensource.org/licenses/mit-license.php
- */
-
-/**
- * \file
- * Interface to progressive animated GIF file decoding.
- */
-
-#ifndef _LIBNSGIF_H_
-#define _LIBNSGIF_H_
-
-#include <stdbool.h>
-#include <inttypes.h>
-
-/* Error return values */
-typedef enum {
- GIF_WORKING = 1,
- GIF_OK = 0,
- GIF_INSUFFICIENT_FRAME_DATA = -1,
- GIF_FRAME_DATA_ERROR = -2,
- GIF_INSUFFICIENT_DATA = -3,
- GIF_DATA_ERROR = -4,
- GIF_INSUFFICIENT_MEMORY = -5,
- GIF_FRAME_NO_DISPLAY = -6,
- GIF_END_OF_FRAME = -7
-} gif_result;
-
-/** GIF frame data */
-typedef struct gif_frame {
- /** whether the frame should be displayed/animated */
- bool display;
- /** delay (in cs) before animating the frame */
- unsigned int frame_delay;
-
- /* Internal members are listed below */
-
- /** offset (in bytes) to the GIF frame data */
- unsigned int frame_pointer;
- /** whether the frame has previously been used */
- bool virgin;
- /** whether the frame is totally opaque */
- bool opaque;
- /** whether a forcable screen redraw is required */
- bool redraw_required;
- /** how the previous frame should be disposed; affects plotting */
- unsigned char disposal_method;
- /** whether we acknoledge transparency */
- bool transparency;
- /** the index designating a transparent pixel */
- unsigned char transparency_index;
- /** x co-ordinate of redraw rectangle */
- unsigned int redraw_x;
- /** y co-ordinate of redraw rectangle */
- unsigned int redraw_y;
- /** width of redraw rectangle */
- unsigned int redraw_width;
- /** height of redraw rectangle */
- unsigned int redraw_height;
-} gif_frame;
-
-/* API for Bitmap callbacks */
-typedef void* (*gif_bitmap_cb_create)(int width, int height);
-typedef void (*gif_bitmap_cb_destroy)(void *bitmap);
-typedef unsigned char* (*gif_bitmap_cb_get_buffer)(void *bitmap);
-typedef void (*gif_bitmap_cb_set_opaque)(void *bitmap, bool opaque);
-typedef bool (*gif_bitmap_cb_test_opaque)(void *bitmap);
-typedef void (*gif_bitmap_cb_modified)(void *bitmap);
-
-/** Bitmap callbacks function table */
-typedef struct gif_bitmap_callback_vt {
- /** Create a bitmap. */
- gif_bitmap_cb_create bitmap_create;
- /** Free a bitmap. */
- gif_bitmap_cb_destroy bitmap_destroy;
- /** Return a pointer to the pixel data in a bitmap. */
- gif_bitmap_cb_get_buffer bitmap_get_buffer;
-
- /* Members below are optional */
-
- /** Sets whether a bitmap should be plotted opaque. */
- gif_bitmap_cb_set_opaque bitmap_set_opaque;
- /** Tests whether a bitmap has an opaque alpha channel. */
- gif_bitmap_cb_test_opaque bitmap_test_opaque;
- /** The bitmap image has changed, so flush any persistant cache. */
- gif_bitmap_cb_modified bitmap_modified;
-} gif_bitmap_callback_vt;
-
-/** GIF animation data */
-typedef struct gif_animation {
- /** LZW decode context */
- void *lzw_ctx;
- /** callbacks for bitmap functions */
- gif_bitmap_callback_vt bitmap_callbacks;
- /** pointer to GIF data */
- unsigned char *gif_data;
- /** width of GIF (may increase during decoding) */
- unsigned int width;
- /** heigth of GIF (may increase during decoding) */
- unsigned int height;
- /** number of frames decoded */
- unsigned int frame_count;
- /** number of frames partially decoded */
- unsigned int frame_count_partial;
- /** decoded frames */
- gif_frame *frames;
- /** current frame decoded to bitmap */
- int decoded_frame;
- /** currently decoded image; stored as bitmap from bitmap_create callback */
- void *frame_image;
- /** number of times to loop animation */
- int loop_count;
-
- /* Internal members are listed below */
-
- /** current index into GIF data */
- unsigned int buffer_position;
- /** total number of bytes of GIF data available */
- unsigned int buffer_size;
- /** current number of frame holders */
- unsigned int frame_holders;
- /** index in the colour table for the background colour */
- unsigned int background_index;
- /** image aspect ratio (ignored) */
- unsigned int aspect_ratio;
- /** size of colour table (in entries) */
- unsigned int colour_table_size;
- /** whether the GIF has a global colour table */
- bool global_colours;
- /** global colour table */
- unsigned int *global_colour_table;
- /** local colour table */
- unsigned int *local_colour_table;
-
- /** previous frame for GIF_FRAME_RESTORE */
- void *prev_frame;
- /** previous frame index */
- int prev_index;
- /** previous frame width */
- unsigned prev_width;
- /** previous frame height */
- unsigned prev_height;
-} gif_animation;
-
-/**
- * Initialises necessary gif_animation members.
- */
-void gif_create(gif_animation *gif, gif_bitmap_callback_vt *bitmap_callbacks);
-
-/**
- * Initialises any workspace held by the animation and attempts to decode
- * any information that hasn't already been decoded.
- * If an error occurs, all previously decoded frames are retained.
- *
- * @return Error return value.
- * - GIF_FRAME_DATA_ERROR for GIF frame data error
- * - GIF_INSUFFICIENT_FRAME_DATA for insufficient data to process
- * any more frames
- * - GIF_INSUFFICIENT_MEMORY for memory error
- * - GIF_DATA_ERROR for GIF error
- * - GIF_INSUFFICIENT_DATA for insufficient data to do anything
- * - GIF_OK for successful decoding
- * - GIF_WORKING for successful decoding if more frames are expected
- */
-gif_result gif_initialise(gif_animation *gif, size_t size, unsigned char *data);
-
-/**
- * Decodes a GIF frame.
- *
- * @return Error return value. If a frame does not contain any image data,
- * GIF_OK is returned and gif->current_error is set to
- * GIF_FRAME_NO_DISPLAY
- * - GIF_FRAME_DATA_ERROR for GIF frame data error
- * - GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
- * - GIF_DATA_ERROR for GIF error (invalid frame header)
- * - GIF_INSUFFICIENT_DATA for insufficient data to do anything
- * - GIF_INSUFFICIENT_MEMORY for insufficient memory to process
- * - GIF_OK for successful decoding
- */
-gif_result gif_decode_frame(gif_animation *gif, unsigned int frame);
-
-/**
- * Releases any workspace held by a gif
- */
-void gif_finalise(gif_animation *gif);
-
-#endif
diff --git a/include/nsgif.h b/include/nsgif.h
new file mode 100644
index 0000000..e6873b6
--- /dev/null
+++ b/include/nsgif.h
@@ -0,0 +1,527 @@
+/*
+ * Copyright 2004 Richard Wilson <richard.wilson@netsurf-browser.org>
+ * Copyright 2008 Sean Fox <dyntryx@gmail.com>
+ * Copyright 2013-2022 Michael Drake <tlsa@netsurf-browser.org>
+ *
+ * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/
+ * Licenced under the MIT License,
+ * http://www.opensource.org/licenses/mit-license.php
+ */
+
+/**
+ * \file
+ * Interface to progressive animated GIF file decoding.
+ */
+
+#ifndef NSNSGIF_H
+#define NSNSGIF_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <inttypes.h>
+
+/** Representation of infinity. */
+#define NSGIF_INFINITE (UINT32_MAX)
+
+/** Maximum colour table size */
+#define NSGIF_MAX_COLOURS 256
+
+/**
+ * Opaque type used by LibNSGIF to represent a GIF object in memory.
+ */
+typedef struct nsgif nsgif_t;
+
+/**
+ * LibNSGIF rectangle structure.
+ *
+ * * Top left coordinate is `(x0, y0)`.
+ * * Width is `x1 - x0`.
+ * * Height is `y1 - y0`.
+ * * Units are pixels.
+ */
+typedef struct nsgif_rect {
+ /** x co-ordinate of redraw rectangle, left */
+ uint32_t x0;
+ /** y co-ordinate of redraw rectangle, top */
+ uint32_t y0;
+ /** x co-ordinate of redraw rectangle, right */
+ uint32_t x1;
+ /** y co-ordinate of redraw rectangle, bottom */
+ uint32_t y1;
+} nsgif_rect_t;
+
+/**
+ * LibNSGIF return codes.
+ */
+typedef enum {
+ /**
+ * Success.
+ */
+ NSGIF_OK,
+
+ /**
+ * Out of memory error.
+ */
+ NSGIF_ERR_OOM,
+
+ /**
+ * GIF source data is invalid, and no frames are recoverable.
+ */
+ NSGIF_ERR_DATA,
+
+ /**
+ * Frame number is not valid.
+ */
+ NSGIF_ERR_BAD_FRAME,
+
+ /**
+ * GIF source data contained an error in a frame.
+ */
+ NSGIF_ERR_DATA_FRAME,
+
+ /**
+ * Unexpected end of GIF source data.
+ */
+ NSGIF_ERR_END_OF_DATA,
+
+ /**
+ * Can't supply more data after calling \ref nsgif_data_complete.
+ */
+ NSGIF_ERR_DATA_COMPLETE,
+
+ /**
+ * The current frame cannot be displayed.
+ */
+ NSGIF_ERR_FRAME_DISPLAY,
+
+ /**
+ * Indicates an animation is complete, and \ref nsgif_reset must be
+ * called to restart the animation from the beginning.
+ */
+ NSGIF_ERR_ANIMATION_END,
+} nsgif_error;
+
+/**
+ * NSGIF \ref nsgif_bitmap_t pixel format.
+ *
+ * All pixel formats are 32 bits per pixel (bpp). The different formats
+ * allow control over the ordering of the colour channels. All colour
+ * channels are 8 bits wide.
+ *
+ * Note that the GIF file format only supports an on/off mask, so the
+ * alpha (A) component (opacity) will always have a value of `0` (fully
+ * transparent) or `255` (fully opaque).
+ */
+typedef enum nsgif_bitmap_fmt {
+ /** Bite-wise RGBA: Byte order: 0xRR, 0xGG, 0xBB, 0xAA. */
+ NSGIF_BITMAP_FMT_R8G8B8A8,
+
+ /** Bite-wise BGRA: Byte order: 0xBB, 0xGG, 0xRR, 0xAA. */
+ NSGIF_BITMAP_FMT_B8G8R8A8,
+
+ /** Bite-wise ARGB: Byte order: 0xAA, 0xRR, 0xGG, 0xBB. */
+ NSGIF_BITMAP_FMT_A8R8G8B8,
+
+ /** Bite-wise ABGR: Byte order: 0xAA, 0xBB, 0xGG, 0xRR. */
+ NSGIF_BITMAP_FMT_A8B8G8R8,
+
+ /**
+ * 32-bit RGBA (0xRRGGBBAA).
+ *
+ * * On little endian host, same as \ref NSGIF_BITMAP_FMT_A8B8G8R8.
+ * * On big endian host, same as \ref NSGIF_BITMAP_FMT_R8G8B8A8.
+ */
+ NSGIF_BITMAP_FMT_RGBA8888,
+
+ /**
+ * 32-bit BGRA (0xBBGGRRAA).
+ *
+ * * On little endian host, same as \ref NSGIF_BITMAP_FMT_A8R8G8B8.
+ * * On big endian host, same as \ref NSGIF_BITMAP_FMT_B8G8R8A8.
+ */
+ NSGIF_BITMAP_FMT_BGRA8888,
+
+ /**
+ * 32-bit ARGB (0xAARRGGBB).
+ *
+ * * On little endian host, same as \ref NSGIF_BITMAP_FMT_B8G8R8A8.
+ * * On big endian host, same as \ref NSGIF_BITMAP_FMT_A8R8G8B8.
+ */
+ NSGIF_BITMAP_FMT_ARGB8888,
+
+ /**
+ * 32-bit BGRA (0xAABBGGRR).
+ *
+ * * On little endian host, same as \ref NSGIF_BITMAP_FMT_R8G8B8A8.
+ * * On big endian host, same as \ref NSGIF_BITMAP_FMT_A8B8G8R8.
+ */
+ NSGIF_BITMAP_FMT_ABGR8888,
+} nsgif_bitmap_fmt_t;
+
+/**
+ * Client bitmap type.
+ *
+ * These are client-created and destroyed, via the \ref nsgif_bitmap_cb_vt
+ * callbacks, but they are owned by a \ref nsgif_t.
+ *
+ * See \ref nsgif_bitmap_fmt for pixel format information.
+ *
+ * The bitmap may have a row_span greater than the bitmap width, but the
+ * difference between row span and width must be a whole number of pixels
+ * (a multiple of four bytes).
+ */
+typedef void nsgif_bitmap_t;
+
+/** Bitmap callbacks function table */
+typedef struct nsgif_bitmap_cb_vt {
+ /**
+ * Callback to create a bitmap with the given dimensions.
+ *
+ * \param[in] width Required bitmap width in pixels.
+ * \param[in] height Required bitmap height in pixels.
+ * \return pointer to client's bitmap structure or NULL on error.
+ */
+ nsgif_bitmap_t* (*create)(int width, int height);
+
+ /**
+ * Callback to free a bitmap.
+ *
+ * \param[in] bitmap The bitmap to destroy.
+ */
+ void (*destroy)(nsgif_bitmap_t *bitmap);
+
+ /**
+ * Get pointer to pixel buffer in a bitmap.
+ *
+ * The pixel buffer must be `(width + N) * height * sizeof(uint32_t)`.
+ * Where `N` is any number greater than or equal to 0.
+ * Note that the returned pointer to uint8_t must be 4-byte aligned.
+ *
+ * \param[in] bitmap The bitmap.
+ * \return pointer to bitmap's pixel buffer.
+ */
+ uint8_t* (*get_buffer)(nsgif_bitmap_t *bitmap);
+
+ /* The following functions are optional. */
+
+ /**
+ * Set whether a bitmap can be plotted opaque.
+ *
+ * \param[in] bitmap The bitmap.
+ * \param[in] opaque Whether the current frame is opaque.
+ */
+ void (*set_opaque)(nsgif_bitmap_t *bitmap, bool opaque);
+
+ /**
+ * Tests whether a bitmap has an opaque alpha channel.
+ *
+ * \param[in] bitmap The bitmap.
+ * \return true if the bitmap is opaque, false otherwise.
+ */
+ bool (*test_opaque)(nsgif_bitmap_t *bitmap);
+
+ /**
+ * Bitmap modified notification.
+ *
+ * \param[in] bitmap The bitmap.
+ */
+ void (*modified)(nsgif_bitmap_t *bitmap);
+
+ /**
+ * Get row span in pixels.
+ *
+ * If this callback is not provided, LibNSGIF will use the width.
+ *
+ * If row span is greater than width, this callback must be provided.
+ *
+ * \param[in] bitmap The bitmap.
+ */
+ uint32_t (*get_rowspan)(nsgif_bitmap_t *bitmap);
+} nsgif_bitmap_cb_vt;
+
+/**
+ * Convert an error code to a string.
+ *
+ * \param[in] err The error code to convert.
+ * \return String representation of given error code.
+ */
+const char *nsgif_strerror(nsgif_error err);
+
+/**
+ * Create the NSGIF object.
+ *
+ * \param[in] bitmap_vt Bitmap operation functions v-table.
+ * \param[in] bitmap_fmt Bitmap pixel format specification.
+ * \param[out] gif_out Return \ref nsgif_t object on success.
+ *
+ * \return NSGIF_OK on success, or appropriate error otherwise.
+ */
+nsgif_error nsgif_create(
+ const nsgif_bitmap_cb_vt *bitmap_vt,
+ nsgif_bitmap_fmt_t bitmap_fmt,
+ nsgif_t **gif_out);
+
+/**
+ * Free a NSGIF object.
+ *
+ * \param[in] gif The NSGIF to free.
+ */
+void nsgif_destroy(nsgif_t *gif);
+
+/**
+ * Scan the source image data.
+ *
+ * This is used to feed the source data into LibNSGIF. This must be called
+ * before calling \ref nsgif_frame_decode.
+ *
+ * It can be called multiple times with, with increasing sizes. If it is called
+ * several times, as more data is available (e.g. slow network fetch) the data
+ * already given to \ref nsgif_data_scan must be provided each time.
+ *
+ * Once all the data has been provided, call \ref nsgif_data_complete.
+ *
+ * For example, if you call \ref nsgif_data_scan with 25 bytes of data, and then
+ * fetch another 10 bytes, you would need to call \ref nsgif_data_scan with a
+ * size of 35 bytes, and the whole 35 bytes must be contiguous memory. It is
+ * safe to `realloc` the source buffer between calls to \ref nsgif_data_scan.
+ * (The actual data pointer is allowed to be different.)
+ *
+ * If an error occurs, all previously scanned frames are retained.
+ *
+ * Note that an error returned from this function is purely informational.
+ * So long as at least one frame is available, you can display frames.
+ *
+ * \param[in] gif The \ref nsgif_t object.
+ * \param[in] size Number of bytes in data.
+ * \param[in] data Raw source GIF data.
+ *
+ * \return NSGIF_OK on success, or appropriate error otherwise.
+ */
+nsgif_error nsgif_data_scan(
+ nsgif_t *gif,
+ size_t size,
+ const uint8_t *data);
+
+/**
+ * Tell libnsgif that all the gif data has been provided.
+ *
+ * Call this after calling \ref nsgif_data_scan with the the entire GIF
+ * source data. You can call \ref nsgif_data_scan multiple times up until
+ * this is called, and after this is called, \ref nsgif_data_scan will
+ * return an error.
+ *
+ * You can decode a GIF before this is called, however, it will fail to
+ * decode any truncated final frame data and will not perform loops when
+ * driven via \ref nsgif_frame_prepare (because it doesn't know if there
+ * will be more frames supplied in future data).
+ *
+ * \param[in] gif The \ref nsgif_t object.
+ */
+void nsgif_data_complete(
+ nsgif_t *gif);
+
+/**
+ * Prepare to show a frame.
+ *
+ * If this is the last frame of an animation with a finite loop count, the
+ * returned `delay_cs` will be \ref NSGIF_INFINITE, indicating that the frame
+ * should be shown forever.
+ *
+ * Note that if \ref nsgif_data_complete has not been called on this gif,
+ * animated GIFs will not loop back to the start. Instead it will return
+ * \ref NSGIF_ERR_END_OF_DATA.
+ *
+ * \param[in] gif The \ref nsgif_t object.
+ * \param[out] area The area in pixels that must be redrawn.
+ * \param[out] delay_cs Time to wait after frame_new before next frame in cs.
+ * \param[out] frame_new The frame to decode.
+ *
+ * \return NSGIF_OK on success, or appropriate error otherwise.
+ */
+nsgif_error nsgif_frame_prepare(
+ nsgif_t *gif,
+ nsgif_rect_t *area,
+ uint32_t *delay_cs,
+ uint32_t *frame_new);
+
+/**
+ * Decodes a GIF frame.
+ *
+ * \param[in] gif The \ref nsgif_t object.
+ * \param[in] frame The frame number to decode.
+ * \param[out] bitmap On success, returns pointer to the client-allocated,
+ * nsgif-owned client bitmap structure.
+ *
+ * \return NSGIF_OK on success, or appropriate error otherwise.
+ */
+nsgif_error nsgif_frame_decode(
+ nsgif_t *gif,
+ uint32_t frame,
+ nsgif_bitmap_t **bitmap);
+
+/**
+ * Reset a GIF animation.
+ *
+ * Some animations are only meant to loop N times, and then show the
+ * final frame forever. This function resets the loop and frame counters,
+ * so that the animation can be replayed without the overhead of recreating
+ * the \ref nsgif_t object and rescanning the raw data.
+ *
+ * \param[in] gif A \ref nsgif_t object.
+ *
+ * \return NSGIF_OK on success, or appropriate error otherwise.
+ */
+nsgif_error nsgif_reset(
+ nsgif_t *gif);
+
+/**
+ * Information about a GIF.
+ */
+typedef struct nsgif_info {
+ /** width of GIF (may increase during decoding) */
+ uint32_t width;
+ /** height of GIF (may increase during decoding) */
+ uint32_t height;
+ /** number of frames decoded */
+ uint32_t frame_count;
+ /** number of times to play animation (zero means loop forever) */
+ int loop_max;
+ /** background colour in same pixel format as \ref nsgif_bitmap_t. */
+ uint32_t background;
+ /** whether the GIF has a global colour table */
+ bool global_palette;
+} nsgif_info_t;
+
+/**
+ * Frame disposal method.
+ *
+ * Clients do not need to know about this, it is provided purely for dumping
+ * raw information about GIF frames.
+ */
+enum nsgif_disposal {
+ NSGIF_DISPOSAL_UNSPECIFIED, /**< No disposal method specified. */
+ NSGIF_DISPOSAL_NONE, /**< Frame remains. */
+ NSGIF_DISPOSAL_RESTORE_BG, /**< Clear frame to background colour. */
+ NSGIF_DISPOSAL_RESTORE_PREV, /**< Restore previous frame. */
+ NSGIF_DISPOSAL_RESTORE_QUIRK, /**< Alias for NSGIF_DISPOSAL_RESTORE_PREV. */
+};
+
+/**
+ * Convert a disposal method to a string.
+ *
+ * \param[in] disposal The disposal method to convert.
+ * \return String representation of given disposal method.
+ */
+const char *nsgif_str_disposal(enum nsgif_disposal disposal);
+
+/**
+ * Information about a GIF frame.
+ */
+typedef struct nsgif_frame_info {
+ /** whether the frame should be displayed/animated */
+ bool display;
+ /** whether the frame may have transparency */
+ bool transparency;
+ /** whether the frame has a local colour table */
+ bool local_palette;
+ /** whether the frame is interlaced */
+ bool interlaced;
+ /** Disposal method for previous frame; affects plotting */
+ uint8_t disposal;
+ /** delay (in cs) before animating the frame */
+ uint32_t delay;
+
+ /** Frame's redraw rectangle. */
+ nsgif_rect_t rect;
+} nsgif_frame_info_t;
+
+/**
+ * Get information about a GIF from an \ref nsgif_t object.
+ *
+ * \param[in] gif The \ref nsgif_t object to get info for.
+ *
+ * \return The gif info, or NULL on error.
+ */
+const nsgif_info_t *nsgif_get_info(const nsgif_t *gif);
+
+/**
+ * Get information about a GIF from an \ref nsgif_t object.
+ *
+ * \param[in] gif The \ref nsgif_t object to get frame info for.
+ * \param[in] frame The frame number to get info for.
+ *
+ * \return The gif frame info, or NULL on error.
+ */
+const nsgif_frame_info_t *nsgif_get_frame_info(
+ const nsgif_t *gif,
+ uint32_t frame);
+
+/**
+ * Get the global colour palette.
+ *
+ * If the GIF has no global colour table, this will return the default
+ * colour palette.
+ *
+ * Colours in same pixel format as \ref nsgif_bitmap_t.
+ *
+ * \param[in] gif The \ref nsgif_t object.
+ * \param[out] table Client buffer to hold the colour table.
+ * \param[out] entries The number of used entries in the colour table.
+ */
+void nsgif_global_palette(
+ const nsgif_t *gif,
+ uint32_t table[NSGIF_MAX_COLOURS],
+ size_t *entries);
+
+/**
+ * Get the local colour palette for a frame.
+ *
+ * Frames may have no local palette. In this case they use the global palette.
+ * This function returns false if the frame has no local palette.
+ *
+ * Colours in same pixel format as \ref nsgif_bitmap_t.
+ *
+ * \param[in] gif The \ref nsgif_t object.
+ * \param[in] frame The frame to get the palette for.
+ * \param[out] table Client buffer to hold the colour table.
+ * \param[out] entries The number of used entries in the colour table.
+ * \return true if a palette is returned, false otherwise.
+ */
+bool nsgif_local_palette(
+ const nsgif_t *gif,
+ uint32_t frame,
+ uint32_t table[NSGIF_MAX_COLOURS],
+ size_t *entries);
+
+/**
+ * Configure handling of small frame delays.
+ *
+ * Historically people created GIFs with a tiny frame delay, however the slow
+ * hardware of the time meant they actually played much slower. As computers
+ * sped up, to prevent animations playing faster than intended, decoders came
+ * to ignore overly small frame delays.
+ *
+ * By default a \ref nsgif_frame_prepare() managed animation will override
+ * frame delays of less than 2 centiseconds with a default frame delay of
+ * 10 centiseconds. This matches the behaviour of web browsers and other
+ * renderers.
+ *
+ * Both the minimum and the default values can be overridden for a given GIF
+ * by the client. To get frame delays exactly as specified by the GIF file, set
+ * `delay_min` to zero.
+ *
+ * Note that this does not affect the frame delay in the frame info
+ * (\ref nsgif_frame_info_t) structure, which will always contain values
+ * specified by the GIF.
+ *
+ * \param[in] gif The \ref nsgif_t object to configure.
+ * \param[in] delay_min The minimum frame delay in centiseconds.
+ * \param[in] delay_default The delay to use if a frame delay is less than
+ * `delay_min`.
+ */
+void nsgif_set_frame_delay_behaviour(
+ nsgif_t *gif,
+ uint16_t delay_min,
+ uint16_t delay_default);
+
+#endif
diff --git a/src/Makefile b/src/Makefile
index cb5d31f..e1e1fa7 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -1,4 +1,4 @@
# Sources
-DIR_SOURCES := libnsgif.c lzw.c
+DIR_SOURCES := gif.c lzw.c
include $(NSBUILD)/Makefile.subdir
diff --git a/src/gif.c b/src/gif.c
new file mode 100644
index 0000000..73814bf
--- /dev/null
+++ b/src/gif.c
@@ -0,0 +1,2076 @@
+/*
+ * Copyright 2004 Richard Wilson <richard.wilson@netsurf-browser.org>
+ * Copyright 2008 Sean Fox <dyntryx@gmail.com>
+ * Copyright 2013-2022 Michael Drake <tlsa@netsurf-browser.org>
+ *
+ * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/
+ * Licenced under the MIT License,
+ * http://www.opensource.org/licenses/mit-license.php
+ */
+
+#include <assert.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+
+#include "lzw.h"
+#include "nsgif.h"
+
+/** Default minimum allowable frame delay in cs. */
+#define NSGIF_FRAME_DELAY_MIN 2
+
+/**
+ * Default frame delay to apply.
+ *
+ * Used when a frame delay lower than the minimum is requested.
+ */
+#define NSGIF_FRAME_DELAY_DEFAULT 10
+
+/** GIF frame data */
+typedef struct nsgif_frame {
+ struct nsgif_frame_info info;
+
+ /** offset (in bytes) to the GIF frame data */
+ size_t frame_offset;
+ /** whether the frame has previously been decoded. */
+ bool decoded;
+ /** whether the frame is totally opaque */
+ bool opaque;
+ /** whether a full image redraw is required */
+ bool redraw_required;
+
+ /** Amount of LZW data found in scan */
+ uint32_t lzw_data_length;
+
+ /** the index designating a transparent pixel */
+ uint32_t transparency_index;
+
+ /** offset to frame colour table */
+ uint32_t colour_table_offset;
+
+ /* Frame flags */
+ uint32_t flags;
+} nsgif_frame;
+
+/** Pixel format: colour component order. */
+struct nsgif_colour_layout {
+ uint8_t r; /**< Byte offset within pixel to red component. */
+ uint8_t g; /**< Byte offset within pixel to green component. */
+ uint8_t b; /**< Byte offset within pixel to blue component. */
+ uint8_t a; /**< Byte offset within pixel to alpha component. */
+};
+
+/** GIF animation data */
+struct nsgif {
+ struct nsgif_info info;
+
+ /** LZW decode context */
+ void *lzw_ctx;
+ /** callbacks for bitmap functions */
+ nsgif_bitmap_cb_vt bitmap;
+ /** decoded frames */
+ nsgif_frame *frames;
+ /** current frame */
+ uint32_t frame;
+ /** current frame decoded to bitmap */
+ uint32_t decoded_frame;
+
+ /** currently decoded image; stored as bitmap from bitmap_create callback */
+ nsgif_bitmap_t *frame_image;
+ /** Row span of frame_image in pixels. */
+ uint32_t rowspan;
+
+ /** Minimum allowable frame delay. */
+ uint16_t delay_min;
+
+ /** Frame delay to apply when delay is less than \ref delay_min. */
+ uint16_t delay_default;
+
+ /** number of animation loops so far */
+ int loop_count;
+
+ /** number of frames partially decoded */
+ uint32_t frame_count_partial;
+
+ /**
+ * Whether all the GIF data has been supplied, or if there may be
+ * more to come.
+ */
+ bool data_complete;
+
+ /** pointer to GIF data */
+ const uint8_t *buf;
+ /** current index into GIF data */
+ size_t buf_pos;
+ /** total number of bytes of GIF data available */
+ size_t buf_len;
+
+ /** current number of frame holders */
+ uint32_t frame_holders;
+ /** background index */
+ uint32_t bg_index;
+ /** image aspect ratio (ignored) */
+ uint32_t aspect_ratio;
+ /** size of global colour table (in entries) */
+ uint32_t colour_table_size;
+
+ /** current colour table */
+ uint32_t *colour_table;
+ /** Client's colour component order. */
+ struct nsgif_colour_layout colour_layout;
+ /** global colour table */
+ uint32_t global_colour_table[NSGIF_MAX_COLOURS];
+ /** local colour table */
+ uint32_t local_colour_table[NSGIF_MAX_COLOURS];
+
+ /** previous frame for NSGIF_FRAME_RESTORE */
+ void *prev_frame;
+ /** previous frame index */
+ uint32_t prev_index;
+};
+
+/**
+ * Helper macro to get number of elements in an array.
+ *
+ * \param[in] _a Array to count elements of.
+ * \return NUlber of elements in array.
+ */
+#define NSGIF_ARRAY_LEN(_a) ((sizeof(_a)) / (sizeof(*_a)))
+
+/**
+ *
+ * \file
+ * \brief GIF image decoder
+ *
+ * The GIF format is thoroughly documented; a full description can be found at
+ * http://www.w3.org/Graphics/GIF/spec-gif89a.txt
+ *
+ * \todo Plain text and comment extensions should be implemented.
+ */
+
+/** Internal flag that the colour table needs to be processed */
+#define NSGIF_PROCESS_COLOURS 0xaa000000
+
+/** Internal flag that a frame is invalid/unprocessed */
+#define NSGIF_FRAME_INVALID UINT32_MAX
+
+/** Transparent colour */
+#define NSGIF_TRANSPARENT_COLOUR 0x00
+
+/** No transparency */
+#define NSGIF_NO_TRANSPARENCY (0xFFFFFFFFu)
+
+/* GIF Flags */
+#define NSGIF_COLOUR_TABLE_MASK 0x80
+#define NSGIF_COLOUR_TABLE_SIZE_MASK 0x07
+#define NSGIF_BLOCK_TERMINATOR 0x00
+#define NSGIF_TRAILER 0x3b
+
+/**
+ * Convert an LZW result code to equivalent GIF result code.
+ *
+ * \param[in] l_res LZW response code.
+ * \return GIF result code.
+ */
+static nsgif_error nsgif__error_from_lzw(lzw_result l_res)
+{
+ static const nsgif_error g_res[] = {
+ [LZW_OK] = NSGIF_OK,
+ [LZW_NO_MEM] = NSGIF_ERR_OOM,
+ [LZW_OK_EOD] = NSGIF_ERR_END_OF_DATA,
+ [LZW_NO_DATA] = NSGIF_ERR_END_OF_DATA,
+ [LZW_EOI_CODE] = NSGIF_ERR_DATA_FRAME,
+ [LZW_BAD_ICODE] = NSGIF_ERR_DATA_FRAME,
+ [LZW_BAD_CODE] = NSGIF_ERR_DATA_FRAME,
+ };
+ assert(l_res != LZW_BAD_PARAM);
+ assert(l_res != LZW_NO_COLOUR);
+ return g_res[l_res];
+}
+
+/**
+ * Updates the sprite memory size
+ *
+ * \param gif The animation context
+ * \param width The width of the sprite
+ * \param height The height of the sprite
+ * \return NSGIF_ERR_OOM for a memory error NSGIF_OK for success
+ */
+static nsgif_error nsgif__initialise_sprite(
+ struct nsgif *gif,
+ uint32_t width,
+ uint32_t height)
+{
+ /* Already allocated? */
+ if (gif->frame_image) {
+ return NSGIF_OK;
+ }
+
+ assert(gif->bitmap.create);
+ gif->frame_image = gif->bitmap.create(width, height);
+ if (gif->frame_image == NULL) {
+ return NSGIF_ERR_OOM;
+ }
+
+ return NSGIF_OK;
+}
+
+/**
+ * Helper to get the rendering bitmap for a gif.
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \return Client pixel buffer for rendering into.
+ */
+static inline uint32_t* nsgif__bitmap_get(
+ struct nsgif *gif)
+{
+ nsgif_error ret;
+
+ /* Make sure we have a buffer to decode to. */
+ ret = nsgif__initialise_sprite(gif, gif->info.width, gif->info.height);
+ if (ret != NSGIF_OK) {
+ return NULL;
+ }
+
+ gif->rowspan = gif->info.width;
+ if (gif->bitmap.get_rowspan) {
+ gif->rowspan = gif->bitmap.get_rowspan(gif->frame_image);
+ }
+
+ /* Get the frame data */
+ assert(gif->bitmap.get_buffer);
+ return (void *)gif->bitmap.get_buffer(gif->frame_image);
+}
+
+/**
+ * Helper to tell the client that their bitmap was modified.
+ *
+ * \param[in] gif The gif object we're decoding.
+ */
+static inline void nsgif__bitmap_modified(
+ const struct nsgif *gif)
+{
+ if (gif->bitmap.modified) {
+ gif->bitmap.modified(gif->frame_image);
+ }
+}
+
+/**
+ * Helper to tell the client that whether the bitmap is opaque.
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \param[in] frame The frame that has been decoded.
+ */
+static inline void nsgif__bitmap_set_opaque(
+ const struct nsgif *gif,
+ const struct nsgif_frame *frame)
+{
+ if (gif->bitmap.set_opaque) {
+ gif->bitmap.set_opaque(
+ gif->frame_image, frame->opaque);
+ }
+}
+
+/**
+ * Helper to get the client to determine if the bitmap is opaque.
+ *
+ * \todo: We don't really need to get the client to do this for us.
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \return true if the bitmap is opaque, false otherwise.
+ */
+static inline bool nsgif__bitmap_get_opaque(
+ const struct nsgif *gif)
+{
+ if (gif->bitmap.test_opaque) {
+ return gif->bitmap.test_opaque(
+ gif->frame_image);
+ }
+
+ return false;
+}
+
+static void nsgif__record_frame(
+ struct nsgif *gif,
+ const uint32_t *bitmap)
+{
+ size_t pixel_bytes = sizeof(*bitmap);
+ size_t height = gif->info.height;
+ size_t width = gif->info.width;
+ uint32_t *prev_frame;
+
+ if (gif->decoded_frame == NSGIF_FRAME_INVALID ||
+ gif->decoded_frame == gif->prev_index) {
+ /* No frame to copy, or already have this frame recorded. */
+ return;
+ }
+
+ bitmap = nsgif__bitmap_get(gif);
+ if (bitmap == NULL) {
+ return;
+ }
+
+ if (gif->prev_frame == NULL) {
+ prev_frame = realloc(gif->prev_frame,
+ width * height * pixel_bytes);
+ if (prev_frame == NULL) {
+ return;
+ }
+ } else {
+ prev_frame = gif->prev_frame;
+ }
+
+ memcpy(prev_frame, bitmap, width * height * pixel_bytes);
+
+ gif->prev_frame = prev_frame;
+ gif->prev_index = gif->decoded_frame;
+}
+
+static nsgif_error nsgif__recover_frame(
+ const struct nsgif *gif,
+ uint32_t *bitmap)
+{
+ const uint32_t *prev_frame = gif->prev_frame;
+ size_t pixel_bytes = sizeof(*bitmap);
+ size_t height = gif->info.height;
+ size_t width = gif->info.width;
+
+ memcpy(bitmap, prev_frame, height * width * pixel_bytes);
+
+ return NSGIF_OK;
+}
+
+/**
+ * Get the next line for GIF decode.
+ *
+ * Note that the step size must be initialised to 24 at the start of the frame
+ * (when y == 0). This is because of the first two passes of the frame have
+ * the same step size of 8, and the step size is used to determine the current
+ * pass.
+ *
+ * \param[in] height Frame height in pixels.
+ * \param[in,out] y Current row, starting from 0, updated on exit.
+ * \param[in,out] step Current step starting with 24, updated on exit.
+ * \return true if there is a row to process, false at the end of the frame.
+ */
+static inline bool nsgif__deinterlace(uint32_t height, uint32_t *y, uint8_t *step)
+{
+ *y += *step & 0xf;
+
+ if (*y < height) return true;
+
+ switch (*step) {
+ case 24: *y = 4; *step = 8; if (*y < height) return true;
+ /* Fall through. */
+ case 8: *y = 2; *step = 4; if (*y < height) return true;
+ /* Fall through. */
+ case 4: *y = 1; *step = 2; if (*y < height) return true;
+ /* Fall through. */
+ default:
+ break;
+ }
+
+ return false;
+}
+
+/**
+ * Get the next line for GIF decode.
+ *
+ * \param[in] interlace Non-zero if the frame is not interlaced.
+ * \param[in] height Frame height in pixels.
+ * \param[in,out] y Current row, starting from 0, updated on exit.
+ * \param[in,out] step Current step starting with 24, updated on exit.
+ * \return true if there is a row to process, false at the end of the frame.
+ */
+static inline bool nsgif__next_row(uint32_t interlace,
+ uint32_t height, uint32_t *y, uint8_t *step)
+{
+ if (!interlace) {
+ return (++*y != height);
+ } else {
+ return nsgif__deinterlace(height, y, step);
+ }
+}
+
+/**
+ * Get any frame clip adjustment for the image extent.
+ *
+ * \param[in] frame_off Frame's X or Y offset.
+ * \param[in] frame_dim Frame width or height.
+ * \param[in] image_ext Image width or height constraint.
+ * \return the amount the frame needs to be clipped to fit the image in given
+ * dimension.
+ */
+static inline uint32_t gif__clip(
+ uint32_t frame_off,
+ uint32_t frame_dim,
+ uint32_t image_ext)
+{
+ uint32_t frame_ext = frame_off + frame_dim;
+
+ if (frame_ext <= image_ext) {
+ return 0;
+ }
+
+ return frame_ext - image_ext;
+}
+
+/**
+ * Perform any jump over decoded data, to accommodate clipped portion of frame.
+ *
+ * \param[in,out] skip Number of pixels of data to jump.
+ * \param[in,out] available Number of pixels of data currently available.
+ * \param[in,out] pos Position in decoded pixel value data.
+ */
+static inline void gif__jump_data(
+ uint32_t *skip,
+ uint32_t *available,
+ const uint8_t **pos)
+{
+ uint32_t jump = (*skip < *available) ? *skip : *available;
+
+ *skip -= jump;
+ *available -= jump;
+ *pos += jump;
+}
+
+static nsgif_error nsgif__decode_complex(
+ struct nsgif *gif,
+ uint32_t width,
+ uint32_t height,
+ uint32_t offset_x,
+ uint32_t offset_y,
+ uint32_t interlace,
+ const uint8_t *data,
+ uint32_t transparency_index,
+ uint32_t *restrict frame_data,
+ uint32_t *restrict colour_table)
+{
+ lzw_result res;
+ nsgif_error ret = NSGIF_OK;
+ uint32_t clip_x = gif__clip(offset_x, width, gif->info.width);
+ uint32_t clip_y = gif__clip(offset_y, height, gif->info.height);
+ const uint8_t *uncompressed;
+ uint32_t available = 0;
+ uint8_t step = 24;
+ uint32_t skip = 0;
+ uint32_t y = 0;
+
+ if (offset_x >= gif->info.width ||
+ offset_y >= gif->info.height) {
+ return NSGIF_OK;
+ }
+
+ width -= clip_x;
+ height -= clip_y;
+
+ if (width == 0 || height == 0) {
+ return NSGIF_OK;
+ }
+
+ /* Initialise the LZW decoding */
+ res = lzw_decode_init(gif->lzw_ctx, data[0],
+ gif->buf, gif->buf_len,
+ data + 1 - gif->buf);
+ if (res != LZW_OK) {
+ return nsgif__error_from_lzw(res);
+ }
+
+ do {
+ uint32_t x;
+ uint32_t *frame_scanline;
+
+ frame_scanline = frame_data + offset_x +
+ (y + offset_y) * gif->rowspan;
+
+ x = width;
+ while (x > 0) {
+ unsigned row_available;
+ while (available == 0) {
+ if (res != LZW_OK) {
+ /* Unexpected end of frame, try to recover */
+ if (res == LZW_OK_EOD ||
+ res == LZW_EOI_CODE) {
+ ret = NSGIF_OK;
+ } else {
+ ret = nsgif__error_from_lzw(res);
+ }
+ return ret;
+ }
+ res = lzw_decode(gif->lzw_ctx,
+ &uncompressed, &available);
+
+ if (available == 0) {
+ return NSGIF_OK;
+ }
+ gif__jump_data(&skip, &available, &uncompressed);
+ }
+
+ row_available = x < available ? x : available;
+ x -= row_available;
+ available -= row_available;
+ if (transparency_index > 0xFF) {
+ while (row_available-- > 0) {
+ *frame_scanline++ =
+ colour_table[*uncompressed++];
+ }
+ } else {
+ while (row_available-- > 0) {
+ register uint32_t colour;
+ colour = *uncompressed++;
+ if (colour != transparency_index) {
+ *frame_scanline =
+ colour_table[colour];
+ }
+ frame_scanline++;
+ }
+ }
+ }
+
+ skip = clip_x;
+ gif__jump_data(&skip, &available, &uncompressed);
+ } while (nsgif__next_row(interlace, height, &y, &step));
+
+ return ret;
+}
+
+static nsgif_error nsgif__decode_simple(
+ struct nsgif *gif,
+ uint32_t height,
+ uint32_t offset_y,
+ const uint8_t *data,
+ uint32_t transparency_index,
+ uint32_t *restrict frame_data,
+ uint32_t *restrict colour_table)
+{
+ uint32_t pixels;
+ uint32_t written = 0;
+ nsgif_error ret = NSGIF_OK;
+ lzw_result res;
+
+ if (offset_y >= gif->info.height) {
+ return NSGIF_OK;
+ }
+
+ height -= gif__clip(offset_y, height, gif->info.height);
+
+ if (height == 0) {
+ return NSGIF_OK;
+ }
+
+ /* Initialise the LZW decoding */
+ res = lzw_decode_init_map(gif->lzw_ctx, data[0],
+ transparency_index, colour_table,
+ gif->buf, gif->buf_len,
+ data + 1 - gif->buf);
+ if (res != LZW_OK) {
+ return nsgif__error_from_lzw(res);
+ }
+
+ frame_data += (offset_y * gif->info.width);
+ pixels = gif->info.width * height;
+
+ while (pixels > 0) {
+ res = lzw_decode_map(gif->lzw_ctx,
+ frame_data, pixels, &written);
+ pixels -= written;
+ frame_data += written;
+ if (res != LZW_OK) {
+ /* Unexpected end of frame, try to recover */
+ if (res == LZW_OK_EOD || res == LZW_EOI_CODE) {
+ ret = NSGIF_OK;
+ } else {
+ ret = nsgif__error_from_lzw(res);
+ }
+ break;
+ }
+ }
+
+ if (pixels == 0) {
+ ret = NSGIF_OK;
+ }
+
+ return ret;
+}
+
+static inline nsgif_error nsgif__decode(
+ struct nsgif *gif,
+ struct nsgif_frame *frame,
+ const uint8_t *data,
+ uint32_t *restrict frame_data)
+{
+ nsgif_error ret;
+ uint32_t width = frame->info.rect.x1 - frame->info.rect.x0;
+ uint32_t height = frame->info.rect.y1 - frame->info.rect.y0;
+ uint32_t offset_x = frame->info.rect.x0;
+ uint32_t offset_y = frame->info.rect.y0;
+ uint32_t transparency_index = frame->transparency_index;
+ uint32_t *restrict colour_table = gif->colour_table;
+
+ if (frame->info.interlaced == false && offset_x == 0 &&
+ width == gif->info.width &&
+ width == gif->rowspan) {
+ ret = nsgif__decode_simple(gif, height, offset_y,
+ data, transparency_index,
+ frame_data, colour_table);
+ } else {
+ ret = nsgif__decode_complex(gif, width, height,
+ offset_x, offset_y, frame->info.interlaced,
+ data, transparency_index,
+ frame_data, colour_table);
+ }
+
+ if (gif->data_complete && ret == NSGIF_ERR_END_OF_DATA) {
+ /* This is all the data there is, so make do. */
+ ret = NSGIF_OK;
+ }
+
+ return ret;
+}
+
+/**
+ * Restore a GIF to the background colour.
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \param[in] frame The frame to clear, or NULL.
+ * \param[in] bitmap The bitmap to clear the frame in.
+ */
+static void nsgif__restore_bg(
+ struct nsgif *gif,
+ struct nsgif_frame *frame,
+ uint32_t *bitmap)
+{
+ size_t pixel_bytes = sizeof(*bitmap);
+
+ if (frame == NULL) {
+ size_t width = gif->info.width;
+ size_t height = gif->info.height;
+
+ memset(bitmap, NSGIF_TRANSPARENT_COLOUR,
+ width * height * pixel_bytes);
+ } else {
+ uint32_t width = frame->info.rect.x1 - frame->info.rect.x0;
+ uint32_t height = frame->info.rect.y1 - frame->info.rect.y0;
+ uint32_t offset_x = frame->info.rect.x0;
+ uint32_t offset_y = frame->info.rect.y0;
+
+ if (frame->info.display == false ||
+ frame->info.rect.x0 >= gif->info.width ||
+ frame->info.rect.y0 >= gif->info.height) {
+ return;
+ }
+
+ width -= gif__clip(offset_x, width, gif->info.width);
+ height -= gif__clip(offset_y, height, gif->info.height);
+
+ if (frame->info.transparency) {
+ for (uint32_t y = 0; y < height; y++) {
+ uint32_t *scanline = bitmap + offset_x +
+ (offset_y + y) * gif->info.width;
+ memset(scanline, NSGIF_TRANSPARENT_COLOUR,
+ width * pixel_bytes);
+ }
+ } else {
+ for (uint32_t y = 0; y < height; y++) {
+ uint32_t *scanline = bitmap + offset_x +
+ (offset_y + y) * gif->info.width;
+ for (uint32_t x = 0; x < width; x++) {
+ scanline[x] = gif->info.background;
+ }
+ }
+ }
+ }
+}
+
+static nsgif_error nsgif__update_bitmap(
+ struct nsgif *gif,
+ struct nsgif_frame *frame,
+ const uint8_t *data,
+ uint32_t frame_idx)
+{
+ nsgif_error ret;
+ uint32_t *bitmap;
+
+ gif->decoded_frame = frame_idx;
+
+ bitmap = nsgif__bitmap_get(gif);
+ if (bitmap == NULL) {
+ return NSGIF_ERR_OOM;
+ }
+
+ /* Handle any bitmap clearing/restoration required before decoding this
+ * frame. */
+ if (frame_idx == 0 || gif->decoded_frame == NSGIF_FRAME_INVALID) {
+ nsgif__restore_bg(gif, NULL, bitmap);
+
+ } else {
+ struct nsgif_frame *prev = &gif->frames[frame_idx - 1];
+
+ if (prev->info.disposal == NSGIF_DISPOSAL_RESTORE_BG) {
+ nsgif__restore_bg(gif, prev, bitmap);
+
+ } else if (prev->info.disposal == NSGIF_DISPOSAL_RESTORE_PREV) {
+ ret = nsgif__recover_frame(gif, bitmap);
+ if (ret != NSGIF_OK) {
+ nsgif__restore_bg(gif, prev, bitmap);
+ }
+ }
+ }
+
+ if (frame->info.disposal == NSGIF_DISPOSAL_RESTORE_PREV) {
+ /* Store the previous frame for later restoration */
+ nsgif__record_frame(gif, bitmap);
+ }
+
+ ret = nsgif__decode(gif, frame, data, bitmap);
+
+ nsgif__bitmap_modified(gif);
+
+ if (!frame->decoded) {
+ frame->opaque = nsgif__bitmap_get_opaque(gif);
+ frame->decoded = true;
+ }
+ nsgif__bitmap_set_opaque(gif, frame);
+
+ return ret;
+}
+
+/**
+ * Parse the graphic control extension
+ *
+ * \param[in] frame The gif frame object we're decoding.
+ * \param[in] data The data to decode.
+ * \param[in] len Byte length of data.
+ * \return NSGIF_ERR_END_OF_DATA if more data is needed,
+ * NSGIF_OK for success.
+ */
+static nsgif_error nsgif__parse_extension_graphic_control(
+ struct nsgif_frame *frame,
+ const uint8_t *data,
+ size_t len)
+{
+ enum {
+ GIF_MASK_TRANSPARENCY = 0x01,
+ GIF_MASK_DISPOSAL = 0x1c,
+ };
+
+ /* 6-byte Graphic Control Extension is:
+ *
+ * +0 CHAR Graphic Control Label
+ * +1 CHAR Block Size
+ * +2 CHAR __Packed Fields__
+ * 3BITS Reserved
+ * 3BITS Disposal Method
+ * 1BIT User Input Flag
+ * 1BIT Transparent Color Flag
+ * +3 SHORT Delay Time
+ * +5 CHAR Transparent Color Index
+ */
+ if (len < 6) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ frame->info.delay = data[3] | (data[4] << 8);
+
+ if (data[2] & GIF_MASK_TRANSPARENCY) {
+ frame->info.transparency = true;
+ frame->transparency_index = data[5];
+ }
+
+ frame->info.disposal = ((data[2] & GIF_MASK_DISPOSAL) >> 2);
+ /* I have encountered documentation and GIFs in the
+ * wild that use 0x04 to restore the previous frame,
+ * rather than the officially documented 0x03. I
+ * believe some (older?) software may even actually
+ * export this way. We handle this as a type of
+ * "quirks" mode. */
+ if (frame->info.disposal == NSGIF_DISPOSAL_RESTORE_QUIRK) {
+ frame->info.disposal = NSGIF_DISPOSAL_RESTORE_PREV;
+ }
+
+ /* if we are clearing the background then we need to
+ * redraw enough to cover the previous frame too. */
+ frame->redraw_required =
+ frame->info.disposal == NSGIF_DISPOSAL_RESTORE_BG ||
+ frame->info.disposal == NSGIF_DISPOSAL_RESTORE_PREV;
+
+ return NSGIF_OK;
+}
+
+/**
+ * Check an app ext identifier and authentication code for loop count extension.
+ *
+ * \param[in] data The data to decode.
+ * \param[in] len Byte length of data.
+ * \return true if extension is a loop count extension.
+ */
+static bool nsgif__app_ext_is_loop_count(
+ const uint8_t *data,
+ size_t len)
+{
+ enum {
+ EXT_LOOP_COUNT_BLOCK_SIZE = 0x0b,
+ };
+
+ assert(len > 13);
+ (void)(len);
+
+ if (data[1] == EXT_LOOP_COUNT_BLOCK_SIZE) {
+ if (strncmp((const char *)data + 2, "NETSCAPE2.0", 11) == 0 ||
+ strncmp((const char *)data + 2, "ANIMEXTS1.0", 11) == 0) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Parse the application extension
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \param[in] data The data to decode.
+ * \param[in] len Byte length of data.
+ * \return NSGIF_ERR_END_OF_DATA if more data is needed,
+ * NSGIF_OK for success.
+ */
+static nsgif_error nsgif__parse_extension_application(
+ struct nsgif *gif,
+ const uint8_t *data,
+ size_t len)
+{
+ /* 14-byte+ Application Extension is:
+ *
+ * +0 CHAR Application Extension Label
+ * +1 CHAR Block Size
+ * +2 8CHARS Application Identifier
+ * +10 3CHARS Appl. Authentication Code
+ * +13 1-256 Application Data (Data sub-blocks)
+ */
+ if (len < 17) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ if (nsgif__app_ext_is_loop_count(data, len)) {
+ enum {
+ EXT_LOOP_COUNT_SUB_BLOCK_SIZE = 0x03,
+ EXT_LOOP_COUNT_SUB_BLOCK_ID = 0x01,
+ };
+ if ((data[13] == EXT_LOOP_COUNT_SUB_BLOCK_SIZE) &&
+ (data[14] == EXT_LOOP_COUNT_SUB_BLOCK_ID)) {
+ gif->info.loop_max = data[15] | (data[16] << 8);
+
+ /* The value in the source data means repeat N times
+ * after the first implied play. A value of zero has
+ * the special meaning of loop forever. (The only way
+ * to play the animation once is not to have this
+ * extension at all. */
+ if (gif->info.loop_max > 0) {
+ gif->info.loop_max++;
+ }
+ }
+ }
+
+ return NSGIF_OK;
+}
+
+/**
+ * Parse the frame's extensions
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \param[in] frame The frame to parse extensions for.
+ * \param[in] pos Current position in data, updated on exit.
+ * \param[in] decode Whether to decode or skip over the extension.
+ * \return NSGIF_ERR_END_OF_DATA if more data is needed,
+ * NSGIF_OK for success.
+ */
+static nsgif_error nsgif__parse_frame_extensions(
+ struct nsgif *gif,
+ struct nsgif_frame *frame,
+ const uint8_t **pos,
+ bool decode)
+{
+ enum {
+ GIF_EXT_INTRODUCER = 0x21,
+ GIF_EXT_GRAPHIC_CONTROL = 0xf9,
+ GIF_EXT_COMMENT = 0xfe,
+ GIF_EXT_PLAIN_TEXT = 0x01,
+ GIF_EXT_APPLICATION = 0xff,
+ };
+ const uint8_t *nsgif_data = *pos;
+ const uint8_t *nsgif_end = gif->buf + gif->buf_len;
+ int nsgif_bytes = nsgif_end - nsgif_data;
+
+ /* Initialise the extensions */
+ while (nsgif_bytes > 0 && nsgif_data[0] == GIF_EXT_INTRODUCER) {
+ bool block_step = true;
+ nsgif_error ret;
+
+ nsgif_data++;
+ nsgif_bytes--;
+
+ if (nsgif_bytes == 0) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ /* Switch on extension label */
+ switch (nsgif_data[0]) {
+ case GIF_EXT_GRAPHIC_CONTROL:
+ if (decode) {
+ ret = nsgif__parse_extension_graphic_control(
+ frame,
+ nsgif_data,
+ nsgif_bytes);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+ }
+ break;
+
+ case GIF_EXT_APPLICATION:
+ if (decode) {
+ ret = nsgif__parse_extension_application(
+ gif, nsgif_data, nsgif_bytes);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+ }
+ break;
+
+ case GIF_EXT_COMMENT:
+ /* Move the pointer to the first data sub-block Skip 1
+ * byte for the extension label. */
+ ++nsgif_data;
+ block_step = false;
+ break;
+
+ default:
+ break;
+ }
+
+ if (block_step) {
+ /* Move the pointer to the first data sub-block Skip 2
+ * bytes for the extension label and size fields Skip
+ * the extension size itself
+ */
+ if (nsgif_bytes < 2) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+ nsgif_data += 2 + nsgif_data[1];
+ }
+
+ /* Repeatedly skip blocks until we get a zero block or run out
+ * of data. This data is ignored by this gif decoder. */
+ while (nsgif_data < nsgif_end && nsgif_data[0] != NSGIF_BLOCK_TERMINATOR) {
+ nsgif_data += nsgif_data[0] + 1;
+ if (nsgif_data >= nsgif_end) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+ }
+ nsgif_data++;
+ nsgif_bytes = nsgif_end - nsgif_data;
+ }
+
+ if (nsgif_data > nsgif_end) {
+ nsgif_data = nsgif_end;
+ }
+
+ /* Set buffer position and return */
+ *pos = nsgif_data;
+ return NSGIF_OK;
+}
+
+/**
+ * Parse a GIF Image Descriptor.
+ *
+ * The format is:
+ *
+ * +0 CHAR Image Separator (0x2c)
+ * +1 SHORT Image Left Position
+ * +3 SHORT Image Top Position
+ * +5 SHORT Width
+ * +7 SHORT Height
+ * +9 CHAR __Packed Fields__
+ * 1BIT Local Colour Table Flag
+ * 1BIT Interlace Flag
+ * 1BIT Sort Flag
+ * 2BITS Reserved
+ * 3BITS Size of Local Colour Table
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \param[in] frame The frame to parse an image descriptor for.
+ * \param[in] pos Current position in data, updated on exit.
+ * \param[in] decode Whether to decode the image descriptor.
+ * \return NSGIF_OK on success, appropriate error otherwise.
+ */
+static nsgif_error nsgif__parse_image_descriptor(
+ struct nsgif *gif,
+ struct nsgif_frame *frame,
+ const uint8_t **pos,
+ bool decode)
+{
+ const uint8_t *data = *pos;
+ size_t len = gif->buf + gif->buf_len - data;
+ enum {
+ NSGIF_IMAGE_DESCRIPTOR_LEN = 10u,
+ NSGIF_IMAGE_SEPARATOR = 0x2Cu,
+ NSGIF_MASK_INTERLACE = 0x40u,
+ };
+
+ assert(gif != NULL);
+ assert(frame != NULL);
+
+ if (len < NSGIF_IMAGE_DESCRIPTOR_LEN) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ if (decode) {
+ uint32_t x, y, w, h;
+
+ if (data[0] != NSGIF_IMAGE_SEPARATOR) {
+ return NSGIF_ERR_DATA_FRAME;
+ }
+
+ x = data[1] | (data[2] << 8);
+ y = data[3] | (data[4] << 8);
+ w = data[5] | (data[6] << 8);
+ h = data[7] | (data[8] << 8);
+ frame->flags = data[9];
+
+ frame->info.rect.x0 = x;
+ frame->info.rect.y0 = y;
+ frame->info.rect.x1 = x + w;
+ frame->info.rect.y1 = y + h;
+
+ frame->info.interlaced = frame->flags & NSGIF_MASK_INTERLACE;
+
+ /* Allow first frame to grow image dimensions. */
+ if (gif->info.frame_count == 0) {
+ if (x + w > gif->info.width) {
+ gif->info.width = x + w;
+ }
+ if (y + h > gif->info.height) {
+ gif->info.height = y + h;
+ }
+ }
+ }
+
+ *pos += NSGIF_IMAGE_DESCRIPTOR_LEN;
+ return NSGIF_OK;
+}
+
+/**
+ * Extract a GIF colour table into a LibNSGIF colour table buffer.
+ *
+ * \param[in] colour_table The colour table to populate.
+ * \param[in] layout la.
+ * \param[in] colour_table_entries The number of colour table entries.
+ * \param[in] data Raw colour table data.
+ */
+static void nsgif__colour_table_decode(
+ uint32_t colour_table[NSGIF_MAX_COLOURS],
+ const struct nsgif_colour_layout *layout,
+ size_t colour_table_entries,
+ const uint8_t *data)
+{
+ uint8_t *entry = (uint8_t *)colour_table;
+
+ while (colour_table_entries--) {
+ /* Gif colour map contents are r,g,b.
+ *
+ * We want to pack them bytewise into the colour table,
+ * according to the client colour layout.
+ */
+
+ entry[layout->r] = *data++;
+ entry[layout->g] = *data++;
+ entry[layout->b] = *data++;
+ entry[layout->a] = 0xff;
+
+ entry += sizeof(uint32_t);
+ }
+}
+
+/**
+ * Extract a GIF colour table into a LibNSGIF colour table buffer.
+ *
+ * \param[in] colour_table The colour table to populate.
+ * \param[in] layout The target pixel format to decode to.
+ * \param[in] colour_table_entries The number of colour table entries.
+ * \param[in] data Current position in data.
+ * \param[in] data_len The available length of `data`.
+ * \param[out] used Number of colour table bytes read.
+ * \param[in] decode Whether to decode the colour table.
+ * \return NSGIF_OK on success, appropriate error otherwise.
+ */
+static inline nsgif_error nsgif__colour_table_extract(
+ uint32_t colour_table[NSGIF_MAX_COLOURS],
+ const struct nsgif_colour_layout *layout,
+ size_t colour_table_entries,
+ const uint8_t *data,
+ size_t data_len,
+ size_t *used,
+ bool decode)
+{
+ if (data_len < colour_table_entries * 3) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ if (decode) {
+ nsgif__colour_table_decode(colour_table, layout,
+ colour_table_entries, data);
+ }
+
+ *used = colour_table_entries * 3;
+ return NSGIF_OK;
+}
+
+/**
+ * Get a frame's colour table.
+ *
+ * Sets up gif->colour_table for the frame.
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \param[in] frame The frame to get the colour table for.
+ * \param[in] pos Current position in data, updated on exit.
+ * \param[in] decode Whether to decode the colour table.
+ * \return NSGIF_OK on success, appropriate error otherwise.
+ */
+static nsgif_error nsgif__parse_colour_table(
+ struct nsgif *gif,
+ struct nsgif_frame *frame,
+ const uint8_t **pos,
+ bool decode)
+{
+ nsgif_error ret;
+ const uint8_t *data = *pos;
+ size_t len = gif->buf + gif->buf_len - data;
+ size_t used_bytes;
+
+ assert(gif != NULL);
+ assert(frame != NULL);
+
+ if ((frame->flags & NSGIF_COLOUR_TABLE_MASK) == 0) {
+ gif->colour_table = gif->global_colour_table;
+ return NSGIF_OK;
+ }
+
+ if (decode == false) {
+ frame->colour_table_offset = *pos - gif->buf;
+ }
+
+ ret = nsgif__colour_table_extract(
+ gif->local_colour_table, &gif->colour_layout,
+ 2 << (frame->flags & NSGIF_COLOUR_TABLE_SIZE_MASK),
+ data, len, &used_bytes, decode);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+ *pos += used_bytes;
+
+ if (decode) {
+ gif->colour_table = gif->local_colour_table;
+ } else {
+ frame->info.local_palette = true;
+ }
+
+ return NSGIF_OK;
+}
+
+/**
+ * Parse the image data for a gif frame.
+ *
+ * Sets up gif->colour_table for the frame.
+ *
+ * \param[in] gif The gif object we're decoding.
+ * \param[in] frame The frame to parse image data for.
+ * \param[in] pos Current position in data, updated on exit.
+ * \param[in] decode Whether to decode the image data.
+ * \return NSGIF_OK on success, appropriate error otherwise.
+ */
+static nsgif_error nsgif__parse_image_data(
+ struct nsgif *gif,
+ struct nsgif_frame *frame,
+ const uint8_t **pos,
+ bool decode)
+{
+ const uint8_t *data = *pos;
+ size_t len = gif->buf + gif->buf_len - data;
+ uint32_t frame_idx = frame - gif->frames;
+ uint8_t minimum_code_size;
+ nsgif_error ret;
+
+ assert(gif != NULL);
+ assert(frame != NULL);
+
+ if (!decode) {
+ gif->frame_count_partial = frame_idx + 1;
+ }
+
+ /* Ensure sufficient data remains. A gif trailer or a minimum lzw code
+ * followed by a gif trailer is treated as OK, although without any
+ * image data. */
+ switch (len) {
+ default: if (data[0] == NSGIF_TRAILER) return NSGIF_OK;
+ break;
+ case 2: if (data[1] == NSGIF_TRAILER) return NSGIF_OK;
+ /* Fall through. */
+ case 1: if (data[0] == NSGIF_TRAILER) return NSGIF_OK;
+ /* Fall through. */
+ case 0: return NSGIF_ERR_END_OF_DATA;
+ }
+
+ minimum_code_size = data[0];
+ if (minimum_code_size >= LZW_CODE_MAX) {
+ return NSGIF_ERR_DATA_FRAME;
+ }
+
+ if (decode) {
+ ret = nsgif__update_bitmap(gif, frame, data, frame_idx);
+ } else {
+ uint32_t block_size = 0;
+
+ /* Skip the minimum code size. */
+ data++;
+ len--;
+
+ while (block_size != 1) {
+ if (len < 1) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+ block_size = data[0] + 1;
+ /* Check if the frame data runs off the end of the file */
+ if (block_size > len) {
+ frame->lzw_data_length += len;
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ len -= block_size;
+ data += block_size;
+ frame->lzw_data_length += block_size;
+ }
+
+ *pos = data;
+
+ gif->info.frame_count = frame_idx + 1;
+ gif->frames[frame_idx].info.display = true;
+
+ return NSGIF_OK;
+ }
+
+ return ret;
+}
+
+static struct nsgif_frame *nsgif__get_frame(
+ struct nsgif *gif,
+ uint32_t frame_idx)
+{
+ struct nsgif_frame *frame;
+
+ if (gif->frame_holders > frame_idx) {
+ frame = &gif->frames[frame_idx];
+ } else {
+ /* Allocate more memory */
+ size_t count = frame_idx + 1;
+ struct nsgif_frame *temp;
+
+ temp = realloc(gif->frames, count * sizeof(*frame));
+ if (temp == NULL) {
+ return NULL;
+ }
+ gif->frames = temp;
+ gif->frame_holders = count;
+
+ frame = &gif->frames[frame_idx];
+
+ frame->info.local_palette = false;
+ frame->info.transparency = false;
+ frame->info.display = false;
+ frame->info.disposal = 0;
+ frame->info.delay = 10;
+
+ frame->transparency_index = NSGIF_NO_TRANSPARENCY;
+ frame->frame_offset = gif->buf_pos;
+ frame->redraw_required = false;
+ frame->lzw_data_length = 0;
+ frame->decoded = false;
+ }
+
+ return frame;
+}
+
+/**
+ * Attempts to initialise the next frame
+ *
+ * \param[in] gif The animation context
+ * \param[in] frame_idx The frame number to decode.
+ * \param[in] decode Whether to decode the graphical image data.
+ * \return NSGIF_OK on success, appropriate error otherwise.
+*/
+static nsgif_error nsgif__process_frame(
+ struct nsgif *gif,
+ uint32_t frame_idx,
+ bool decode)
+{
+ nsgif_error ret;
+ const uint8_t *pos;
+ const uint8_t *end;
+ struct nsgif_frame *frame;
+
+ frame = nsgif__get_frame(gif, frame_idx);
+ if (frame == NULL) {
+ return NSGIF_ERR_OOM;
+ }
+
+ end = gif->buf + gif->buf_len;
+
+ if (decode) {
+ pos = gif->buf + frame->frame_offset;
+
+ /* Ensure this frame is supposed to be decoded */
+ if (frame->info.display == false) {
+ return NSGIF_OK;
+ }
+
+ /* Ensure the frame is in range to decode */
+ if (frame_idx > gif->frame_count_partial) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ /* Done if frame is already decoded */
+ if (frame_idx == gif->decoded_frame) {
+ return NSGIF_OK;
+ }
+ } else {
+ pos = gif->buf + gif->buf_pos;
+
+ /* Check if we've finished */
+ if (pos < end && pos[0] == NSGIF_TRAILER) {
+ return NSGIF_OK;
+ }
+ }
+
+ ret = nsgif__parse_frame_extensions(gif, frame, &pos, !decode);
+ if (ret != NSGIF_OK) {
+ goto cleanup;
+ }
+
+ ret = nsgif__parse_image_descriptor(gif, frame, &pos, !decode);
+ if (ret != NSGIF_OK) {
+ goto cleanup;
+ }
+
+ ret = nsgif__parse_colour_table(gif, frame, &pos, decode);
+ if (ret != NSGIF_OK) {
+ goto cleanup;
+ }
+
+ ret = nsgif__parse_image_data(gif, frame, &pos, decode);
+ if (ret != NSGIF_OK) {
+ goto cleanup;
+ }
+
+cleanup:
+ if (!decode) {
+ gif->buf_pos = pos - gif->buf;
+ }
+
+ return ret;
+}
+
+/* exported function documented in nsgif.h */
+void nsgif_destroy(nsgif_t *gif)
+{
+ if (gif == NULL) {
+ return;
+ }
+
+ /* Release all our memory blocks */
+ if (gif->frame_image) {
+ assert(gif->bitmap.destroy);
+ gif->bitmap.destroy(gif->frame_image);
+ gif->frame_image = NULL;
+ }
+
+ free(gif->frames);
+ gif->frames = NULL;
+
+ free(gif->prev_frame);
+ gif->prev_frame = NULL;
+
+ lzw_context_destroy(gif->lzw_ctx);
+ gif->lzw_ctx = NULL;
+
+ free(gif);
+}
+
+/**
+ * Check whether the host is little endian.
+ *
+ * Checks whether least significant bit is in the first byte of a `uint16_t`.
+ *
+ * \return true if host is little endian.
+ */
+static inline bool nsgif__host_is_little_endian(void)
+{
+ const uint16_t test = 1;
+
+ return ((const uint8_t *) &test)[0];
+}
+
+static struct nsgif_colour_layout nsgif__bitmap_fmt_to_colour_layout(
+ nsgif_bitmap_fmt_t bitmap_fmt)
+{
+ bool le = nsgif__host_is_little_endian();
+
+ /* Map endian-dependant formats to byte-wise format for the host. */
+ switch (bitmap_fmt) {
+ case NSGIF_BITMAP_FMT_RGBA8888:
+ bitmap_fmt = (le) ? NSGIF_BITMAP_FMT_A8B8G8R8
+ : NSGIF_BITMAP_FMT_R8G8B8A8;
+ break;
+ case NSGIF_BITMAP_FMT_BGRA8888:
+ bitmap_fmt = (le) ? NSGIF_BITMAP_FMT_A8R8G8B8
+ : NSGIF_BITMAP_FMT_B8G8R8A8;
+ break;
+ case NSGIF_BITMAP_FMT_ARGB8888:
+ bitmap_fmt = (le) ? NSGIF_BITMAP_FMT_B8G8R8A8
+ : NSGIF_BITMAP_FMT_A8R8G8B8;
+ break;
+ case NSGIF_BITMAP_FMT_ABGR8888:
+ bitmap_fmt = (le) ? NSGIF_BITMAP_FMT_R8G8B8A8
+ : NSGIF_BITMAP_FMT_A8B8G8R8;
+ break;
+ default:
+ break;
+ }
+
+ /* Set up colour component order for bitmap format. */
+ switch (bitmap_fmt) {
+ default:
+ /* Fall through. */
+ case NSGIF_BITMAP_FMT_R8G8B8A8:
+ return (struct nsgif_colour_layout) {
+ .r = 0,
+ .g = 1,
+ .b = 2,
+ .a = 3,
+ };
+
+ case NSGIF_BITMAP_FMT_B8G8R8A8:
+ return (struct nsgif_colour_layout) {
+ .b = 0,
+ .g = 1,
+ .r = 2,
+ .a = 3,
+ };
+
+ case NSGIF_BITMAP_FMT_A8R8G8B8:
+ return (struct nsgif_colour_layout) {
+ .a = 0,
+ .r = 1,
+ .g = 2,
+ .b = 3,
+ };
+
+ case NSGIF_BITMAP_FMT_A8B8G8R8:
+ return (struct nsgif_colour_layout) {
+ .a = 0,
+ .b = 1,
+ .g = 2,
+ .r = 3,
+ };
+ }
+}
+
+/* exported function documented in nsgif.h */
+nsgif_error nsgif_create(
+ const nsgif_bitmap_cb_vt *bitmap_vt,
+ nsgif_bitmap_fmt_t bitmap_fmt,
+ nsgif_t **gif_out)
+{
+ nsgif_t *gif;
+
+ gif = calloc(1, sizeof(*gif));
+ if (gif == NULL) {
+ return NSGIF_ERR_OOM;
+ }
+
+ gif->bitmap = *bitmap_vt;
+ gif->decoded_frame = NSGIF_FRAME_INVALID;
+ gif->prev_index = NSGIF_FRAME_INVALID;
+
+ gif->delay_min = NSGIF_FRAME_DELAY_MIN;
+ gif->delay_default = NSGIF_FRAME_DELAY_DEFAULT;
+
+ gif->colour_layout = nsgif__bitmap_fmt_to_colour_layout(bitmap_fmt);
+
+ *gif_out = gif;
+ return NSGIF_OK;
+}
+
+/* exported function documented in nsgif.h */
+void nsgif_set_frame_delay_behaviour(
+ nsgif_t *gif,
+ uint16_t delay_min,
+ uint16_t delay_default)
+{
+ gif->delay_min = delay_min;
+ gif->delay_default = delay_default;
+}
+
+/**
+ * Read GIF header.
+ *
+ * 6-byte GIF file header is:
+ *
+ * +0 3CHARS Signature ('GIF')
+ * +3 3CHARS Version ('87a' or '89a')
+ *
+ * \param[in] gif The GIF object we're decoding.
+ * \param[in,out] pos The current buffer position, updated on success.
+ * \param[in] strict Whether to require a known GIF version.
+ * \return NSGIF_OK on success, appropriate error otherwise.
+ */
+static nsgif_error nsgif__parse_header(
+ struct nsgif *gif,
+ const uint8_t **pos,
+ bool strict)
+{
+ const uint8_t *data = *pos;
+ size_t len = gif->buf + gif->buf_len - data;
+
+ if (len < 6) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ if (strncmp((const char *) data, "GIF", 3) != 0) {
+ return NSGIF_ERR_DATA;
+ }
+ data += 3;
+
+ if (strict == true) {
+ if ((strncmp((const char *) data, "87a", 3) != 0) &&
+ (strncmp((const char *) data, "89a", 3) != 0)) {
+ return NSGIF_ERR_DATA;
+ }
+ }
+ data += 3;
+
+ *pos = data;
+ return NSGIF_OK;
+}
+
+/**
+ * Read Logical Screen Descriptor.
+ *
+ * 7-byte Logical Screen Descriptor is:
+ *
+ * +0 SHORT Logical Screen Width
+ * +2 SHORT Logical Screen Height
+ * +4 CHAR __Packed Fields__
+ * 1BIT Global Colour Table Flag
+ * 3BITS Colour Resolution
+ * 1BIT Sort Flag
+ * 3BITS Size of Global Colour Table
+ * +5 CHAR Background Colour Index
+ * +6 CHAR Pixel Aspect Ratio
+ *
+ * \param[in] gif The GIF object we're decoding.
+ * \param[in,out] pos The current buffer position, updated on success.
+ * \return NSGIF_OK on success, appropriate error otherwise.
+ */
+static nsgif_error nsgif__parse_logical_screen_descriptor(
+ struct nsgif *gif,
+ const uint8_t **pos)
+{
+ const uint8_t *data = *pos;
+ size_t len = gif->buf + gif->buf_len - data;
+
+ if (len < 7) {
+ return NSGIF_ERR_END_OF_DATA;
+ }
+
+ gif->info.width = data[0] | (data[1] << 8);
+ gif->info.height = data[2] | (data[3] << 8);
+ gif->info.global_palette = data[4] & NSGIF_COLOUR_TABLE_MASK;
+ gif->colour_table_size = 2 << (data[4] & NSGIF_COLOUR_TABLE_SIZE_MASK);
+ gif->bg_index = data[5];
+ gif->aspect_ratio = data[6];
+ gif->info.loop_max = 1;
+
+ *pos += 7;
+ return NSGIF_OK;
+}
+
+/* exported function documented in nsgif.h */
+nsgif_error nsgif_data_scan(
+ nsgif_t *gif,
+ size_t size,
+ const uint8_t *data)
+{
+ const uint8_t *nsgif_data;
+ nsgif_error ret;
+ uint32_t frames;
+
+ if (gif->data_complete) {
+ return NSGIF_ERR_DATA_COMPLETE;
+ }
+
+ /* Initialize values */
+ gif->buf_len = size;
+ gif->buf = data;
+
+ /* Get our current processing position */
+ nsgif_data = gif->buf + gif->buf_pos;
+
+ /* See if we should initialise the GIF */
+ if (gif->buf_pos == 0) {
+ /* We want everything to be NULL before we start so we've no
+ * chance of freeing bad pointers (paranoia)
+ */
+ gif->frame_image = NULL;
+ gif->frames = NULL;
+ gif->frame_holders = 0;
+
+ /* The caller may have been lazy and not reset any values */
+ gif->info.frame_count = 0;
+ gif->frame_count_partial = 0;
+ gif->decoded_frame = NSGIF_FRAME_INVALID;
+ gif->frame = NSGIF_FRAME_INVALID;
+
+ ret = nsgif__parse_header(gif, &nsgif_data, false);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+
+ ret = nsgif__parse_logical_screen_descriptor(gif, &nsgif_data);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+
+ /* Remember we've done this now */
+ gif->buf_pos = nsgif_data - gif->buf;
+
+ /* Some broken GIFs report the size as the screen size they
+ * were created in. As such, we detect for the common cases and
+ * set the sizes as 0 if they are found which results in the
+ * GIF being the maximum size of the frames.
+ */
+ if (((gif->info.width == 640) && (gif->info.height == 480)) ||
+ ((gif->info.width == 640) && (gif->info.height == 512)) ||
+ ((gif->info.width == 800) && (gif->info.height == 600)) ||
+ ((gif->info.width == 1024) && (gif->info.height == 768)) ||
+ ((gif->info.width == 1280) && (gif->info.height == 1024)) ||
+ ((gif->info.width == 1600) && (gif->info.height == 1200)) ||
+ ((gif->info.width == 0) || (gif->info.height == 0)) ||
+ ((gif->info.width > 2048) || (gif->info.height > 2048))) {
+ gif->info.width = 1;
+ gif->info.height = 1;
+ }
+
+ /* Set the first colour to a value that will never occur in
+ * reality so we know if we've processed it
+ */
+ gif->global_colour_table[0] = NSGIF_PROCESS_COLOURS;
+
+ /* Check if the GIF has no frame data (13-byte header + 1-byte
+ * termination block) Although generally useless, the GIF
+ * specification does not expressly prohibit this
+ */
+ if (gif->buf_len == gif->buf_pos + 1) {
+ if (nsgif_data[0] == NSGIF_TRAILER) {
+ return NSGIF_OK;
+ }
+ }
+ }
+
+ /* Do the colour map if we haven't already. As the top byte is always
+ * 0xff or 0x00 depending on the transparency we know if it's been
+ * filled in.
+ */
+ if (gif->global_colour_table[0] == NSGIF_PROCESS_COLOURS) {
+ /* Check for a global colour map signified by bit 7 */
+ if (gif->info.global_palette) {
+ size_t remaining = gif->buf + gif->buf_len - nsgif_data;
+ size_t used;
+
+ ret = nsgif__colour_table_extract(
+ gif->global_colour_table,
+ &gif->colour_layout,
+ gif->colour_table_size,
+ nsgif_data, remaining, &used, true);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+
+ nsgif_data += used;
+ gif->buf_pos = (nsgif_data - gif->buf);
+ } else {
+ /* Create a default colour table with the first two
+ * colours as black and white. */
+ uint8_t *entry = (uint8_t *)gif->global_colour_table;
+
+ /* Black */
+ entry[gif->colour_layout.r] = 0x00;
+ entry[gif->colour_layout.g] = 0x00;
+ entry[gif->colour_layout.b] = 0x00;
+ entry[gif->colour_layout.a] = 0xFF;
+
+ entry += sizeof(uint32_t);
+
+ /* White */
+ entry[gif->colour_layout.r] = 0xFF;
+ entry[gif->colour_layout.g] = 0xFF;
+ entry[gif->colour_layout.b] = 0xFF;
+ entry[gif->colour_layout.a] = 0xFF;
+
+ gif->colour_table_size = 2;
+ }
+
+ if (gif->info.global_palette &&
+ gif->bg_index < gif->colour_table_size) {
+ size_t bg_idx = gif->bg_index;
+ gif->info.background = gif->global_colour_table[bg_idx];
+ } else {
+ gif->info.background = gif->global_colour_table[0];
+ }
+ }
+
+ if (gif->lzw_ctx == NULL) {
+ lzw_result res = lzw_context_create(
+ (struct lzw_ctx **)&gif->lzw_ctx);
+ if (res != LZW_OK) {
+ return nsgif__error_from_lzw(res);
+ }
+ }
+
+ /* Try to initialise all frames. */
+ do {
+ frames = gif->info.frame_count;
+ ret = nsgif__process_frame(gif, frames, false);
+ } while (gif->info.frame_count > frames);
+
+ if (ret == NSGIF_ERR_END_OF_DATA && gif->info.frame_count > 0) {
+ ret = NSGIF_OK;
+ }
+
+ return ret;
+}
+
+/* exported function documented in nsgif.h */
+void nsgif_data_complete(
+ nsgif_t *gif)
+{
+ if (gif->data_complete == false) {
+ uint32_t start = gif->info.frame_count;
+ uint32_t end = gif->frame_count_partial;
+
+ for (uint32_t f = start; f < end; f++) {
+ nsgif_frame *frame = &gif->frames[f];
+
+ if (frame->lzw_data_length > 0) {
+ frame->info.display = true;
+ gif->info.frame_count = f + 1;
+
+ if (f == 0) {
+ frame->info.transparency = true;
+ }
+ break;
+ }
+ }
+ }
+
+ gif->data_complete = true;
+}
+
+static void nsgif__redraw_rect_extend(
+ const nsgif_rect_t *frame,
+ nsgif_rect_t *redraw)
+{
+ if (redraw->x1 == 0 || redraw->y1 == 0) {
+ *redraw = *frame;
+ } else {
+ if (redraw->x0 > frame->x0) {
+ redraw->x0 = frame->x0;
+ }
+ if (redraw->x1 < frame->x1) {
+ redraw->x1 = frame->x1;
+ }
+ if (redraw->y0 > frame->y0) {
+ redraw->y0 = frame->y0;
+ }
+ if (redraw->y1 < frame->y1) {
+ redraw->y1 = frame->y1;
+ }
+ }
+}
+
+static uint32_t nsgif__frame_next(
+ const nsgif_t *gif,
+ bool partial,
+ uint32_t frame)
+{
+ uint32_t frames = partial ?
+ gif->frame_count_partial :
+ gif->info.frame_count;
+
+ if (frames == 0) {
+ return NSGIF_FRAME_INVALID;
+ }
+
+ frame++;
+ return (frame >= frames) ? 0 : frame;
+}
+
+static nsgif_error nsgif__next_displayable_frame(
+ const nsgif_t *gif,
+ uint32_t *frame,
+ uint32_t *delay)
+{
+ uint32_t next = *frame;
+
+ do {
+ next = nsgif__frame_next(gif, false, next);
+ if (next <= *frame && *frame != NSGIF_FRAME_INVALID &&
+ gif->data_complete == false) {
+ return NSGIF_ERR_END_OF_DATA;
+
+ } else if (next == *frame || next == NSGIF_FRAME_INVALID) {
+ return NSGIF_ERR_FRAME_DISPLAY;
+ }
+
+ if (delay != NULL) {
+ *delay += gif->frames[next].info.delay;
+ }
+
+ } while (gif->frames[next].info.display == false);
+
+ *frame = next;
+ return NSGIF_OK;
+}
+
+static inline bool nsgif__animation_complete(int count, int max)
+{
+ if (max == 0) {
+ return false;
+ }
+
+ return (count >= max);
+}
+
+nsgif_error nsgif_reset(
+ nsgif_t *gif)
+{
+ gif->loop_count = 0;
+ gif->frame = NSGIF_FRAME_INVALID;
+
+ return NSGIF_OK;
+}
+
+/* exported function documented in nsgif.h */
+nsgif_error nsgif_frame_prepare(
+ nsgif_t *gif,
+ nsgif_rect_t *area,
+ uint32_t *delay_cs,
+ uint32_t *frame_new)
+{
+ nsgif_error ret;
+ nsgif_rect_t rect = {
+ .x1 = 0,
+ .y1 = 0,
+ };
+ uint32_t delay = 0;
+ uint32_t frame = gif->frame;
+
+ if (gif->frame != NSGIF_FRAME_INVALID &&
+ gif->frame < gif->info.frame_count &&
+ gif->frames[gif->frame].info.display) {
+ rect = gif->frames[gif->frame].info.rect;
+ }
+
+ if (nsgif__animation_complete(
+ gif->loop_count,
+ gif->info.loop_max)) {
+ return NSGIF_ERR_ANIMATION_END;
+ }
+
+ ret = nsgif__next_displayable_frame(gif, &frame, &delay);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+
+ if (gif->frame != NSGIF_FRAME_INVALID && frame < gif->frame) {
+ gif->loop_count++;
+ }
+
+ if (gif->data_complete) {
+ /* Check for last frame, which has infinite delay. */
+
+ if (gif->info.frame_count == 1) {
+ delay = NSGIF_INFINITE;
+ } else if (gif->info.loop_max != 0) {
+ uint32_t frame_next = frame;
+
+ ret = nsgif__next_displayable_frame(gif,
+ &frame_next, NULL);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+
+ if (gif->data_complete && frame_next < frame) {
+ if (nsgif__animation_complete(
+ gif->loop_count + 1,
+ gif->info.loop_max)) {
+ delay = NSGIF_INFINITE;
+ }
+ }
+ }
+ }
+
+ gif->frame = frame;
+ nsgif__redraw_rect_extend(&gif->frames[frame].info.rect, &rect);
+
+ if (delay < gif->delay_min) {
+ delay = gif->delay_default;
+ }
+
+ *frame_new = gif->frame;
+ *delay_cs = delay;
+ *area = rect;
+
+ return NSGIF_OK;
+}
+
+/* exported function documented in nsgif.h */
+nsgif_error nsgif_frame_decode(
+ nsgif_t *gif,
+ uint32_t frame,
+ nsgif_bitmap_t **bitmap)
+{
+ uint32_t start_frame;
+ nsgif_error ret = NSGIF_OK;
+
+ if (frame >= gif->info.frame_count) {
+ return NSGIF_ERR_BAD_FRAME;
+ }
+
+ if (gif->decoded_frame == frame) {
+ *bitmap = gif->frame_image;
+ return NSGIF_OK;
+
+ } else if (gif->decoded_frame >= frame ||
+ gif->decoded_frame == NSGIF_FRAME_INVALID) {
+ /* Can skip to first frame or restart. */
+ start_frame = 0;
+ } else {
+ start_frame = nsgif__frame_next(
+ gif, false, gif->decoded_frame);
+ }
+
+ for (uint32_t f = start_frame; f <= frame; f++) {
+ ret = nsgif__process_frame(gif, f, true);
+ if (ret != NSGIF_OK) {
+ return ret;
+ }
+ }
+
+ *bitmap = gif->frame_image;
+ return ret;
+}
+
+/* exported function documented in nsgif.h */
+const nsgif_info_t *nsgif_get_info(const nsgif_t *gif)
+{
+ return &gif->info;
+}
+
+/* exported function documented in nsgif.h */
+const nsgif_frame_info_t *nsgif_get_frame_info(
+ const nsgif_t *gif,
+ uint32_t frame)
+{
+ if (frame >= gif->info.frame_count) {
+ return NULL;
+ }
+
+ return &gif->frames[frame].info;
+}
+
+/* exported function documented in nsgif.h */
+void nsgif_global_palette(
+ const nsgif_t *gif,
+ uint32_t table[NSGIF_MAX_COLOURS],
+ size_t *entries)
+{
+ size_t len = sizeof(*table) * NSGIF_MAX_COLOURS;
+
+ memcpy(table, gif->global_colour_table, len);
+ *entries = gif->colour_table_size;
+}
+
+/* exported function documented in nsgif.h */
+bool nsgif_local_palette(
+ const nsgif_t *gif,
+ uint32_t frame,
+ uint32_t table[NSGIF_MAX_COLOURS],
+ size_t *entries)
+{
+ const nsgif_frame *f;
+
+ if (frame >= gif->frame_count_partial) {
+ return false;
+ }
+
+ f = &gif->frames[frame];
+ if (f->info.local_palette == false) {
+ return false;
+ }
+
+ *entries = 2 << (f->flags & NSGIF_COLOUR_TABLE_SIZE_MASK);
+ nsgif__colour_table_decode(table, &gif->colour_layout,
+ *entries, gif->buf + f->colour_table_offset);
+
+ return true;
+}
+
+/* exported function documented in nsgif.h */
+const char *nsgif_strerror(nsgif_error err)
+{
+ static const char *const str[] = {
+ [NSGIF_OK] = "Success",
+ [NSGIF_ERR_OOM] = "Out of memory",
+ [NSGIF_ERR_DATA] = "Invalid source data",
+ [NSGIF_ERR_BAD_FRAME] = "Requested frame does not exist",
+ [NSGIF_ERR_DATA_FRAME] = "Invalid frame data",
+ [NSGIF_ERR_END_OF_DATA] = "Unexpected end of GIF source data",
+ [NSGIF_ERR_DATA_COMPLETE] = "Can't add data to completed GIF",
+ [NSGIF_ERR_FRAME_DISPLAY] = "Frame can't be displayed",
+ [NSGIF_ERR_ANIMATION_END] = "Animation complete",
+ };
+
+ if (err >= NSGIF_ARRAY_LEN(str) || str[err] == NULL) {
+ return "Unknown error";
+ }
+
+ return str[err];
+}
+
+/* exported function documented in nsgif.h */
+const char *nsgif_str_disposal(enum nsgif_disposal disposal)
+{
+ static const char *const str[] = {
+ [NSGIF_DISPOSAL_UNSPECIFIED] = "Unspecified",
+ [NSGIF_DISPOSAL_NONE] = "None",
+ [NSGIF_DISPOSAL_RESTORE_BG] = "Restore background",
+ [NSGIF_DISPOSAL_RESTORE_PREV] = "Restore previous",
+ [NSGIF_DISPOSAL_RESTORE_QUIRK] = "Restore quirk",
+ };
+
+ if (disposal >= NSGIF_ARRAY_LEN(str) || str[disposal] == NULL) {
+ return "Unspecified";
+ }
+
+ return str[disposal];
+}
diff --git a/src/libnsgif.c b/src/libnsgif.c
deleted file mode 100644
index 95bbbfb..0000000
--- a/src/libnsgif.c
+++ /dev/null
@@ -1,1228 +0,0 @@
-/*
- * Copyright 2004 Richard Wilson <richard.wilson@netsurf-browser.org>
- * Copyright 2008 Sean Fox <dyntryx@gmail.com>
- *
- * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/
- * Licenced under the MIT License,
- * http://www.opensource.org/licenses/mit-license.php
- */
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <assert.h>
-#include "libnsgif.h"
-#include "utils/log.h"
-
-#include "lzw.h"
-
-/**
- *
- * \file
- * \brief GIF image decoder
- *
- * The GIF format is thoroughly documented; a full description can be found at
- * http://www.w3.org/Graphics/GIF/spec-gif89a.txt
- *
- * \todo Plain text and comment extensions should be implemented.
- */
-
-
-/** Maximum colour table size */
-#define GIF_MAX_COLOURS 256
-
-/** Internal flag that the colour table needs to be processed */
-#define GIF_PROCESS_COLOURS 0xaa000000
-
-/** Internal flag that a frame is invalid/unprocessed */
-#define GIF_INVALID_FRAME -1
-
-/** Transparent colour */
-#define GIF_TRANSPARENT_COLOUR 0x00
-
-/* GIF Flags */
-#define GIF_FRAME_COMBINE 1
-#define GIF_FRAME_CLEAR 2
-#define GIF_FRAME_RESTORE 3
-#define GIF_FRAME_QUIRKS_RESTORE 4
-
-#define GIF_IMAGE_SEPARATOR 0x2c
-#define GIF_INTERLACE_MASK 0x40
-#define GIF_COLOUR_TABLE_MASK 0x80
-#define GIF_COLOUR_TABLE_SIZE_MASK 0x07
-#define GIF_EXTENSION_INTRODUCER 0x21
-#define GIF_EXTENSION_GRAPHIC_CONTROL 0xf9
-#define GIF_DISPOSAL_MASK 0x1c
-#define GIF_TRANSPARENCY_MASK 0x01
-#define GIF_EXTENSION_COMMENT 0xfe
-#define GIF_EXTENSION_PLAIN_TEXT 0x01
-#define GIF_EXTENSION_APPLICATION 0xff
-#define GIF_BLOCK_TERMINATOR 0x00
-#define GIF_TRAILER 0x3b
-
-/** standard GIF header size */
-#define GIF_STANDARD_HEADER_SIZE 13
-
-
-/**
- * Updates the sprite memory size
- *
- * \param gif The animation context
- * \param width The width of the sprite
- * \param height The height of the sprite
- * \return GIF_INSUFFICIENT_MEMORY for a memory error GIF_OK for success
- */
-static gif_result
-gif_initialise_sprite(gif_animation *gif,
- unsigned int width,
- unsigned int height)
-{
- unsigned int max_width;
- unsigned int max_height;
- struct bitmap *buffer;
-
- /* Check if we've changed */
- if ((width <= gif->width) && (height <= gif->height)) {
- return GIF_OK;
- }
-
- /* Get our maximum values */
- max_width = (width > gif->width) ? width : gif->width;
- max_height = (height > gif->height) ? height : gif->height;
-
- /* Allocate some more memory */
- assert(gif->bitmap_callbacks.bitmap_create);
- buffer = gif->bitmap_callbacks.bitmap_create(max_width, max_height);
- if (buffer == NULL) {
- return GIF_INSUFFICIENT_MEMORY;
- }
-
- assert(gif->bitmap_callbacks.bitmap_destroy);
- gif->bitmap_callbacks.bitmap_destroy(gif->frame_image);
- gif->frame_image = buffer;
- gif->width = max_width;
- gif->height = max_height;
-
- /* Invalidate our currently decoded image */
- gif->decoded_frame = GIF_INVALID_FRAME;
- return GIF_OK;
-}
-
-
-/**
- * Attempts to initialise the frame's extensions
- *
- * \param gif The animation context
- * \param frame The frame number
- * @return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the
- * frame GIF_OK for successful initialisation.
- */
-static gif_result
-gif_initialise_frame_extensions(gif_animation *gif, const int frame)
-{
- unsigned char *gif_data, *gif_end;
- int gif_bytes;
- unsigned int block_size;
-
- /* Get our buffer position etc. */
- gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
- gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
-
- /* Initialise the extensions */
- while (gif_data < gif_end && gif_data[0] == GIF_EXTENSION_INTRODUCER) {
- ++gif_data;
- if ((gif_bytes = (gif_end - gif_data)) < 1) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
-
- /* Switch on extension label */
- switch (gif_data[0]) {
- case GIF_EXTENSION_GRAPHIC_CONTROL:
- /* 6-byte Graphic Control Extension is:
- *
- * +0 CHAR Graphic Control Label
- * +1 CHAR Block Size
- * +2 CHAR __Packed Fields__
- * 3BITS Reserved
- * 3BITS Disposal Method
- * 1BIT User Input Flag
- * 1BIT Transparent Color Flag
- * +3 SHORT Delay Time
- * +5 CHAR Transparent Color Index
- */
- if (gif_bytes < 6) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
-
- gif->frames[frame].frame_delay = gif_data[3] | (gif_data[4] << 8);
- if (gif_data[2] & GIF_TRANSPARENCY_MASK) {
- gif->frames[frame].transparency = true;
- gif->frames[frame].transparency_index = gif_data[5];
- }
- gif->frames[frame].disposal_method = ((gif_data[2] & GIF_DISPOSAL_MASK) >> 2);
- /* I have encountered documentation and GIFs in the
- * wild that use 0x04 to restore the previous frame,
- * rather than the officially documented 0x03. I
- * believe some (older?) software may even actually
- * export this way. We handle this as a type of
- * "quirks" mode.
- */
- if (gif->frames[frame].disposal_method == GIF_FRAME_QUIRKS_RESTORE) {
- gif->frames[frame].disposal_method = GIF_FRAME_RESTORE;
- }
- gif_data += (2 + gif_data[1]);
- break;
-
- case GIF_EXTENSION_APPLICATION:
- /* 14-byte+ Application Extension is:
- *
- * +0 CHAR Application Extension Label
- * +1 CHAR Block Size
- * +2 8CHARS Application Identifier
- * +10 3CHARS Appl. Authentication Code
- * +13 1-256 Application Data (Data sub-blocks)
- */
- if (gif_bytes < 17) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- if ((gif_data[1] == 0x0b) &&
- (strncmp((const char *) gif_data + 2,
- "NETSCAPE2.0", 11) == 0) &&
- (gif_data[13] == 0x03) &&
- (gif_data[14] == 0x01)) {
- gif->loop_count = gif_data[15] | (gif_data[16] << 8);
- }
- gif_data += (2 + gif_data[1]);
- break;
-
- case GIF_EXTENSION_COMMENT:
- /* Move the pointer to the first data sub-block Skip 1
- * byte for the extension label
- */
- ++gif_data;
- break;
-
- default:
- /* Move the pointer to the first data sub-block Skip 2
- * bytes for the extension label and size fields Skip
- * the extension size itself
- */
- if (gif_bytes < 2) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- gif_data += (2 + gif_data[1]);
- }
-
- /* Repeatedly skip blocks until we get a zero block or run out
- * of data This data is ignored by this gif decoder
- */
- gif_bytes = (gif_end - gif_data);
- block_size = 0;
- while (gif_data < gif_end && gif_data[0] != GIF_BLOCK_TERMINATOR) {
- block_size = gif_data[0] + 1;
- if ((gif_bytes -= block_size) < 0) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- gif_data += block_size;
- }
- ++gif_data;
- }
-
- /* Set buffer position and return */
- gif->buffer_position = (gif_data - gif->gif_data);
- return GIF_OK;
-}
-
-
-/**
- * Attempts to initialise the next frame
- *
- * \param gif The animation context
- * \return error code
- * - GIF_INSUFFICIENT_DATA for insufficient data to do anything
- * - GIF_FRAME_DATA_ERROR for GIF frame data error
- * - GIF_INSUFFICIENT_MEMORY for insufficient memory to process
- * - GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
- * - GIF_DATA_ERROR for GIF error (invalid frame header)
- * - GIF_OK for successful decoding
- * - GIF_WORKING for successful decoding if more frames are expected
-*/
-static gif_result gif_initialise_frame(gif_animation *gif)
-{
- int frame;
- gif_frame *temp_buf;
-
- unsigned char *gif_data, *gif_end;
- int gif_bytes;
- unsigned int flags = 0;
- unsigned int width, height, offset_x, offset_y;
- unsigned int block_size, colour_table_size;
- bool first_image = true;
- gif_result return_value;
-
- /* Get the frame to decode and our data position */
- frame = gif->frame_count;
-
- /* Get our buffer position etc. */
- gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
- gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
- gif_bytes = (gif_end - gif_data);
-
- /* Check if we've finished */
- if ((gif_bytes > 0) && (gif_data[0] == GIF_TRAILER)) {
- return GIF_OK;
- }
-
- /* Check if there is enough data remaining. The shortest block of data
- * is a 4-byte comment extension + 1-byte block terminator + 1-byte gif
- * trailer
- */
- if (gif_bytes < 6) {
- return GIF_INSUFFICIENT_DATA;
- }
-
- /* We could theoretically get some junk data that gives us millions of
- * frames, so we ensure that we don't have a silly number
- */
- if (frame > 4096) {
- return GIF_FRAME_DATA_ERROR;
- }
-
- /* Get some memory to store our pointers in etc. */
- if ((int)gif->frame_holders <= frame) {
- /* Allocate more memory */
- temp_buf = (gif_frame *)realloc(gif->frames, (frame + 1) * sizeof(gif_frame));
- if (temp_buf == NULL) {
- return GIF_INSUFFICIENT_MEMORY;
- }
- gif->frames = temp_buf;
- gif->frame_holders = frame + 1;
- }
-
- /* Store our frame pointer. We would do it when allocating except we
- * start off with one frame allocated so we can always use realloc.
- */
- gif->frames[frame].frame_pointer = gif->buffer_position;
- gif->frames[frame].display = false;
- gif->frames[frame].virgin = true;
- gif->frames[frame].disposal_method = 0;
- gif->frames[frame].transparency = false;
- gif->frames[frame].frame_delay = 100;
- gif->frames[frame].redraw_required = false;
-
- /* Invalidate any previous decoding we have of this frame */
- if (gif->decoded_frame == frame) {
- gif->decoded_frame = GIF_INVALID_FRAME;
- }
-
- /* We pretend to initialise the frames, but really we just skip over
- * all the data contained within. This is all basically a cut down
- * version of gif_decode_frame that doesn't have any of the LZW bits in
- * it.
- */
-
- /* Initialise any extensions */
- gif->buffer_position = gif_data - gif->gif_data;
- return_value = gif_initialise_frame_extensions(gif, frame);
- if (return_value != GIF_OK) {
- return return_value;
- }
- gif_data = (gif->gif_data + gif->buffer_position);
- gif_bytes = (gif_end - gif_data);
-
- /* Check if we've finished */
- if ((gif_bytes = (gif_end - gif_data)) < 1) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
-
- if (gif_data[0] == GIF_TRAILER) {
- gif->buffer_position = (gif_data - gif->gif_data);
- gif->frame_count = frame + 1;
- return GIF_OK;
- }
-
- /* If we're not done, there should be an image descriptor */
- if (gif_data[0] != GIF_IMAGE_SEPARATOR) {
- return GIF_FRAME_DATA_ERROR;
- }
-
- /* Do some simple boundary checking */
- if (gif_bytes < 10) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- offset_x = gif_data[1] | (gif_data[2] << 8);
- offset_y = gif_data[3] | (gif_data[4] << 8);
- width = gif_data[5] | (gif_data[6] << 8);
- height = gif_data[7] | (gif_data[8] << 8);
-
- /* Set up the redraw characteristics. We have to check for extending
- * the area due to multi-image frames.
- */
- if (!first_image) {
- if (gif->frames[frame].redraw_x > offset_x) {
- gif->frames[frame].redraw_width += (gif->frames[frame].redraw_x - offset_x);
- gif->frames[frame].redraw_x = offset_x;
- }
-
- if (gif->frames[frame].redraw_y > offset_y) {
- gif->frames[frame].redraw_height += (gif->frames[frame].redraw_y - offset_y);
- gif->frames[frame].redraw_y = offset_y;
- }
-
- if ((offset_x + width) > (gif->frames[frame].redraw_x + gif->frames[frame].redraw_width)) {
- gif->frames[frame].redraw_width = (offset_x + width) - gif->frames[frame].redraw_x;
- }
-
- if ((offset_y + height) > (gif->frames[frame].redraw_y + gif->frames[frame].redraw_height)) {
- gif->frames[frame].redraw_height = (offset_y + height) - gif->frames[frame].redraw_y;
- }
- } else {
- first_image = false;
- gif->frames[frame].redraw_x = offset_x;
- gif->frames[frame].redraw_y = offset_y;
- gif->frames[frame].redraw_width = width;
- gif->frames[frame].redraw_height = height;
- }
-
- /* if we are clearing the background then we need to redraw enough to
- * cover the previous frame too
- */
- gif->frames[frame].redraw_required = ((gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) ||
- (gif->frames[frame].disposal_method == GIF_FRAME_RESTORE));
-
- /* Boundary checking - shouldn't ever happen except with junk data */
- if (gif_initialise_sprite(gif, (offset_x + width), (offset_y + height))) {
- return GIF_INSUFFICIENT_MEMORY;
- }
-
- /* Decode the flags */
- flags = gif_data[9];
- colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);
-
- /* Move our data onwards and remember we've got a bit of this frame */
- gif_data += 10;
- gif_bytes = (gif_end - gif_data);
- gif->frame_count_partial = frame + 1;
-
- /* Skip the local colour table */
- if (flags & GIF_COLOUR_TABLE_MASK) {
- gif_data += 3 * colour_table_size;
- if ((gif_bytes = (gif_end - gif_data)) < 0) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- }
-
- /* Ensure we have a correct code size */
- if (gif_bytes < 1) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- if (gif_data[0] > LZW_CODE_MAX) {
- return GIF_DATA_ERROR;
- }
-
- /* Move our pointer to the actual image data */
- gif_data++;
- --gif_bytes;
-
- /* Repeatedly skip blocks until we get a zero block or run out of data
- * These blocks of image data are processed later by gif_decode_frame()
- */
- block_size = 0;
- while (block_size != 1) {
- if (gif_bytes < 1) return GIF_INSUFFICIENT_FRAME_DATA;
- block_size = gif_data[0] + 1;
- /* Check if the frame data runs off the end of the file */
- if ((int)(gif_bytes - block_size) < 0) {
- /* Try to recover by signaling the end of the gif.
- * Once we get garbage data, there is no logical way to
- * determine where the next frame is. It's probably
- * better to partially load the gif than not at all.
- */
- if (gif_bytes >= 2) {
- gif_data[0] = 0;
- gif_data[1] = GIF_TRAILER;
- gif_bytes = 1;
- ++gif_data;
- break;
- } else {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- } else {
- gif_bytes -= block_size;
- gif_data += block_size;
- }
- }
-
- /* Add the frame and set the display flag */
- gif->buffer_position = gif_data - gif->gif_data;
- gif->frame_count = frame + 1;
- gif->frames[frame].display = true;
-
- /* Check if we've finished */
- if (gif_bytes < 1) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- } else {
- if (gif_data[0] == GIF_TRAILER) {
- return GIF_OK;
- }
- }
- return GIF_WORKING;
-}
-
-
-
-
-/**
- * Skips the frame's extensions (which have been previously initialised)
- *
- * \param gif The animation context
- * \return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the
- * frame GIF_OK for successful decoding
- */
-static gif_result gif_skip_frame_extensions(gif_animation *gif)
-{
- unsigned char *gif_data, *gif_end;
- int gif_bytes;
- unsigned int block_size;
-
- /* Get our buffer position etc. */
- gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
- gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
- gif_bytes = (gif_end - gif_data);
-
- /* Skip the extensions */
- while (gif_data < gif_end && gif_data[0] == GIF_EXTENSION_INTRODUCER) {
- ++gif_data;
- if (gif_data >= gif_end) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
-
- /* Switch on extension label */
- switch(gif_data[0]) {
- case GIF_EXTENSION_COMMENT:
- /* Move the pointer to the first data sub-block
- * 1 byte for the extension label
- */
- ++gif_data;
- break;
-
- default:
- /* Move the pointer to the first data sub-block 2 bytes
- * for the extension label and size fields Skip the
- * extension size itself
- */
- if (gif_data + 1 >= gif_end) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- gif_data += (2 + gif_data[1]);
- }
-
- /* Repeatedly skip blocks until we get a zero block or run out
- * of data This data is ignored by this gif decoder
- */
- gif_bytes = (gif_end - gif_data);
- block_size = 0;
- while (gif_data < gif_end && gif_data[0] != GIF_BLOCK_TERMINATOR) {
- block_size = gif_data[0] + 1;
- if ((gif_bytes -= block_size) < 0) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
- gif_data += block_size;
- }
- ++gif_data;
- }
-
- /* Set buffer position and return */
- gif->buffer_position = (gif_data - gif->gif_data);
- return GIF_OK;
-}
-
-static unsigned int gif_interlaced_line(int height, int y) {
- if ((y << 3) < height) {
- return (y << 3);
- }
- y -= ((height + 7) >> 3);
- if ((y << 3) < (height - 4)) {
- return (y << 3) + 4;
- }
- y -= ((height + 3) >> 3);
- if ((y << 2) < (height - 2)) {
- return (y << 2) + 2;
- }
- y -= ((height + 1) >> 2);
- return (y << 1) + 1;
-}
-
-
-static gif_result gif_error_from_lzw(lzw_result l_res)
-{
- static const gif_result g_res[] = {
- [LZW_OK] = GIF_OK,
- [LZW_OK_EOD] = GIF_END_OF_FRAME,
- [LZW_NO_MEM] = GIF_INSUFFICIENT_MEMORY,
- [LZW_NO_DATA] = GIF_INSUFFICIENT_FRAME_DATA,
- [LZW_EOI_CODE] = GIF_FRAME_DATA_ERROR,
- [LZW_BAD_ICODE] = GIF_FRAME_DATA_ERROR,
- [LZW_BAD_CODE] = GIF_FRAME_DATA_ERROR,
- };
- return g_res[l_res];
-}
-
-static void gif__record_previous_frame(gif_animation *gif)
-{
- bool need_alloc = gif->prev_frame == NULL;
- const uint32_t *frame_data;
- uint32_t *prev_frame;
-
- if (gif->decoded_frame == GIF_INVALID_FRAME ||
- gif->decoded_frame == gif->prev_index) {
- /* No frame to copy, or already have this frame recorded. */
- return;
- }
-
- assert(gif->bitmap_callbacks.bitmap_get_buffer);
- frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
- if (!frame_data) {
- return;
- }
-
- if (gif->prev_frame != NULL &&
- gif->width * gif->height < gif->prev_width * gif->prev_height) {
- need_alloc = true;
- }
-
- if (need_alloc) {
- prev_frame = realloc(gif->prev_frame,
- gif->width * gif->height * 4);
- if (prev_frame == NULL) {
- return;
- }
- } else {
- prev_frame = gif->prev_frame;
- }
-
- memcpy(prev_frame, frame_data, gif->width * gif->height * 4);
-
- gif->prev_frame = prev_frame;
- gif->prev_width = gif->width;
- gif->prev_height = gif->height;
- gif->prev_index = gif->decoded_frame;
-}
-
-static gif_result gif__recover_previous_frame(const gif_animation *gif)
-{
- const uint32_t *prev_frame = gif->prev_frame;
- unsigned height = gif->height < gif->prev_height ? gif->height : gif->prev_height;
- unsigned width = gif->width < gif->prev_width ? gif->width : gif->prev_width;
- uint32_t *frame_data;
-
- if (prev_frame == NULL) {
- return GIF_FRAME_DATA_ERROR;
- }
-
- assert(gif->bitmap_callbacks.bitmap_get_buffer);
- frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
- if (!frame_data) {
- return GIF_INSUFFICIENT_MEMORY;
- }
-
- for (unsigned y = 0; y < height; y++) {
- memcpy(frame_data, prev_frame, width * 4);
-
- frame_data += gif->width;
- prev_frame += gif->prev_width;
- }
-
- return GIF_OK;
-}
-
-/**
- * decode a gif frame
- *
- * \param gif gif animation context.
- * \param frame The frame number to decode.
- * \param clear_image flag for image data being cleared instead of plotted.
- */
-static gif_result
-gif_internal_decode_frame(gif_animation *gif,
- unsigned int frame,
- bool clear_image)
-{
- gif_result err;
- unsigned int index = 0;
- unsigned char *gif_data, *gif_end;
- int gif_bytes;
- unsigned int width, height, offset_x, offset_y;
- unsigned int flags, colour_table_size, interlace;
- unsigned int *colour_table;
- unsigned int *frame_data = 0; // Set to 0 for no warnings
- unsigned int *frame_scanline;
- unsigned int save_buffer_position;
- unsigned int return_value = 0;
- unsigned int x, y, decode_y, burst_bytes;
- register unsigned char colour;
-
- /* Ensure this frame is supposed to be decoded */
- if (gif->frames[frame].display == false) {
- return GIF_OK;
- }
-
- /* Ensure the frame is in range to decode */
- if (frame > gif->frame_count_partial) {
- return GIF_INSUFFICIENT_DATA;
- }
-
- /* done if frame is already decoded */
- if ((!clear_image) &&
- ((int)frame == gif->decoded_frame)) {
- return GIF_OK;
- }
-
- if (gif->frames[frame].disposal_method == GIF_FRAME_RESTORE) {
- /* Store the previous frame for later restoration */
- gif__record_previous_frame(gif);
- }
-
- /* Get the start of our frame data and the end of the GIF data */
- gif_data = gif->gif_data + gif->frames[frame].frame_pointer;
- gif_end = gif->gif_data + gif->buffer_size;
- gif_bytes = (gif_end - gif_data);
-
- /*
- * Ensure there is a minimal amount of data to proceed. The shortest
- * block of data is a 10-byte image descriptor + 1-byte gif trailer
- */
- if (gif_bytes < 12) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
-
- /* Save the buffer position */
- save_buffer_position = gif->buffer_position;
- gif->buffer_position = gif_data - gif->gif_data;
-
- /* Skip any extensions because they have allready been processed */
- if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) {
- goto gif_decode_frame_exit;
- }
- gif_data = (gif->gif_data + gif->buffer_position);
- gif_bytes = (gif_end - gif_data);
-
- /* Ensure we have enough data for the 10-byte image descriptor + 1-byte
- * gif trailer
- */
- if (gif_bytes < 12) {
- return_value = GIF_INSUFFICIENT_FRAME_DATA;
- goto gif_decode_frame_exit;
- }
-
- /* 10-byte Image Descriptor is:
- *
- * +0 CHAR Image Separator (0x2c)
- * +1 SHORT Image Left Position
- * +3 SHORT Image Top Position
- * +5 SHORT Width
- * +7 SHORT Height
- * +9 CHAR __Packed Fields__
- * 1BIT Local Colour Table Flag
- * 1BIT Interlace Flag
- * 1BIT Sort Flag
- * 2BITS Reserved
- * 3BITS Size of Local Colour Table
- */
- if (gif_data[0] != GIF_IMAGE_SEPARATOR) {
- return_value = GIF_DATA_ERROR;
- goto gif_decode_frame_exit;
- }
- offset_x = gif_data[1] | (gif_data[2] << 8);
- offset_y = gif_data[3] | (gif_data[4] << 8);
- width = gif_data[5] | (gif_data[6] << 8);
- height = gif_data[7] | (gif_data[8] << 8);
-
- /* Boundary checking - shouldn't ever happen except unless the data has
- * been modified since initialisation.
- */
- if ((offset_x + width > gif->width) ||
- (offset_y + height > gif->height)) {
- return_value = GIF_DATA_ERROR;
- goto gif_decode_frame_exit;
- }
-
- /* Decode the flags */
- flags = gif_data[9];
- colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);
- interlace = flags & GIF_INTERLACE_MASK;
-
- /* Advance data pointer to next block either colour table or image
- * data.
- */
- gif_data += 10;
- gif_bytes = (gif_end - gif_data);
-
- /* Set up the colour table */
- if (flags & GIF_COLOUR_TABLE_MASK) {
- if (gif_bytes < (int)(3 * colour_table_size)) {
- return_value = GIF_INSUFFICIENT_FRAME_DATA;
- goto gif_decode_frame_exit;
- }
- colour_table = gif->local_colour_table;
- if (!clear_image) {
- for (index = 0; index < colour_table_size; index++) {
- /* Gif colour map contents are r,g,b.
- *
- * We want to pack them bytewise into the
- * colour table, such that the red component
- * is in byte 0 and the alpha component is in
- * byte 3.
- */
- unsigned char *entry =
- (unsigned char *) &colour_table[index];
-
- entry[0] = gif_data[0]; /* r */
- entry[1] = gif_data[1]; /* g */
- entry[2] = gif_data[2]; /* b */
- entry[3] = 0xff; /* a */
-
- gif_data += 3;
- }
- } else {
- gif_data += 3 * colour_table_size;
- }
- gif_bytes = (gif_end - gif_data);
- } else {
- colour_table = gif->global_colour_table;
- }
-
- /* Ensure sufficient data remains */
- if (gif_bytes < 1) {
- return_value = GIF_INSUFFICIENT_FRAME_DATA;
- goto gif_decode_frame_exit;
- }
-
- /* check for an end marker */
- if (gif_data[0] == GIF_TRAILER) {
- return_value = GIF_OK;
- goto gif_decode_frame_exit;
- }
-
- /* Get the frame data */
- assert(gif->bitmap_callbacks.bitmap_get_buffer);
- frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
- if (!frame_data) {
- return GIF_INSUFFICIENT_MEMORY;
- }
-
- /* If we are clearing the image we just clear, if not decode */
- if (!clear_image) {
- lzw_result res;
- const uint8_t *stack_base;
- const uint8_t *stack_pos;
-
- /* Ensure we have enough data for a 1-byte LZW code size +
- * 1-byte gif trailer
- */
- if (gif_bytes < 2) {
- return_value = GIF_INSUFFICIENT_FRAME_DATA;
- goto gif_decode_frame_exit;
- }
-
- /* If we only have a 1-byte LZW code size + 1-byte gif trailer,
- * we're finished
- */
- if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) {
- return_value = GIF_OK;
- goto gif_decode_frame_exit;
- }
-
- /* If the previous frame's disposal method requires we restore
- * the background colour or this is the first frame, clear
- * the frame data
- */
- if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) {
- memset((char*)frame_data,
- GIF_TRANSPARENT_COLOUR,
- gif->width * gif->height * sizeof(int));
- gif->decoded_frame = frame;
- /* The line below would fill the image with its
- * background color, but because GIFs support
- * transparency we likely wouldn't want to do that. */
- /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */
- } else if ((frame != 0) &&
- (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) {
- return_value = gif_internal_decode_frame(gif,
- (frame - 1),
- true);
- if (return_value != GIF_OK) {
- goto gif_decode_frame_exit;
- }
-
- } else if ((frame != 0) &&
- (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) {
- /*
- * If the previous frame's disposal method requires we
- * restore the previous image, restore our saved image.
- */
- err = gif__recover_previous_frame(gif);
- if (err != GIF_OK) {
- /* see notes above on transparency
- * vs. background color
- */
- memset((char*)frame_data,
- GIF_TRANSPARENT_COLOUR,
- gif->width * gif->height * sizeof(int));
- }
- }
- gif->decoded_frame = frame;
- gif->buffer_position = (gif_data - gif->gif_data) + 1;
-
- /* Initialise the LZW decoding */
- res = lzw_decode_init(gif->lzw_ctx, gif->gif_data,
- gif->buffer_size, gif->buffer_position,
- gif_data[0], &stack_base, &stack_pos);
- if (res != LZW_OK) {
- return gif_error_from_lzw(res);
- }
-
- /* Decompress the data */
- for (y = 0; y < height; y++) {
- if (interlace) {
- decode_y = gif_interlaced_line(height, y) + offset_y;
- } else {
- decode_y = y + offset_y;
- }
- frame_scanline = frame_data + offset_x + (decode_y * gif->width);
-
- /* Rather than decoding pixel by pixel, we try to burst
- * out streams of data to remove the need for end-of
- * data checks every pixel.
- */
- x = width;
- while (x > 0) {
- burst_bytes = (stack_pos - stack_base);
- if (burst_bytes > 0) {
- if (burst_bytes > x) {
- burst_bytes = x;
- }
- x -= burst_bytes;
- while (burst_bytes-- > 0) {
- colour = *--stack_pos;
- if (((gif->frames[frame].transparency) &&
- (colour != gif->frames[frame].transparency_index)) ||
- (!gif->frames[frame].transparency)) {
- *frame_scanline = colour_table[colour];
- }
- frame_scanline++;
- }
- } else {
- res = lzw_decode(gif->lzw_ctx, &stack_pos);
- if (res != LZW_OK) {
- /* Unexpected end of frame, try to recover */
- if (res == LZW_OK_EOD) {
- return_value = GIF_OK;
- } else {
- return_value = gif_error_from_lzw(res);
- }
- goto gif_decode_frame_exit;
- }
- }
- }
- }
- } else {
- /* Clear our frame */
- if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) {
- for (y = 0; y < height; y++) {
- frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width);
- if (gif->frames[frame].transparency) {
- memset(frame_scanline,
- GIF_TRANSPARENT_COLOUR,
- width * 4);
- } else {
- memset(frame_scanline,
- colour_table[gif->background_index],
- width * 4);
- }
- }
- }
- }
-gif_decode_frame_exit:
-
- /* Check if we should test for optimisation */
- if (gif->frames[frame].virgin) {
- if (gif->bitmap_callbacks.bitmap_test_opaque) {
- gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image);
- } else {
- gif->frames[frame].opaque = false;
- }
- gif->frames[frame].virgin = false;
- }
-
- if (gif->bitmap_callbacks.bitmap_set_opaque) {
- gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque);
- }
-
- if (gif->bitmap_callbacks.bitmap_modified) {
- gif->bitmap_callbacks.bitmap_modified(gif->frame_image);
- }
-
- /* Restore the buffer position */
- gif->buffer_position = save_buffer_position;
-
- return return_value;
-}
-
-
-/* exported function documented in libnsgif.h */
-void gif_create(gif_animation *gif, gif_bitmap_callback_vt *bitmap_callbacks)
-{
- memset(gif, 0, sizeof(gif_animation));
- gif->bitmap_callbacks = *bitmap_callbacks;
- gif->decoded_frame = GIF_INVALID_FRAME;
- gif->prev_index = GIF_INVALID_FRAME;
-}
-
-
-/* exported function documented in libnsgif.h */
-gif_result gif_initialise(gif_animation *gif, size_t size, unsigned char *data)
-{
- unsigned char *gif_data;
- unsigned int index;
- gif_result return_value;
-
- /* Initialize values */
- gif->buffer_size = size;
- gif->gif_data = data;
-
- if (gif->lzw_ctx == NULL) {
- lzw_result res = lzw_context_create(
- (struct lzw_ctx **)&gif->lzw_ctx);
- if (res != LZW_OK) {
- return gif_error_from_lzw(res);
- }
- }
-
- /* Check for sufficient data to be a GIF (6-byte header + 7-byte
- * logical screen descriptor)
- */
- if (gif->buffer_size < GIF_STANDARD_HEADER_SIZE) {
- return GIF_INSUFFICIENT_DATA;
- }
-
- /* Get our current processing position */
- gif_data = gif->gif_data + gif->buffer_position;
-
- /* See if we should initialise the GIF */
- if (gif->buffer_position == 0) {
- /* We want everything to be NULL before we start so we've no
- * chance of freeing bad pointers (paranoia)
- */
- gif->frame_image = NULL;
- gif->frames = NULL;
- gif->local_colour_table = NULL;
- gif->global_colour_table = NULL;
-
- /* The caller may have been lazy and not reset any values */
- gif->frame_count = 0;
- gif->frame_count_partial = 0;
- gif->decoded_frame = GIF_INVALID_FRAME;
-
- /* 6-byte GIF file header is:
- *
- * +0 3CHARS Signature ('GIF')
- * +3 3CHARS Version ('87a' or '89a')
- */
- if (strncmp((const char *) gif_data, "GIF", 3) != 0) {
- return GIF_DATA_ERROR;
- }
- gif_data += 3;
-
- /* Ensure GIF reports version 87a or 89a */
- /*
- if ((strncmp(gif_data, "87a", 3) != 0) &&
- (strncmp(gif_data, "89a", 3) != 0))
- LOG(("Unknown GIF format - proceeding anyway"));
- */
- gif_data += 3;
-
- /* 7-byte Logical Screen Descriptor is:
- *
- * +0 SHORT Logical Screen Width
- * +2 SHORT Logical Screen Height
- * +4 CHAR __Packed Fields__
- * 1BIT Global Colour Table Flag
- * 3BITS Colour Resolution
- * 1BIT Sort Flag
- * 3BITS Size of Global Colour Table
- * +5 CHAR Background Colour Index
- * +6 CHAR Pixel Aspect Ratio
- */
- gif->width = gif_data[0] | (gif_data[1] << 8);
- gif->height = gif_data[2] | (gif_data[3] << 8);
- gif->global_colours = (gif_data[4] & GIF_COLOUR_TABLE_MASK);
- gif->colour_table_size = (2 << (gif_data[4] & GIF_COLOUR_TABLE_SIZE_MASK));
- gif->background_index = gif_data[5];
- gif->aspect_ratio = gif_data[6];
- gif->loop_count = 1;
- gif_data += 7;
-
- /* Some broken GIFs report the size as the screen size they
- * were created in. As such, we detect for the common cases and
- * set the sizes as 0 if they are found which results in the
- * GIF being the maximum size of the frames.
- */
- if (((gif->width == 640) && (gif->height == 480)) ||
- ((gif->width == 640) && (gif->height == 512)) ||
- ((gif->width == 800) && (gif->height == 600)) ||
- ((gif->width == 1024) && (gif->height == 768)) ||
- ((gif->width == 1280) && (gif->height == 1024)) ||
- ((gif->width == 1600) && (gif->height == 1200)) ||
- ((gif->width == 0) || (gif->height == 0)) ||
- ((gif->width > 2048) || (gif->height > 2048))) {
- gif->width = 1;
- gif->height = 1;
- }
-
- /* Allocate some data irrespective of whether we've got any
- * colour tables. We always get the maximum size in case a GIF
- * is lying to us. It's far better to give the wrong colours
- * than to trample over some memory somewhere.
- */
- gif->global_colour_table = calloc(GIF_MAX_COLOURS, sizeof(unsigned int));
- gif->local_colour_table = calloc(GIF_MAX_COLOURS, sizeof(unsigned int));
- if ((gif->global_colour_table == NULL) ||
- (gif->local_colour_table == NULL)) {
- gif_finalise(gif);
- return GIF_INSUFFICIENT_MEMORY;
- }
-
- /* Set the first colour to a value that will never occur in
- * reality so we know if we've processed it
- */
- gif->global_colour_table[0] = GIF_PROCESS_COLOURS;
-
- /* Check if the GIF has no frame data (13-byte header + 1-byte
- * termination block) Although generally useless, the GIF
- * specification does not expressly prohibit this
- */
- if (gif->buffer_size == (GIF_STANDARD_HEADER_SIZE + 1)) {
- if (gif_data[0] == GIF_TRAILER) {
- return GIF_OK;
- } else {
- return GIF_INSUFFICIENT_DATA;
- }
- }
-
- /* Initialise enough workspace for a frame */
- if ((gif->frames = (gif_frame *)malloc(sizeof(gif_frame))) == NULL) {
- gif_finalise(gif);
- return GIF_INSUFFICIENT_MEMORY;
- }
- gif->frame_holders = 1;
-
- /* Initialise the bitmap header */
- assert(gif->bitmap_callbacks.bitmap_create);
- gif->frame_image = gif->bitmap_callbacks.bitmap_create(gif->width, gif->height);
- if (gif->frame_image == NULL) {
- gif_finalise(gif);
- return GIF_INSUFFICIENT_MEMORY;
- }
-
- /* Remember we've done this now */
- gif->buffer_position = gif_data - gif->gif_data;
- }
-
- /* Do the colour map if we haven't already. As the top byte is always
- * 0xff or 0x00 depending on the transparency we know if it's been
- * filled in.
- */
- if (gif->global_colour_table[0] == GIF_PROCESS_COLOURS) {
- /* Check for a global colour map signified by bit 7 */
- if (gif->global_colours) {
- if (gif->buffer_size < (gif->colour_table_size * 3 + GIF_STANDARD_HEADER_SIZE)) {
- return GIF_INSUFFICIENT_DATA;
- }
- for (index = 0; index < gif->colour_table_size; index++) {
- /* Gif colour map contents are r,g,b.
- *
- * We want to pack them bytewise into the
- * colour table, such that the red component
- * is in byte 0 and the alpha component is in
- * byte 3.
- */
- unsigned char *entry = (unsigned char *) &gif->
- global_colour_table[index];
-
- entry[0] = gif_data[0]; /* r */
- entry[1] = gif_data[1]; /* g */
- entry[2] = gif_data[2]; /* b */
- entry[3] = 0xff; /* a */
-
- gif_data += 3;
- }
- gif->buffer_position = (gif_data - gif->gif_data);
- } else {
- /* Create a default colour table with the first two
- * colours as black and white
- */
- unsigned int *entry = gif->global_colour_table;
-
- entry[0] = 0x00000000;
- /* Force Alpha channel to opaque */
- ((unsigned char *) entry)[3] = 0xff;
-
- entry[1] = 0xffffffff;
- }
- }
-
- /* Repeatedly try to initialise frames */
- while ((return_value = gif_initialise_frame(gif)) == GIF_WORKING);
-
- /* If there was a memory error tell the caller */
- if ((return_value == GIF_INSUFFICIENT_MEMORY) ||
- (return_value == GIF_DATA_ERROR)) {
- return return_value;
- }
-
- /* If we didn't have some frames then a GIF_INSUFFICIENT_DATA becomes a
- * GIF_INSUFFICIENT_FRAME_DATA
- */
- if ((return_value == GIF_INSUFFICIENT_DATA) &&
- (gif->frame_count_partial > 0)) {
- return GIF_INSUFFICIENT_FRAME_DATA;
- }
-
- /* Return how many we got */
- return return_value;
-}
-
-
-/* exported function documented in libnsgif.h */
-gif_result gif_decode_frame(gif_animation *gif, unsigned int frame)
-{
- return gif_internal_decode_frame(gif, frame, false);
-}
-
-
-/* exported function documented in libnsgif.h */
-void gif_finalise(gif_animation *gif)
-{
- /* Release all our memory blocks */
- if (gif->frame_image) {
- assert(gif->bitmap_callbacks.bitmap_destroy);
- gif->bitmap_callbacks.bitmap_destroy(gif->frame_image);
- }
-
- gif->frame_image = NULL;
- free(gif->frames);
- gif->frames = NULL;
- free(gif->local_colour_table);
- gif->local_colour_table = NULL;
- free(gif->global_colour_table);
- gif->global_colour_table = NULL;
-
- free(gif->prev_frame);
- gif->prev_frame = NULL;
-
- lzw_context_destroy(gif->lzw_ctx);
- gif->lzw_ctx = NULL;
-}
diff --git a/src/lzw.c b/src/lzw.c
index 31cf7d4..3098ef5 100644
--- a/src/lzw.c
+++ b/src/lzw.c
@@ -4,6 +4,7 @@
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2017 Michael Drake <michael.drake@codethink.co.uk>
+ * Copyright 2021 Michael Drake <tlsa@netsurf-browser.org>
*/
#include <assert.h>
@@ -20,6 +21,8 @@
* Decoder for GIF LZW data.
*/
+/** Maximum number of lzw table entries. */
+#define LZW_TABLE_ENTRY_MAX (1u << LZW_CODE_MAX)
/**
* Context for reading LZW data.
@@ -33,57 +36,65 @@
* Note that an individual LZW code can be split over up to three sub-blocks.
*/
struct lzw_read_ctx {
- const uint8_t *data; /**< Pointer to start of input data */
- uint32_t data_len; /**< Input data length */
- uint32_t data_sb_next; /**< Offset to sub-block size */
+ const uint8_t *restrict data; /**< Pointer to start of input data */
+ size_t data_len; /**< Input data length */
+ size_t data_sb_next; /**< Offset to sub-block size */
const uint8_t *sb_data; /**< Pointer to current sub-block in data */
- uint32_t sb_bit; /**< Current bit offset in sub-block */
+ size_t sb_bit; /**< Current bit offset in sub-block */
uint32_t sb_bit_count; /**< Bit count in sub-block */
};
/**
- * LZW dictionary entry.
+ * LZW table entry.
*
- * Records in the dictionary are composed of 1 or more entries.
- * Entries point to previous entries which can be followed to compose
+ * Records in the table are composed of 1 or more entries.
+ * Entries refer to the entry they extend which can be followed to compose
* the complete record. To compose the record in reverse order, take
- * the `last_value` from each entry, and move to the previous entry.
- * If the previous_entry's index is < the current clear_code, then it
+ * the `value` from each entry, and move to the entry it extends.
+ * If the extended entries index is < the current clear_code, then it
* is the last entry in the record.
*/
-struct lzw_dictionary_entry {
- uint8_t last_value; /**< Last value for record ending at entry. */
- uint8_t first_value; /**< First value for entry's record. */
- uint16_t previous_entry; /**< Offset in dictionary to previous entry. */
+struct lzw_table_entry {
+ uint8_t value; /**< Last value for record ending at entry. */
+ uint8_t first; /**< First value in entry's entire record. */
+ uint16_t count; /**< Count of values in this entry's record. */
+ uint16_t extends; /**< Offset in table to previous entry. */
};
/**
* LZW decompression context.
*/
struct lzw_ctx {
- /** Input reading context */
- struct lzw_read_ctx input;
+ struct lzw_read_ctx input; /**< Input reading context */
- uint32_t previous_code; /**< Code read from input previously. */
- uint32_t previous_code_first; /**< First value of previous code. */
+ uint16_t prev_code; /**< Code read from input previously. */
+ uint16_t prev_code_first; /**< First value of previous code. */
+ uint16_t prev_code_count; /**< Total values for previous code. */
- uint32_t initial_code_size; /**< Starting LZW code size. */
- uint32_t current_code_size; /**< Current LZW code size. */
- uint32_t current_code_size_max; /**< Max code value for current size. */
+ uint8_t initial_code_size; /**< Starting LZW code size. */
- uint32_t clear_code; /**< Special Clear code value */
- uint32_t eoi_code; /**< Special End of Information code value */
+ uint8_t code_size; /**< Current LZW code size. */
+ uint16_t code_max; /**< Max code value for current code size. */
- uint32_t current_entry; /**< Next position in table to fill. */
+ uint16_t clear_code; /**< Special Clear code value */
+ uint16_t eoi_code; /**< Special End of Information code value */
- /** Output value stack. */
- uint8_t stack_base[1 << LZW_CODE_MAX];
+ uint16_t table_size; /**< Next position in table to fill. */
- /** LZW decode dictionary. Generated during decode. */
- struct lzw_dictionary_entry table[1 << LZW_CODE_MAX];
-};
+ uint16_t output_code; /**< Code that has been partially output. */
+ uint16_t output_left; /**< Number of values left for output_code. */
+
+ bool has_transparency; /**< Whether the image is opaque. */
+ uint8_t transparency_idx; /**< Index representing transparency. */
+ const uint32_t *restrict colour_map; /**< Index to colour mapping. */
+ /** LZW code table. Generated during decode. */
+ struct lzw_table_entry table[LZW_TABLE_ENTRY_MAX];
+
+ /** Output value stack. */
+ uint8_t stack_base[LZW_TABLE_ENTRY_MAX];
+};
/* Exported function, documented in lzw.h */
lzw_result lzw_context_create(struct lzw_ctx **ctx)
@@ -97,24 +108,22 @@ lzw_result lzw_context_create(struct lzw_ctx **ctx)
return LZW_OK;
}
-
/* Exported function, documented in lzw.h */
void lzw_context_destroy(struct lzw_ctx *ctx)
{
free(ctx);
}
-
/**
* Advance the context to the next sub-block in the input data.
*
* \param[in] ctx LZW reading context, updated on success.
* \return LZW_OK or LZW_OK_EOD on success, appropriate error otherwise.
*/
-static lzw_result lzw__block_advance(struct lzw_read_ctx *ctx)
+static lzw_result lzw__block_advance(struct lzw_read_ctx *restrict ctx)
{
- uint32_t block_size;
- uint32_t next_block_pos = ctx->data_sb_next;
+ size_t block_size;
+ size_t next_block_pos = ctx->data_sb_next;
const uint8_t *data_next = ctx->data + next_block_pos;
if (next_block_pos >= ctx->data_len) {
@@ -141,7 +150,6 @@ static lzw_result lzw__block_advance(struct lzw_read_ctx *ctx)
return LZW_OK;
}
-
/**
* Get the next LZW code of given size from the raw input data.
*
@@ -152,31 +160,27 @@ static lzw_result lzw__block_advance(struct lzw_read_ctx *ctx)
* \param[out] code_out Returns an LZW code on success.
* \return LZW_OK or LZW_OK_EOD on success, appropriate error otherwise.
*/
-static inline lzw_result lzw__next_code(
- struct lzw_read_ctx *ctx,
- uint8_t code_size,
- uint32_t *code_out)
+static inline lzw_result lzw__read_code(
+ struct lzw_read_ctx *restrict ctx,
+ uint16_t code_size,
+ uint16_t *restrict code_out)
{
uint32_t code = 0;
- uint8_t current_bit = ctx->sb_bit & 0x7;
- uint8_t byte_advance = (current_bit + code_size) >> 3;
+ uint32_t current_bit = ctx->sb_bit & 0x7;
- assert(byte_advance <= 2);
-
- if (ctx->sb_bit + code_size <= ctx->sb_bit_count) {
- /* Fast path: code fully inside this sub-block */
+ if (ctx->sb_bit + 24 <= ctx->sb_bit_count) {
+ /* Fast path: read three bytes from this sub-block */
const uint8_t *data = ctx->sb_data + (ctx->sb_bit >> 3);
- switch (byte_advance) {
- case 2: code |= data[2] << 16; /* Fall through */
- case 1: code |= data[1] << 8; /* Fall through */
- case 0: code |= data[0] << 0;
- }
+ code |= *data++ << 0;
+ code |= *data++ << 8;
+ code |= *data << 16;
ctx->sb_bit += code_size;
} else {
/* Slow path: code spans sub-blocks */
+ uint8_t byte_advance = (current_bit + code_size) >> 3;
uint8_t byte = 0;
- uint8_t bits_remaining_0 = (code_size < (8 - current_bit)) ?
- code_size : (8 - current_bit);
+ uint8_t bits_remaining_0 = (code_size < (8u - current_bit)) ?
+ code_size : (8u - current_bit);
uint8_t bits_remaining_1 = code_size - bits_remaining_0;
uint8_t bits_used[3] = {
[0] = bits_remaining_0,
@@ -184,6 +188,8 @@ static inline lzw_result lzw__next_code(
[2] = bits_remaining_1 - 8,
};
+ assert(byte_advance <= 2);
+
while (true) {
const uint8_t *data = ctx->sb_data;
lzw_result res;
@@ -213,165 +219,395 @@ static inline lzw_result lzw__next_code(
return LZW_OK;
}
-
/**
- * Clear LZW code dictionary.
+ * Handle clear code.
*
- * \param[in] ctx LZW reading context, updated.
- * \param[out] stack_pos_out Returns current stack position.
+ * \param[in] ctx LZW reading context, updated.
+ * \param[out] code_out Returns next code after a clear code.
* \return LZW_OK or error code.
*/
-static lzw_result lzw__clear_codes(
+static inline lzw_result lzw__handle_clear(
struct lzw_ctx *ctx,
- const uint8_t ** const stack_pos_out)
+ uint16_t *code_out)
{
- uint32_t code;
- uint8_t *stack_pos;
+ uint16_t code;
- /* Reset dictionary building context */
- ctx->current_code_size = ctx->initial_code_size + 1;
- ctx->current_code_size_max = (1 << ctx->current_code_size) - 1;;
- ctx->current_entry = (1 << ctx->initial_code_size) + 2;
+ /* Reset table building context */
+ ctx->code_size = ctx->initial_code_size;
+ ctx->code_max = (1 << ctx->initial_code_size) - 1;
+ ctx->table_size = ctx->eoi_code + 1;
/* There might be a sequence of clear codes, so process them all */
do {
- lzw_result res = lzw__next_code(&ctx->input,
- ctx->current_code_size, &code);
+ lzw_result res = lzw__read_code(&ctx->input,
+ ctx->code_size, &code);
if (res != LZW_OK) {
return res;
}
} while (code == ctx->clear_code);
- /* The initial code must be from the initial dictionary. */
+ /* The initial code must be from the initial table. */
if (code > ctx->clear_code) {
return LZW_BAD_ICODE;
}
- /* Record this initial code as "previous" code, needed during decode. */
- ctx->previous_code = code;
- ctx->previous_code_first = code;
-
- /* Reset the stack, and add first non-clear code added as first item. */
- stack_pos = ctx->stack_base;
- *stack_pos++ = code;
-
- *stack_pos_out = stack_pos;
+ *code_out = code;
return LZW_OK;
}
-
/* Exported function, documented in lzw.h */
lzw_result lzw_decode_init(
struct lzw_ctx *ctx,
- const uint8_t *compressed_data,
- uint32_t compressed_data_len,
- uint32_t compressed_data_pos,
- uint8_t code_size,
- const uint8_t ** const stack_base_out,
- const uint8_t ** const stack_pos_out)
+ uint8_t minimum_code_size,
+ const uint8_t *input_data,
+ size_t input_length,
+ size_t input_pos)
{
- struct lzw_dictionary_entry *table = ctx->table;
+ struct lzw_table_entry *table = ctx->table;
+ lzw_result res;
+ uint16_t code;
+
+ if (minimum_code_size >= LZW_CODE_MAX) {
+ return LZW_BAD_ICODE;
+ }
/* Initialise the input reading context */
- ctx->input.data = compressed_data;
- ctx->input.data_len = compressed_data_len;
- ctx->input.data_sb_next = compressed_data_pos;
+ ctx->input.data = input_data;
+ ctx->input.data_len = input_length;
+ ctx->input.data_sb_next = input_pos;
ctx->input.sb_bit = 0;
ctx->input.sb_bit_count = 0;
- /* Initialise the dictionary building context */
- ctx->initial_code_size = code_size;
+ /* Initialise the table building context */
+ ctx->initial_code_size = minimum_code_size + 1;
- ctx->clear_code = (1 << code_size) + 0;
- ctx->eoi_code = (1 << code_size) + 1;
+ ctx->clear_code = (1 << minimum_code_size) + 0;
+ ctx->eoi_code = (1 << minimum_code_size) + 1;
- /* Initialise the standard dictionary entries */
- for (uint32_t i = 0; i < ctx->clear_code; ++i) {
- table[i].first_value = i;
- table[i].last_value = i;
+ ctx->output_left = 0;
+
+ /* Initialise the standard table entries */
+ for (uint16_t i = 0; i < ctx->clear_code; i++) {
+ table[i].first = i;
+ table[i].value = i;
+ table[i].count = 1;
}
- *stack_base_out = ctx->stack_base;
- return lzw__clear_codes(ctx, stack_pos_out);
-}
+ res = lzw__handle_clear(ctx, &code);
+ if (res != LZW_OK) {
+ return res;
+ }
+
+ /* Store details of this code as "previous code" to the context. */
+ ctx->prev_code_first = ctx->table[code].first;
+ ctx->prev_code_count = ctx->table[code].count;
+ ctx->prev_code = code;
+
+ /* Add code to context for immediate output. */
+ ctx->output_code = code;
+ ctx->output_left = 1;
+ ctx->has_transparency = false;
+ ctx->transparency_idx = 0;
+ ctx->colour_map = NULL;
+
+ return LZW_OK;
+}
/* Exported function, documented in lzw.h */
-lzw_result lzw_decode(struct lzw_ctx *ctx,
- const uint8_t ** const stack_pos_out)
+lzw_result lzw_decode_init_map(
+ struct lzw_ctx *ctx,
+ uint8_t minimum_code_size,
+ uint32_t transparency_idx,
+ const uint32_t *colour_table,
+ const uint8_t *input_data,
+ size_t input_length,
+ size_t input_pos)
+{
+ lzw_result res;
+
+ if (colour_table == NULL) {
+ return LZW_BAD_PARAM;
+ }
+
+ res = lzw_decode_init(ctx, minimum_code_size,
+ input_data, input_length, input_pos);
+ if (res != LZW_OK) {
+ return res;
+ }
+
+ ctx->has_transparency = (transparency_idx <= 0xFF);
+ ctx->transparency_idx = transparency_idx;
+ ctx->colour_map = colour_table;
+
+ return LZW_OK;
+}
+
+/**
+ * Create new table entry.
+ *
+ * \param[in] ctx LZW reading context, updated.
+ * \param[in] code Last value code for new table entry.
+ */
+static inline void lzw__table_add_entry(
+ struct lzw_ctx *ctx,
+ uint16_t code)
+{
+ struct lzw_table_entry *entry = &ctx->table[ctx->table_size];
+
+ entry->value = code;
+ entry->first = ctx->prev_code_first;
+ entry->count = ctx->prev_code_count + 1;
+ entry->extends = ctx->prev_code;
+
+ ctx->table_size++;
+}
+
+typedef uint32_t (*lzw_writer_fn)(
+ struct lzw_ctx *ctx,
+ void *restrict output_data,
+ uint32_t output_length,
+ uint32_t output_pos,
+ uint16_t code,
+ uint16_t left);
+
+/**
+ * Get the next LZW code and write its value(s) to output buffer.
+ *
+ * \param[in] ctx LZW reading context, updated.
+ * \param[in] write_fn Function for writing pixels to output.
+ * \param[in] output_data Array to write output values into.
+ * \param[in] output_length Size of output array.
+ * \param[in,out] output_written Number of values written. Updated on exit.
+ * \return LZW_OK on success, or appropriate error code otherwise.
+ */
+static inline lzw_result lzw__decode(
+ struct lzw_ctx *ctx,
+ lzw_writer_fn write_fn,
+ void *restrict output_data,
+ uint32_t output_length,
+ uint32_t *restrict output_written)
{
lzw_result res;
- uint32_t code_new;
- uint32_t code_out;
- uint8_t last_value;
- uint8_t *stack_pos = ctx->stack_base;
- uint32_t clear_code = ctx->clear_code;
- uint32_t current_entry = ctx->current_entry;
- struct lzw_dictionary_entry * const table = ctx->table;
+ uint16_t code;
/* Get a new code from the input */
- res = lzw__next_code(&ctx->input, ctx->current_code_size, &code_new);
+ res = lzw__read_code(&ctx->input, ctx->code_size, &code);
if (res != LZW_OK) {
return res;
}
/* Handle the new code */
- if (code_new == clear_code) {
- /* Got Clear code */
- return lzw__clear_codes(ctx, stack_pos_out);
-
- } else if (code_new == ctx->eoi_code) {
+ if (code == ctx->eoi_code) {
/* Got End of Information code */
return LZW_EOI_CODE;
- } else if (code_new > current_entry) {
+ } else if (code > ctx->table_size) {
/* Code is invalid */
return LZW_BAD_CODE;
- } else if (code_new < current_entry) {
- /* Code is in table */
- code_out = code_new;
- last_value = table[code_new].first_value;
+ } else if (code == ctx->clear_code) {
+ res = lzw__handle_clear(ctx, &code);
+ if (res != LZW_OK) {
+ return res;
+ }
+
+ } else if (ctx->table_size < LZW_TABLE_ENTRY_MAX) {
+ uint16_t size = ctx->table_size;
+ lzw__table_add_entry(ctx, (code < size) ?
+ ctx->table[code].first :
+ ctx->prev_code_first);
+
+ /* Ensure code size is increased, if needed. */
+ if (size == ctx->code_max && ctx->code_size < LZW_CODE_MAX) {
+ ctx->code_size++;
+ ctx->code_max = (1 << ctx->code_size) - 1;
+ }
+ }
+
+ *output_written += write_fn(ctx,
+ output_data, output_length, *output_written,
+ code, ctx->table[code].count);
+
+ /* Store details of this code as "previous code" to the context. */
+ ctx->prev_code_first = ctx->table[code].first;
+ ctx->prev_code_count = ctx->table[code].count;
+ ctx->prev_code = code;
+
+ return LZW_OK;
+}
+
+/**
+ * Write values for this code to the output stack.
+ *
+ * If there isn't enough space in the output stack, this function will write
+ * the as many as it can into the output. If `ctx->output_left > 0` after
+ * this call, then there is more data for this code left to output. The code
+ * is stored to the context as `ctx->output_code`.
+ *
+ * \param[in] ctx LZW reading context, updated.
+ * \param[in] output_data Array to write output values into.
+ * \param[in] output_length length Size of output array.
+ * \param[in] output_used Current position in output array.
+ * \param[in] code LZW code to output values for.
+ * \param[in] left Number of values remaining to output for this code.
+ * \return Number of pixel values written.
+ */
+static inline uint32_t lzw__write_fn(struct lzw_ctx *ctx,
+ void *restrict output_data,
+ uint32_t output_length,
+ uint32_t output_used,
+ uint16_t code,
+ uint16_t left)
+{
+ uint8_t *restrict output_pos = (uint8_t *)output_data + output_used;
+ const struct lzw_table_entry * const table = ctx->table;
+ uint32_t space = output_length - output_used;
+ uint16_t count = left;
+
+ if (count > space) {
+ left = count - space;
+ count = space;
} else {
- /* Code not in table */
- *stack_pos++ = ctx->previous_code_first;
- code_out = ctx->previous_code;
- last_value = ctx->previous_code_first;
+ left = 0;
}
- /* Add to the dictionary, only if there's space */
- if (current_entry < (1 << LZW_CODE_MAX)) {
- struct lzw_dictionary_entry *entry = table + current_entry;
- entry->last_value = last_value;
- entry->first_value = ctx->previous_code_first;
- entry->previous_entry = ctx->previous_code;
- ctx->current_entry++;
+ ctx->output_code = code;
+ ctx->output_left = left;
+
+ /* Skip over any values we don't have space for. */
+ for (unsigned i = left; i != 0; i--) {
+ const struct lzw_table_entry *entry = table + code;
+ code = entry->extends;
+ }
+
+ output_pos += count;
+ for (unsigned i = count; i != 0; i--) {
+ const struct lzw_table_entry *entry = table + code;
+ *--output_pos = entry->value;
+ code = entry->extends;
+ }
+
+ return count;
+}
+
+/* Exported function, documented in lzw.h */
+lzw_result lzw_decode(struct lzw_ctx *ctx,
+ const uint8_t *restrict *const restrict output_data,
+ uint32_t *restrict output_written)
+{
+ const uint32_t output_length = sizeof(ctx->stack_base);
+
+ *output_written = 0;
+ *output_data = ctx->stack_base;
+
+ if (ctx->output_left != 0) {
+ *output_written += lzw__write_fn(ctx,
+ ctx->stack_base, output_length, *output_written,
+ ctx->output_code, ctx->output_left);
}
- /* Ensure code size is increased, if needed. */
- if (current_entry == ctx->current_code_size_max) {
- if (ctx->current_code_size < LZW_CODE_MAX) {
- ctx->current_code_size++;
- ctx->current_code_size_max =
- (1 << ctx->current_code_size) - 1;
+ while (*output_written != output_length) {
+ lzw_result res = lzw__decode(ctx, lzw__write_fn,
+ ctx->stack_base, output_length, output_written);
+ if (res != LZW_OK) {
+ return res;
}
}
- /* Store details of this code as "previous code" to the context. */
- ctx->previous_code_first = table[code_new].first_value;
- ctx->previous_code = code_new;
-
- /* Put rest of data for this code on output stack.
- * Note, in the case of "code not in table", the last entry of the
- * current code has already been placed on the stack above. */
- while (code_out > clear_code) {
- struct lzw_dictionary_entry *entry = table + code_out;
- *stack_pos++ = entry->last_value;
- code_out = entry->previous_entry;
+ return LZW_OK;
+}
+
+/**
+ * Write colour mapped values for this code to the output.
+ *
+ * If there isn't enough space in the output stack, this function will write
+ * the as many as it can into the output. If `ctx->output_left > 0` after
+ * this call, then there is more data for this code left to output. The code
+ * is stored to the context as `ctx->output_code`.
+ *
+ * \param[in] ctx LZW reading context, updated.
+ * \param[in] output_data Array to write output values into.
+ * \param[in] output_length Size of output array.
+ * \param[in] output_used Current position in output array.
+ * \param[in] code LZW code to output values for.
+ * \param[in] left Number of values remaining to output for code.
+ * \return Number of pixel values written.
+ */
+static inline uint32_t lzw__map_write_fn(struct lzw_ctx *ctx,
+ void *restrict output_data,
+ uint32_t output_length,
+ uint32_t output_used,
+ uint16_t code,
+ uint16_t left)
+{
+ uint32_t *restrict output_pos = (uint32_t *)output_data + output_used;
+ const struct lzw_table_entry * const table = ctx->table;
+ uint32_t space = output_length - output_used;
+ uint16_t count = left;
+
+ if (count > space) {
+ left = count - space;
+ count = space;
+ } else {
+ left = 0;
+ }
+
+ ctx->output_code = code;
+ ctx->output_left = left;
+
+ for (unsigned i = left; i != 0; i--) {
+ const struct lzw_table_entry *entry = table + code;
+ code = entry->extends;
+ }
+
+ output_pos += count;
+ if (ctx->has_transparency) {
+ for (unsigned i = count; i != 0; i--) {
+ const struct lzw_table_entry *entry = table + code;
+ --output_pos;
+ if (entry->value != ctx->transparency_idx) {
+ *output_pos = ctx->colour_map[entry->value];
+ }
+ code = entry->extends;
+ }
+ } else {
+ for (unsigned i = count; i != 0; i--) {
+ const struct lzw_table_entry *entry = table + code;
+ *--output_pos = ctx->colour_map[entry->value];
+ code = entry->extends;
+ }
+ }
+
+ return count;
+}
+
+/* Exported function, documented in lzw.h */
+lzw_result lzw_decode_map(struct lzw_ctx *ctx,
+ uint32_t *restrict output_data,
+ uint32_t output_length,
+ uint32_t *restrict output_written)
+{
+ *output_written = 0;
+
+ if (ctx->colour_map == NULL) {
+ return LZW_NO_COLOUR;
+ }
+
+ if (ctx->output_left != 0) {
+ *output_written += lzw__map_write_fn(ctx,
+ output_data, output_length, *output_written,
+ ctx->output_code, ctx->output_left);
+ }
+
+ while (*output_written != output_length) {
+ lzw_result res = lzw__decode(ctx, lzw__map_write_fn,
+ output_data, output_length, output_written);
+ if (res != LZW_OK) {
+ return res;
+ }
}
- *stack_pos++ = table[code_out].last_value;
- *stack_pos_out = stack_pos;
return LZW_OK;
}
diff --git a/src/lzw.h b/src/lzw.h
index 385b425..f19432f 100644
--- a/src/lzw.h
+++ b/src/lzw.h
@@ -4,6 +4,7 @@
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2017 Michael Drake <michael.drake@codethink.co.uk>
+ * Copyright 2021 Michael Drake <tlsa@netsurf-browser.org>
*/
#ifndef LZW_H_
@@ -16,15 +17,12 @@
* Decoder for GIF LZW data.
*/
-
/** Maximum LZW code size in bits */
#define LZW_CODE_MAX 12
-
/* Declare lzw internal context structure */
struct lzw_ctx;
-
/** LZW decoding response codes */
typedef enum lzw_result {
LZW_OK, /**< Success */
@@ -32,11 +30,12 @@ typedef enum lzw_result {
LZW_NO_MEM, /**< Error: Out of memory */
LZW_NO_DATA, /**< Error: Out of data */
LZW_EOI_CODE, /**< Error: End of Information code */
+ LZW_NO_COLOUR, /**< Error: No colour map provided. */
LZW_BAD_ICODE, /**< Error: Bad initial LZW code */
+ LZW_BAD_PARAM, /**< Error: Bad function parameter. */
LZW_BAD_CODE, /**< Error: Bad LZW code */
} lzw_result;
-
/**
* Create an LZW decompression context.
*
@@ -58,48 +57,81 @@ void lzw_context_destroy(
/**
* Initialise an LZW decompression context for decoding.
*
- * Caller owns neither `stack_base_out` or `stack_pos_out`.
- *
- * \param[in] ctx The LZW decompression context to initialise.
- * \param[in] compressed_data The compressed data.
- * \param[in] compressed_data_len Byte length of compressed data.
- * \param[in] compressed_data_pos Start position in data. Must be position
- * of a size byte at sub-block start.
- * \param[in] code_size The initial LZW code size to use.
- * \param[out] stack_base_out Returns base of decompressed data stack.
- * \param[out] stack_pos_out Returns current stack position.
- * There are `stack_pos_out - stack_base_out`
- * current stack entries.
+ * \param[in] ctx The LZW decompression context to initialise.
+ * \param[in] minimum_code_size The LZW Minimum Code Size.
+ * \param[in] input_data The compressed data.
+ * \param[in] input_length Byte length of compressed data.
+ * \param[in] input_pos Start position in data. Must be position
+ * of a size byte at sub-block start.
* \return LZW_OK on success, or appropriate error code otherwise.
*/
lzw_result lzw_decode_init(
struct lzw_ctx *ctx,
- const uint8_t *compressed_data,
- uint32_t compressed_data_len,
- uint32_t compressed_data_pos,
- uint8_t code_size,
- const uint8_t ** const stack_base_out,
- const uint8_t ** const stack_pos_out);
+ uint8_t minimum_code_size,
+ const uint8_t *input_data,
+ size_t input_length,
+ size_t input_pos);
/**
- * Fill the LZW stack with decompressed data
+ * Read input codes until end of LZW context owned output buffer.
+ *
+ * Ensure anything in output is used before calling this, as anything
+ * there before this call will be trampled.
*
- * Ensure anything on the stack is used before calling this, as anything
- * on the stack before this call will be trampled.
+ * \param[in] ctx LZW reading context, updated.
+ * \param[out] output_data Returns pointer to array of output values.
+ * \param[out] output_written Returns the number of values written to data.
+ * \return LZW_OK on success, or appropriate error code otherwise.
+ */
+lzw_result lzw_decode(struct lzw_ctx *ctx,
+ const uint8_t *restrict *const restrict output_data,
+ uint32_t *restrict output_written);
+
+/**
+ * Initialise an LZW decompression context for decoding to colour map values.
*
- * Caller does not own `stack_pos_out`.
+ * For transparency to work correctly, the given client buffer must have
+ * the values from the previous frame. The transparency_idx should be a value
+ * of 256 or above, if the frame does not have transparency.
*
- * \param[in] ctx LZW reading context, updated.
- * \param[out] stack_pos_out Returns current stack position.
- * Use with `stack_base_out` value from previous
- * lzw_decode_init() call.
- * There are `stack_pos_out - stack_base_out`
- * current stack entries.
+ * \param[in] ctx The LZW decompression context to initialise.
+ * \param[in] minimum_code_size The LZW Minimum Code Size.
+ * \param[in] transparency_idx Index representing transparency.
+ * \param[in] colour_table Index to pixel colour mapping.
+ * \param[in] input_data The compressed data.
+ * \param[in] input_length Byte length of compressed data.
+ * \param[in] input_pos Start position in data. Must be position
+ * of a size byte at sub-block start.
* \return LZW_OK on success, or appropriate error code otherwise.
*/
-lzw_result lzw_decode(
+lzw_result lzw_decode_init_map(
struct lzw_ctx *ctx,
- const uint8_t ** const stack_pos_out);
+ uint8_t minimum_code_size,
+ uint32_t transparency_idx,
+ const uint32_t *colour_table,
+ const uint8_t *input_data,
+ size_t input_length,
+ size_t input_pos);
+/**
+ * Read LZW codes into client buffer, mapping output to colours.
+ *
+ * The context must have been initialised using \ref lzw_decode_init_map
+ * before calling this function, in order to provide the colour mapping table
+ * and any transparency index.
+ *
+ * Ensure anything in output is used before calling this, as anything
+ * there before this call will be trampled.
+ *
+ * \param[in] ctx LZW reading context, updated.
+ * \param[in] output_data Client buffer to fill with colour mapped values.
+ * \param[in] output_length Size of output array.
+ * \param[out] output_written Returns the number of values written to data.
+ * \return LZW_OK on success, or appropriate error code otherwise.
+ */
+lzw_result lzw_decode_map(struct lzw_ctx *ctx,
+ uint32_t *restrict output_data,
+ uint32_t output_length,
+ uint32_t *restrict output_written);
#endif
diff --git a/src/utils/log.h b/src/utils/log.h
deleted file mode 100644
index 1413374..0000000
--- a/src/utils/log.h
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright 2003 James Bursa <bursa@users.sourceforge.net>
- * Copyright 2004 John Tytgat <John.Tytgat@aaug.net>
- *
- * This file is part of NetSurf, http://www.netsurf-browser.org/
- * Licenced under the MIT License,
- * http://www.opensource.org/licenses/mit-license.php
- */
-
-#include <stdio.h>
-
-#ifndef _LIBNSGIF_LOG_H_
-#define _LIBNSGIF_LOG_H_
-
-#ifdef NDEBUG
-# define LOG(x) ((void) 0)
-#else
-# define LOG(x) do { fprintf(stderr, x), fputc('\n', stderr); } while (0)
-#endif /* NDEBUG */
-
-#endif /* _LIBNSGIF_LOG_H_ */
diff --git a/test/Makefile b/test/Makefile
index f067d81..a578aef 100644
--- a/test/Makefile
+++ b/test/Makefile
@@ -1,3 +1,3 @@
-DIR_TEST_ITEMS := decode_gif:decode_gif.c
+DIR_TEST_ITEMS := nsgif:nsgif.c
include $(NSBUILD)/Makefile.subdir
diff --git a/test/cli.c b/test/cli.c
new file mode 100644
index 0000000..9c095fe
--- /dev/null
+++ b/test/cli.c
@@ -0,0 +1,827 @@
+/*
+ * SPDX-License-Identifier: ISC
+ *
+ * Copyright (C) 2021-2022 Michael Drake <tlsa@netsurf-browser.org>
+ */
+
+/**
+ * \file
+ * \brief Command line argument handling.
+ */
+
+#include <ctype.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "cli.h"
+
+/**
+ * CLI parsing context.
+ */
+struct cli_ctx {
+ const struct cli_table *cli; /**< Client CLI spec. */
+ size_t pos_count; /**< The number of positional arguments found. */
+ bool no_pos; /**< Have an argument that negates min_positional. */
+};
+
+/**
+ * Check whether a CLI argument type should have a numerical value.
+ *
+ * \param[in] type An argument type.
+ * \return true if the argument needs a numerical value, or false otherwise.
+ */
+static inline bool cli__arg_is_numerical(enum cli_arg_type type)
+{
+ return (type != CLI_STRING && type != CLI_BOOL);
+}
+
+/**
+ * Parse a signed integer value from an argument.
+ *
+ * \param[in] str String containing value to parse.
+ * \param[out] i Pointer to place to store parsed value.
+ * \param[in,out] pos Current position in str, updated on exit.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_value_int(
+ const char *str,
+ int64_t *i,
+ size_t *pos)
+{
+ long long temp;
+ char *end = NULL;
+
+ str += *pos;
+ errno = 0;
+ temp = strtoll(str, &end, 0);
+
+ if (end == str || errno == ERANGE ||
+ temp > INT64_MAX || temp < INT64_MIN) {
+ fprintf(stderr, "Failed to parse integer from '%s'\n", str);
+ return false;
+ }
+
+ *i = (int64_t)temp;
+ *pos += (size_t)(end - str);
+ return true;
+}
+
+/**
+ * Parse an unsigned integer value from an argument.
+ *
+ * \param[in] str String containing value to parse.
+ * \param[out] u Pointer to place to store parsed value.
+ * \param[in,out] pos Current position in str, updated on exit.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_value_uint(
+ const char *str,
+ uint64_t *u,
+ size_t *pos)
+{
+ unsigned long long temp;
+ char *end = NULL;
+
+ str += *pos;
+ errno = 0;
+ temp = strtoull(str, &end, 0);
+
+ if (end == str || errno == ERANGE || temp > UINT64_MAX) {
+ fprintf(stderr, "Failed to parse unsigned from '%s'\n", str);
+ return false;
+ }
+
+ *u = (uint64_t)temp;
+ *pos += (size_t)(end - str);
+ return true;
+}
+
+/**
+ * Parse an enum value from an argument.
+ *
+ * \param[in] str String containing value to parse.
+ * \param[out] e Enum details.
+ * \param[in,out] pos Current position in str, updated on exit.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_value_enum(
+ const char *str,
+ const struct cli_enum *e,
+ size_t *pos)
+{
+ str += *pos;
+ *pos += strlen(str);
+
+ for (const struct cli_str_val *sv = e->desc; sv->str != NULL; sv++) {
+ if (strcmp(str, sv->str) == 0) {
+ *e->e = sv->val;
+ return true;
+ }
+ }
+
+ fprintf(stderr, "ERROR: Unknown enum value '%s'.\n", str);
+
+ return false;
+}
+
+/**
+ * Parse a string value from an argument.
+ *
+ * \param[in] str String containing value to parse.
+ * \param[out] s Pointer to place to store parsed value.
+ * \param[in,out] pos Current position in str, updated on exit.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_value_string(
+ const char *str,
+ const char **s,
+ size_t *pos)
+{
+ *s = str + *pos;
+ *pos += strlen(*s);
+ return true;
+}
+
+/**
+ * Parse a value from an argument.
+ *
+ * \param[in] entry Client command line interface argument specification.
+ * \param[in] arg Argument to parse a value from.
+ * \param[in,out] pos Current position in argument, updated on exit.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_value(
+ const struct cli_table_entry *entry,
+ const char *arg,
+ size_t *pos)
+{
+ switch (entry->t) {
+ case CLI_CMD:
+ if (strcmp(arg + *pos, entry->l) == 0) {
+ *pos += strlen(arg);
+ return true;
+ }
+ return false;
+
+ case CLI_INT:
+ return cli__parse_value_int(arg, entry->v.i, pos);
+
+ case CLI_UINT:
+ return cli__parse_value_uint(arg, entry->v.u, pos);
+
+ case CLI_ENUM:
+ return cli__parse_value_enum(arg, &entry->v.e, pos);
+
+ case CLI_STRING:
+ return cli__parse_value_string(arg, entry->v.s, pos);
+
+ default:
+ fprintf(stderr, "Unexpected value for '%s': %s\n",
+ entry->l, arg);
+ break;
+ }
+
+ return false;
+}
+
+/**
+ * Parse a value from an argument.
+ *
+ * \param[in] entry Client command line interface argument specification.
+ * \param[in] argc Number of command line arguments.
+ * \param[in] argv String vector containing command line arguments.
+ * \param[in] arg_pos Current position in argv.
+ * \param[in,out] pos Current pos in current argument, updated on exit.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_argv_value(const struct cli_table_entry *entry,
+ int argc, const char **argv,
+ int arg_pos, size_t *pos)
+{
+ const char *arg = argv[arg_pos];
+
+ if (arg_pos >= argc) {
+ fprintf(stderr, "Value not given for '%s'\n", entry->l);
+ return false;
+ }
+
+ return cli__parse_value(entry, arg, pos);
+}
+
+/**
+ * Check whether a CLI argument is a positional value.
+ *
+ * \param[in] entry Client command line interface argument specification.
+ * \return true if the argument is positional, or false otherwise.
+ */
+static inline bool cli__entry_is_positional(const struct cli_table_entry *entry)
+{
+ return entry->p;
+}
+
+/**
+ * Look up a short argument flag.
+ *
+ * \param[in] cli Client command line interface specification.
+ * \param[in] s Argument flag to look up in client CLI spec.
+ * \return Client CLI spec entry on success, or NULL otherwise.
+ */
+static const struct cli_table_entry *cli__lookup_short(
+ const struct cli_table *cli, char s)
+{
+ for (size_t i = 0; i < cli->count; i++) {
+ if (cli__entry_is_positional(&cli->entries[i])) {
+ continue;
+ }
+ if (cli->entries[i].s == s) {
+ return &cli->entries[i];
+ }
+ }
+
+ fprintf(stderr, "Unknown flag: '%c'\n", s);
+ return NULL;
+}
+
+/**
+ * Handle an argument with a type that requires a value.
+ *
+ * This can handle the value being in the current argument, optionally split by
+ * a separator, or in the next argument.
+ *
+ * \param[in] entry Client command line interface argument specification.
+ * \param[in] argc Number of command line arguments.
+ * \param[in] argv String vector containing command line arguments.
+ * \param[in,out] arg_pos Current position in argv, updated on exit.
+ * \param[in] pos Current position in current argument string.
+ * \param[in] sep Name/value separator character, or '\0' if none.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__handle_arg_value(const struct cli_table_entry *entry,
+ int argc, const char **argv, int *arg_pos, size_t pos, char sep)
+{
+ const char *arg = argv[*arg_pos];
+ size_t orig_pos;
+ bool ret;
+
+ if (arg[pos] == '\0') {
+ (*arg_pos)++;
+ pos = 0;
+ } else if (arg[pos] == sep) {
+ pos++;
+ } else if (cli__arg_is_numerical(entry->t) == false) {
+ fprintf(stderr, "Separator required for non-numerical value\n");
+ return false;
+ }
+
+ if (isspace(argv[*arg_pos][pos])) {
+ fprintf(stderr, "Unexpected white space in '%s' "
+ "for argument '%s'\n",
+ &argv[*arg_pos][pos], entry->l);
+ return false;
+ }
+
+ orig_pos = pos;
+ ret = cli__parse_argv_value(entry, argc, argv, *arg_pos, &pos);
+ if (ret != true) {
+ return ret;
+ }
+
+ if (argv[*arg_pos][pos] != '\0') {
+ fprintf(stderr, "Invalid value '%s' for argument '%s'\n",
+ &argv[*arg_pos][orig_pos], entry->l);
+ return false;
+ }
+
+ return true;
+}
+
+static inline bool cli__is_negative(const char *arg)
+{
+ int64_t i;
+ size_t pos = 0;
+
+ return cli__parse_value_int(arg, &i, &pos)
+ && pos == strlen(arg)
+ && i < 0;
+}
+
+/**
+ * Parse a positional argument according to the given CLI spec entry.
+ *
+ * \param[in] ctx Command line interface parsing context.
+ * \param[in] entry Client command line interface argument specification.
+ * \param[in] arg Argument to parse.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_positional_entry(struct cli_ctx *ctx,
+ const struct cli_table_entry *entry,
+ const char *arg)
+{
+ size_t pos = 0;
+ bool ret;
+
+ ret = cli__parse_value(entry, arg, &pos);
+ if (ret != true) {
+ return ret;
+ } else if (arg[pos] != '\0') {
+ fprintf(stderr, "Failed to parse value '%s' for arg '%s'\n",
+ arg, entry->l);
+ return false;
+ }
+
+ ctx->pos_count++;
+ return true;
+}
+
+/**
+ * Parse a positional argument.
+ *
+ * \param[in] ctx Command line interface parsing context.
+ * \param[in] arg Argument to parse.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_positional(struct cli_ctx *ctx,
+ const char *arg)
+{
+ const struct cli_table *cli = ctx->cli;
+ size_t positional = 0;
+
+ for (size_t i = 0; i < cli->count; i++) {
+ if (cli__entry_is_positional(&cli->entries[i])) {
+ if (positional == ctx->pos_count) {
+ return cli__parse_positional_entry(ctx,
+ &cli->entries[i], arg);
+ }
+
+ positional++;
+ }
+ }
+
+ fprintf(stderr, "Unexpected positional argument: '%s'\n", arg);
+ return false;
+}
+
+/**
+ * Parse a flags argument.
+ *
+ * \param[in] ctx Command line interface parsing context.
+ * \param[in] argc Number of command line arguments.
+ * \param[in] argv String vector containing command line arguments.
+ * \param[out] arg_pos Current position in argv, updated on exit.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_short(struct cli_ctx *ctx,
+ int argc, const char **argv, int *arg_pos)
+{
+ const char *arg = argv[*arg_pos];
+ size_t pos = 1;
+
+ if (arg[0] != '-') {
+ return false;
+ }
+
+ while (arg[pos] != '\0') {
+ const struct cli_table_entry *entry;
+
+ entry = cli__lookup_short(ctx->cli, arg[pos]);
+ if (entry == NULL) {
+ if (cli__is_negative(argv[pos])) {
+ return cli__parse_positional(ctx, argv[pos]);
+ }
+ return false;
+ }
+
+ if (entry->no_pos) {
+ ctx->no_pos = true;
+ }
+
+ if (entry->t == CLI_BOOL) {
+ *entry->v.b = true;
+ } else {
+ return cli__handle_arg_value(entry, argc, argv,
+ arg_pos, pos + 1, '\0');
+ }
+
+ pos++;
+ }
+
+ return true;
+}
+
+/**
+ * Look up a long argument name.
+ *
+ * \param[in] cli Client command line interface specification.
+ * \param[in] arg Argument name to look up in cli spec.
+ * \param[in,out] pos Current position in arg, updated on exit.
+ * \return Client CLI spec entry on success, or NULL otherwise.
+ */
+static const struct cli_table_entry *cli__lookup_long(
+ const struct cli_table *cli,
+ const char *arg,
+ size_t *pos)
+{
+ arg += *pos;
+
+ for (size_t i = 0; i < cli->count; i++) {
+ if (cli__entry_is_positional(&cli->entries[i]) == false) {
+ const char *name = cli->entries[i].l;
+ size_t name_len = strlen(cli->entries[i].l);
+
+ if (strncmp(name, arg, name_len) == 0) {
+ if (arg[name_len] != '\0' &&
+ arg[name_len] != '=') {
+ continue;
+ }
+ *pos += name_len;
+ return &cli->entries[i];
+ }
+ }
+ }
+
+ fprintf(stderr, "Unknown argument: '%s'\n", arg);
+ return NULL;
+}
+
+/**
+ * Parse a long argument.
+ *
+ * \param[in] ctx Command line interface parsing context.
+ * \param[in] argc Number of command line arguments.
+ * \param[in] argv String vector containing command line arguments.
+ * \param[out] arg_pos Current position in argv, updated on exit.
+ * \return true on success, or false otherwise.
+ */
+static bool cli__parse_long(struct cli_ctx *ctx,
+ int argc, const char **argv, int *arg_pos)
+{
+ const struct cli_table_entry *entry;
+ const char *arg = argv[*arg_pos];
+ size_t pos = 2;
+
+ if (arg[0] != '-' ||
+ arg[1] != '-') {
+ return false;
+ }
+
+ entry = cli__lookup_long(ctx->cli, arg, &pos);
+ if (entry == NULL) {
+ return false;
+ }
+
+ if (entry->no_pos) {
+ ctx->no_pos = true;
+ }
+
+ if (entry->t == CLI_BOOL) {
+ if (arg[pos] != '\0') {
+ fprintf(stderr, "Unexpected value for argument '%s'\n",
+ arg);
+ return false;
+ }
+ *entry->v.b = true;
+ } else {
+ bool ret;
+
+ ret = cli__handle_arg_value(entry, argc, argv,
+ arg_pos, pos, '=');
+ if (ret != true) {
+ return ret;
+ }
+ }
+
+ return true;
+}
+
+/**
+ * Get the string to indicate type of value expected for an argument.
+ *
+ * \param[in] type The argument type.
+ * \return String for value type.
+ */
+static const char *cli__string_from_type(enum cli_arg_type type)
+{
+ static const char *const strings[] = {
+ [CLI_BOOL] = "",
+ [CLI_INT] = "INT",
+ [CLI_UINT] = "UINT",
+ [CLI_ENUM] = "ENUM",
+ [CLI_STRING] = "STRING",
+ };
+
+ if (type >= CLI_ARRAY_LEN(strings) || strings[type] == NULL) {
+ return "";
+ }
+
+ return strings[type];
+}
+
+/**
+ * Helper to update a maximum adjusted string length if new values is greater.
+ *
+ * \param[in] str String to check.
+ * \param[in] adjustment Amount to modify length of string by (bytes).
+ * \param[out] len Returns the maximum of existing and this length.
+ */
+static void cli__max_len(const char *str, size_t adjustment, size_t *len)
+{
+ size_t str_len = strlen(str) + adjustment;
+
+ if (str_len > *len) {
+ *len = str_len;
+ }
+}
+
+/**
+ * Count up various properties of the client CLI interface specification.
+ *
+ * \param[in] cli Client command line interface specification.
+ * \param[out] count Returns number of non-positional arguments.
+ * \param[out] pcount Returns number of positional arguments.
+ * \param[out] max_len Returns max string length of non-positional arguments.
+ * \param[out] pmax_len Returns max string length of positional arguments.
+ * \param[out] phas_desc Returns number of positional args with descriptions.
+ */
+static void cli__count(const struct cli_table *cli,
+ size_t *count,
+ size_t *pcount,
+ size_t *max_len,
+ size_t *pmax_len,
+ size_t *phas_desc)
+{
+ if (count != NULL) *count = 0;
+ if (pcount != NULL) *pcount = 0;
+ if (max_len != NULL) *max_len = 0;
+ if (pmax_len != NULL) *pmax_len = 0;
+ if (phas_desc != NULL) *phas_desc = 0;
+
+ for (size_t i = 0; i < cli->count; i++) {
+ const struct cli_table_entry *entry = &cli->entries[i];
+
+ if (cli__entry_is_positional(entry)) {
+ if (pcount != NULL) {
+ (*pcount)++;
+ }
+ if (pmax_len != NULL) {
+ cli__max_len(entry->l, 0, pmax_len);
+ }
+ if (phas_desc != NULL) {
+ (*phas_desc)++;
+ }
+ } else {
+ if (count != NULL) {
+ (*count)++;
+ }
+ if (max_len != NULL) {
+ const char *type_str;
+ size_t type_len;
+
+ type_str = cli__string_from_type(entry->t);
+ type_len = strlen(type_str);
+
+ cli__max_len(entry->l, type_len, max_len);
+ }
+ }
+ }
+}
+
+/* Documented in cli.h */
+bool cli_parse(const struct cli_table *cli, int argc, const char **argv)
+{
+ struct cli_ctx ctx = {
+ .cli = cli,
+ };
+ enum {
+ ARG_PROG_NAME,
+ ARG_FIRST,
+ };
+
+ for (int i = ARG_FIRST; i < argc; i++) {
+ const char *arg = argv[i];
+ bool ret;
+
+ if (arg[0] == '-') {
+ if (arg[1] == '-') {
+ ret = cli__parse_long(&ctx, argc, argv, &i);
+ } else {
+ ret = cli__parse_short(&ctx, argc, argv, &i);
+ }
+ } else {
+ ret = cli__parse_positional(&ctx, argv[i]);
+ }
+
+ if (ret != true) {
+ return ret;
+ }
+ }
+
+ if (ctx.no_pos == false && ctx.pos_count < cli->min_positional) {
+ fprintf(stderr, "Insufficient positional arguments found.\n");
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * Get terminal width.
+ *
+ * \return terminal width in characters.
+ */
+static size_t cli__terminal_width(void)
+{
+ return 80;
+}
+
+/**
+ * Print a wrapped string, with a given indent.
+ *
+ * The indent is assumed to already be applied for the first line of the
+ * output by the caller.
+ *
+ * \param[in] str The string to print.
+ * \param[in] indent The number of spaces to pad the left margin with.
+ */
+static void cli__print_wrapping_string(const char *str, size_t indent)
+{
+ size_t terminal_width = cli__terminal_width();
+ size_t avail = (indent > terminal_width) ? 0 : terminal_width - indent;
+ size_t space = avail;
+
+ while (*str != '\0') {
+ size_t word_len = strcspn(str, " \n\t");
+ if (word_len <= space || space == avail) {
+ fprintf(stderr, "%*.*s",
+ (int)word_len,
+ (int)word_len, str);
+ str += word_len;
+ if (word_len <= space) {
+ space -= word_len;
+ }
+ if (space > 0) {
+ fprintf(stderr, " ");
+ space--;
+ }
+ } else {
+ fprintf(stderr, "\n%*s", (int)indent, "");
+ space = avail;
+ }
+ str += strspn(str, " \n\t");
+ }
+}
+
+/**
+ * Print an entry's description, with a given indent.
+ *
+ * The indent is assumed to already be applied for the first line of the
+ * output by the caller.
+ *
+ * \param[in] entry The entry to print the description for.
+ * \param[in] indent The number of spaces to pad the left margin with.
+ */
+static void cli__print_description(const struct cli_table_entry *entry,
+ size_t indent)
+{
+ if (entry->d != NULL) {
+ cli__print_wrapping_string(entry->d, indent);
+ }
+
+ fprintf(stderr, "\n");
+
+ if (entry->t == CLI_ENUM) {
+ size_t max_len = 0;
+
+ for (const struct cli_str_val *e = entry->v.e.desc;
+ e->str != NULL; e++) {
+ size_t len = strlen(e->str);
+ if (max_len < len) {
+ max_len = len;
+ }
+ }
+
+ fprintf(stderr, "\n");
+
+ for (const struct cli_str_val *e = entry->v.e.desc;
+ e->str != NULL; e++) {
+ fprintf(stderr, " ");
+
+ if (e->d == NULL || e->d[0] == '\0') {
+ fprintf(stderr, "%s\n",
+ e->str);
+ } else {
+ fprintf(stderr, "%-*s - ",
+ (int)(max_len),
+ e->str);
+ cli__print_wrapping_string(e->d,
+ 8 + max_len + 3);
+ fprintf(stderr, "\n");
+ }
+ }
+ }
+}
+
+/* Documented in cli.h */
+void cli_help(const struct cli_table *cli, const char *prog_name)
+{
+ size_t count;
+ size_t pcount;
+ size_t max_len;
+ size_t pmax_len;
+ size_t phas_desc;
+ size_t required = 0;
+ enum {
+ ARG_PROG_NAME,
+ };
+
+ cli__count(cli, &count, &pcount, &max_len, &pmax_len, &phas_desc);
+
+ if (cli->d != NULL) {
+ fprintf(stderr, "\n");
+ cli__print_wrapping_string(cli->d, 0);
+ fprintf(stderr, "\n");
+ }
+
+ fprintf(stderr, "\nUsage: %s", prog_name);
+
+ if (pcount > 0) {
+ for (size_t i = 0; i < cli->count; i++) {
+ if (cli__entry_is_positional(&cli->entries[i])) {
+ const char *punctuation =
+ (required == cli->min_positional) ?
+ " [" : " ";
+
+ if (cli->entries[i].t == CLI_CMD) {
+ fprintf(stderr, "%s%s", punctuation,
+ cli->entries[i].l);
+ } else {
+ fprintf(stderr, "%s<%s>", punctuation,
+ cli->entries[i].l);
+ }
+ required++;
+ }
+ }
+ if (required == pcount && required > cli->min_positional) {
+ fprintf(stderr, "]");
+ }
+ }
+
+ if (count > 0) {
+ fprintf(stderr, " [options]");
+ }
+
+ fprintf(stderr, "\n\n");
+
+ if (phas_desc > 0) {
+ fprintf(stderr, "Where:\n\n");
+
+ for (size_t i = 0; i < cli->count; i++) {
+ const struct cli_table_entry *entry = &cli->entries[i];
+
+ if (entry->d == NULL) {
+ continue;
+ }
+
+ if (cli__entry_is_positional(entry)) {
+ fprintf(stderr, " %*.*s ",
+ (int)pmax_len,
+ (int)pmax_len,
+ entry->l);
+ cli__print_description(entry, pmax_len + 4);
+ fprintf(stderr, "\n");
+ }
+ }
+ }
+
+ if (count > 0) {
+ fprintf(stderr, "Options:\n\n");
+
+ for (size_t i = 0; i < cli->count; i++) {
+ const struct cli_table_entry *entry = &cli->entries[i];
+ const char *type_str;
+ size_t type_len;
+ size_t arg_len;
+
+ if (cli__entry_is_positional(entry)) {
+ continue;
+ }
+
+ if (entry->s != '\0') {
+ fprintf(stderr, " -%c", entry->s);
+ } else {
+ fprintf(stderr, " ");
+ }
+
+ type_str = cli__string_from_type(entry->t);
+ type_len = strlen(type_str);
+ arg_len = strlen(entry->l);
+
+ fprintf(stderr, " --%s %s%*.s ", entry->l, type_str,
+ (int)(max_len - arg_len - type_len),
+ "");
+ cli__print_description(entry, max_len + 11);
+ fprintf(stderr, "\n");
+ }
+ }
+}
diff --git a/test/cli.h b/test/cli.h
new file mode 100644
index 0000000..ffcd272
--- /dev/null
+++ b/test/cli.h
@@ -0,0 +1,99 @@
+/*
+ * SPDX-License-Identifier: ISC
+ *
+ * Copyright (C) 2021-2022 Michael Drake <tlsa@netsurf-browser.org>
+ */
+
+/**
+ * \file
+ * \brief Command line argument handling API.
+ */
+
+#ifndef _PELTAR_CLI_H_
+#define _PELTAR_CLI_H_
+
+#include <stdint.h>
+#include <stdbool.h>
+
+/**
+ * Helper to get element count for an array,
+ *
+ * \param[in] _a Array to get number of elements for.
+ */
+#define CLI_ARRAY_LEN(_a) ((sizeof(_a))/(sizeof(*(_a))))
+
+/**
+ * CLI argument type.
+ */
+enum cli_arg_type {
+ CLI_CMD, /**< A sub-command. Must match long argument name. */
+ CLI_BOOL, /**< Has no value; presence of flag indicates true. */
+ CLI_INT, /**< Has signed integer value. */
+ CLI_UINT, /**< Has unsigned integer value. */
+ CLI_ENUM, /**< Has enumeration value. */
+ CLI_STRING, /**< Has string value. */
+};
+
+/** Enum value descriptor. */
+struct cli_str_val {
+ const char *str; /**< String for the enum value name. */
+ int64_t val; /**< The value for this string. */
+ const char *d; /**< Description of this value for help output. */
+};
+
+/** Enum data. */
+struct cli_enum {
+ const struct cli_str_val *desc; /**< Array describing enum values. */
+ int64_t *e; /**< Location to store \ref CLI_ENUM value. */
+};
+
+/**
+ * Client description for a command line argument.
+ */
+struct cli_table_entry {
+ const char *l; /**< Long argument name. */
+ const char s; /**< Short flag name. (Non-positional arguments.) */
+ bool p; /**< Whether the argument is a positional argument. */
+ bool no_pos; /**< When present, no positional arguments are required. */
+ enum cli_arg_type t; /**< Argument type. */
+ union {
+ bool *b; /**< Location to store \ref CLI_BOOL value. */
+ int64_t *i; /**< Location to store \ref CLI_INT value. */
+ uint64_t *u; /**< Location to store \ref CLI_UINT value. */
+ const char **s; /**< Location to store \ref CLI_STRING value. */
+ struct cli_enum e; /**< \ref CLI_ENUM value details. */
+ } v; /**< Where to store type-specific values. */
+ const char *d; /**< Description of this argument for help output. */
+};
+
+/**
+ * Client command line interface specification.
+ */
+struct cli_table {
+ const struct cli_table_entry *entries;
+ size_t count;
+ size_t min_positional;
+ const char *d; /**< Description of this application for help output. */
+};
+
+/**
+ * Parse the command line arguments.
+ *
+ * \param[in] cli Client command line interface specification.
+ * \param[in] argc Number of command line arguments.
+ * \param[in] argv String vector containing command line arguments.
+ * \return true on success, false on error.
+ */
+bool cli_parse(const struct cli_table *cli, int argc, const char **argv);
+
+/**
+ * Print usage and help output.
+ *
+ * Note: Assumes non-Unicode. (One byte per character.)
+ *
+ * \param[in] cli Client command line interface specification.
+ * \param[in] prog_name Program name.
+ */
+void cli_help(const struct cli_table *cli, const char *prog_name);
+
+#endif
diff --git a/test/decode_gif.c b/test/decode_gif.c
deleted file mode 100644
index 619be29..0000000
--- a/test/decode_gif.c
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * Copyright 2008 Sean Fox <dyntryx@gmail.com>
- * Copyright 2008 James Bursa <james@netsurf-browser.org>
- *
- * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/
- * Licenced under the MIT License,
- * http://www.opensource.org/licenses/mit-license.php
- */
-
-#include <assert.h>
-#include <errno.h>
-#include <stdbool.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-
-#include "../include/libnsgif.h"
-
-#define BYTES_PER_PIXEL 4
-#define MAX_IMAGE_BYTES (48 * 1024 * 1024)
-
-
-static void *bitmap_create(int width, int height)
-{
- /* ensure a stupidly large bitmap is not created */
- if (((long long)width * (long long)height) > (MAX_IMAGE_BYTES/BYTES_PER_PIXEL)) {
- return NULL;
- }
- return calloc(width * height, BYTES_PER_PIXEL);
-}
-
-
-static void bitmap_set_opaque(void *bitmap, bool opaque)
-{
- (void) opaque; /* unused */
- (void) bitmap; /* unused */
- assert(bitmap);
-}
-
-
-static bool bitmap_test_opaque(void *bitmap)
-{
- (void) bitmap; /* unused */
- assert(bitmap);
- return false;
-}
-
-
-static unsigned char *bitmap_get_buffer(void *bitmap)
-{
- assert(bitmap);
- return bitmap;
-}
-
-
-static void bitmap_destroy(void *bitmap)
-{
- assert(bitmap);
- free(bitmap);
-}
-
-
-static void bitmap_modified(void *bitmap)
-{
- (void) bitmap; /* unused */
- assert(bitmap);
- return;
-}
-
-static unsigned char *load_file(const char *path, size_t *data_size)
-{
- FILE *fd;
- struct stat sb;
- unsigned char *buffer;
- size_t size;
- size_t n;
-
- fd = fopen(path, "rb");
- if (!fd) {
- perror(path);
- exit(EXIT_FAILURE);
- }
-
- if (stat(path, &sb)) {
- perror(path);
- exit(EXIT_FAILURE);
- }
- size = sb.st_size;
-
- buffer = malloc(size);
- if (!buffer) {
- fprintf(stderr, "Unable to allocate %lld bytes\n",
- (long long) size);
- exit(EXIT_FAILURE);
- }
-
- n = fread(buffer, 1, size, fd);
- if (n != size) {
- perror(path);
- exit(EXIT_FAILURE);
- }
-
- fclose(fd);
-
- *data_size = size;
- return buffer;
-}
-
-
-static void warning(const char *context, gif_result code)
-{
- fprintf(stderr, "%s failed: ", context);
- switch (code)
- {
- case GIF_INSUFFICIENT_FRAME_DATA:
- fprintf(stderr, "GIF_INSUFFICIENT_FRAME_DATA");
- break;
- case GIF_FRAME_DATA_ERROR:
- fprintf(stderr, "GIF_FRAME_DATA_ERROR");
- break;
- case GIF_INSUFFICIENT_DATA:
- fprintf(stderr, "GIF_INSUFFICIENT_DATA");
- break;
- case GIF_DATA_ERROR:
- fprintf(stderr, "GIF_DATA_ERROR");
- break;
- case GIF_INSUFFICIENT_MEMORY:
- fprintf(stderr, "GIF_INSUFFICIENT_MEMORY");
- break;
- default:
- fprintf(stderr, "unknown code %i", code);
- break;
- }
- fprintf(stderr, "\n");
-}
-
-static void write_ppm(FILE* fh, const char *name, gif_animation *gif,
- bool no_write)
-{
- unsigned int i;
- gif_result code;
-
- if (!no_write) {
- fprintf(fh, "P3\n");
- fprintf(fh, "# %s\n", name);
- fprintf(fh, "# width %u \n", gif->width);
- fprintf(fh, "# height %u \n", gif->height);
- fprintf(fh, "# frame_count %u \n", gif->frame_count);
- fprintf(fh, "# frame_count_partial %u \n", gif->frame_count_partial);
- fprintf(fh, "# loop_count %u \n", gif->loop_count);
- fprintf(fh, "%u %u 256\n", gif->width, gif->height * gif->frame_count);
- }
-
- /* decode the frames */
- for (i = 0; i != gif->frame_count; i++) {
- unsigned int row, col;
- unsigned char *image;
-
- code = gif_decode_frame(gif, i);
- if (code != GIF_OK)
- warning("gif_decode_frame", code);
-
- if (!no_write) {
- fprintf(fh, "# frame %u:\n", i);
- image = (unsigned char *) gif->frame_image;
- for (row = 0; row != gif->height; row++) {
- for (col = 0; col != gif->width; col++) {
- size_t z = (row * gif->width + col) * 4;
- fprintf(fh, "%u %u %u ",
- (unsigned char) image[z],
- (unsigned char) image[z + 1],
- (unsigned char) image[z + 2]);
- }
- fprintf(fh, "\n");
- }
- }
- }
-
-}
-
-int main(int argc, char *argv[])
-{
- gif_bitmap_callback_vt bitmap_callbacks = {
- bitmap_create,
- bitmap_destroy,
- bitmap_get_buffer,
- bitmap_set_opaque,
- bitmap_test_opaque,
- bitmap_modified
- };
- gif_animation gif;
- size_t size;
- gif_result code;
- unsigned char *data;
- FILE *outf = stdout;
- bool no_write = false;
-
- if (argc < 2) {
- fprintf(stderr, "Usage: %s image.gif [out]\n", argv[0]);
- fprintf(stderr, "\n");
- fprintf(stderr, "If [out] is NOWRITE, the gif will be docoded "
- "but not output.\n");
- fprintf(stderr, "Otherwise [out] is an output filename.\n");
- fprintf(stderr, "When [out] is unset, output is to stdout.\n");
-
- return 1;
- }
-
- if (argc > 2) {
- if (strcmp(argv[2], "NOWRITE") == 0) {
- no_write = true;
- } else {
- outf = fopen(argv[2], "w+");
- if (outf == NULL) {
- fprintf(stderr, "Unable to open %s for writing\n", argv[2]);
- return 2;
- }
- }
- }
-
- /* create our gif animation */
- gif_create(&gif, &bitmap_callbacks);
-
- /* load file into memory */
- data = load_file(argv[1], &size);
-
- /* begin decoding */
- do {
- code = gif_initialise(&gif, size, data);
- if (code != GIF_OK && code != GIF_WORKING) {
- warning("gif_initialise", code);
- gif_finalise(&gif);
- free(data);
- return 1;
- }
- } while (code != GIF_OK);
-
- write_ppm(outf, argv[1], &gif, no_write);
-
- if (argc > 2 && !no_write) {
- fclose(outf);
- }
-
- /* clean up */
- gif_finalise(&gif);
- free(data);
-
- return 0;
-}
diff --git a/test/nsgif.c b/test/nsgif.c
new file mode 100644
index 0000000..29341e7
--- /dev/null
+++ b/test/nsgif.c
@@ -0,0 +1,442 @@
+/*
+ * Copyright 2008 Sean Fox <dyntryx@gmail.com>
+ * Copyright 2008 James Bursa <james@netsurf-browser.org>
+ * Copyright 2022 Michael Drake <tlsa@netsurf-browser.org>
+ *
+ * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/
+ * Licenced under the MIT License,
+ * http://www.opensource.org/licenses/mit-license.php
+ */
+
+#include <assert.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include "../include/nsgif.h"
+
+#include "cli.h"
+#include "cli.c"
+
+#define STR_VAL(_S) STR(_S)
+#define STR(_S) #_S
+
+#define BYTES_PER_PIXEL 4
+
+static struct nsgif_options {
+ const char *file;
+ const char *ppm;
+ uint64_t loops;
+ bool palette;
+ bool version;
+ bool info;
+ bool help;
+} nsgif_options;
+
+static const struct cli_table_entry cli_entries[] = {
+ {
+ .s = 'h',
+ .l = "help",
+ .t = CLI_BOOL,
+ .no_pos = true,
+ .v.b = &nsgif_options.help,
+ .d = "Print this text.",
+ },
+ {
+ .s = 'i',
+ .l = "info",
+ .t = CLI_BOOL,
+ .v.b = &nsgif_options.info,
+ .d = "Dump GIF info to stdout."
+ },
+ {
+ .s = 'l',
+ .l = "loops",
+ .t = CLI_UINT,
+ .v.u = &nsgif_options.loops,
+ .d = "Loop through decoding all frames N times. "
+ "The default is 1."
+ },
+ {
+ .s = 'm',
+ .l = "ppm",
+ .t = CLI_STRING,
+ .v.s = &nsgif_options.ppm,
+ .d = "Convert frames to PPM image at given path."
+ },
+ {
+ .s = 'p',
+ .l = "palette",
+ .t = CLI_BOOL,
+ .v.b = &nsgif_options.palette,
+ .d = "Save palette images."
+ },
+ {
+ .s = 'V',
+ .l = "version",
+ .t = CLI_BOOL,
+ .no_pos = true,
+ .v.b = &nsgif_options.version,
+ .d = "Print version number."
+ },
+ {
+ .p = true,
+ .l = "FILE",
+ .t = CLI_STRING,
+ .v.s = &nsgif_options.file,
+ .d = "Path to GIF file to load."
+ },
+};
+
+const struct cli_table cli = {
+ .entries = cli_entries,
+ .count = (sizeof(cli_entries))/(sizeof(*cli_entries)),
+ .min_positional = 1,
+ .d = "NSGIF - A utility for inspecting and decoding GIFs with libnsgif",
+};
+
+static void *bitmap_create(int width, int height)
+{
+ /* Ensure a stupidly large bitmap is not created */
+ if (width > 4096 || height > 4096) {
+ return NULL;
+ }
+
+ return calloc(width * height, BYTES_PER_PIXEL);
+}
+
+static unsigned char *bitmap_get_buffer(void *bitmap)
+{
+ return bitmap;
+}
+
+static void bitmap_destroy(void *bitmap)
+{
+ free(bitmap);
+}
+
+static uint8_t *load_file(const char *path, size_t *data_size)
+{
+ FILE *fd;
+ struct stat sb;
+ unsigned char *buffer;
+ size_t size;
+ size_t n;
+
+ fd = fopen(path, "rb");
+ if (!fd) {
+ perror(path);
+ exit(EXIT_FAILURE);
+ }
+
+ if (stat(path, &sb)) {
+ perror(path);
+ exit(EXIT_FAILURE);
+ }
+ size = sb.st_size;
+
+ buffer = malloc(size);
+ if (!buffer) {
+ fprintf(stderr, "Unable to allocate %lld bytes\n",
+ (long long) size);
+ exit(EXIT_FAILURE);
+ }
+
+ n = fread(buffer, 1, size, fd);
+ if (n != size) {
+ perror(path);
+ exit(EXIT_FAILURE);
+ }
+
+ fclose(fd);
+
+ *data_size = size;
+ return buffer;
+}
+
+static void warning(const char *context, nsgif_error err)
+{
+ fprintf(stderr, "%s: %s\n", context, nsgif_strerror(err));
+}
+
+static void print_gif_info(const nsgif_info_t *info)
+{
+ const uint8_t *bg = (uint8_t *) &info->background;
+
+ fprintf(stdout, "gif:\n");
+ fprintf(stdout, " width: %"PRIu32"\n", info->width);
+ fprintf(stdout, " height: %"PRIu32"\n", info->height);
+ fprintf(stdout, " max-loops: %"PRIu32"\n", info->loop_max);
+ fprintf(stdout, " frame-count: %"PRIu32"\n", info->frame_count);
+ fprintf(stdout, " global palette: %s\n", info->global_palette ? "yes" : "no");
+ fprintf(stdout, " background:\n");
+ fprintf(stdout, " red: 0x%"PRIx8"\n", bg[0]);
+ fprintf(stdout, " green: 0x%"PRIx8"\n", bg[1]);
+ fprintf(stdout, " blue: 0x%"PRIx8"\n", bg[2]);
+ fprintf(stdout, " frames:\n");
+}
+
+static void print_gif_frame_info(const nsgif_frame_info_t *info, uint32_t i)
+{
+ const char *disposal = nsgif_str_disposal(info->disposal);
+
+ fprintf(stdout, " - frame: %"PRIu32"\n", i);
+ fprintf(stdout, " local palette: %s\n", info->local_palette ? "yes" : "no");
+ fprintf(stdout, " disposal-method: %s\n", disposal);
+ fprintf(stdout, " transparency: %s\n", info->transparency ? "yes" : "no");
+ fprintf(stdout, " interlaced: %s\n", info->interlaced ? "yes" : "no");
+ fprintf(stdout, " display: %s\n", info->display ? "yes" : "no");
+ fprintf(stdout, " delay: %"PRIu32"\n", info->delay);
+ fprintf(stdout, " rect:\n");
+ fprintf(stdout, " x: %"PRIu32"\n", info->rect.x0);
+ fprintf(stdout, " y: %"PRIu32"\n", info->rect.y0);
+ fprintf(stdout, " w: %"PRIu32"\n", info->rect.x1 - info->rect.x0);
+ fprintf(stdout, " h: %"PRIu32"\n", info->rect.y1 - info->rect.y0);
+}
+
+static bool save_palette(
+ const char *img_filename,
+ const char *palette_filename,
+ const uint32_t palette[NSGIF_MAX_COLOURS],
+ size_t used_entries)
+{
+ enum {
+ SIZE = 32,
+ COUNT = 16,
+ };
+ FILE *f;
+ int size = COUNT * SIZE + 1;
+
+ f = fopen(palette_filename, "w+");
+ if (f == NULL) {
+ fprintf(stderr, "Unable to open %s for writing\n",
+ palette_filename);
+ return false;
+ }
+
+ fprintf(f, "P3\n");
+ fprintf(f, "# %s: %s\n", img_filename, palette_filename);
+ fprintf(f, "# Colour count: %zu\n", used_entries);
+ fprintf(f, "%u %u 256\n", size, size);
+
+ for (int y = 0; y < size; y++) {
+ for (int x = 0; x < size; x++) {
+ if (x % SIZE == 0 || y % SIZE == 0) {
+ fprintf(f, "0 0 0 ");
+ } else {
+ size_t offset = y / SIZE * COUNT + x / SIZE;
+ uint8_t *entry = (uint8_t *)&palette[offset];
+
+ fprintf(f, "%u %u %u ",
+ entry[0],
+ entry[1],
+ entry[2]);
+ }
+ }
+
+ fprintf(f, "\n");
+ }
+
+ fclose(f);
+
+ return true;
+}
+
+static bool save_global_palette(const nsgif_t *gif)
+{
+ uint32_t table[NSGIF_MAX_COLOURS];
+ size_t entries;
+
+ nsgif_global_palette(gif, table, &entries);
+
+ return save_palette(nsgif_options.file, "global-palette.ppm",
+ table, entries);
+}
+
+static bool save_local_palette(const nsgif_t *gif, uint32_t frame)
+{
+ static uint32_t table[NSGIF_MAX_COLOURS];
+ char filename[64];
+ size_t entries;
+
+ snprintf(filename, sizeof(filename), "local-palette-%"PRIu32".ppm",
+ frame);
+
+ if (!nsgif_local_palette(gif, frame, table, &entries)) {
+ return false;
+ }
+
+ return save_palette(nsgif_options.file, filename, table, entries);
+}
+
+static void decode(FILE* ppm, const char *name, nsgif_t *gif, bool first)
+{
+ nsgif_error err;
+ uint32_t frame_prev = 0;
+ const nsgif_info_t *info;
+
+ info = nsgif_get_info(gif);
+
+ if (first && ppm != NULL) {
+ fprintf(ppm, "P3\n");
+ fprintf(ppm, "# %s\n", name);
+ fprintf(ppm, "# width %u \n", info->width);
+ fprintf(ppm, "# height %u \n", info->height);
+ fprintf(ppm, "# frame_count %u \n", info->frame_count);
+ fprintf(ppm, "# loop_max %u \n", info->loop_max);
+ fprintf(ppm, "%u %u 256\n", info->width,
+ info->height * info->frame_count);
+ }
+
+ if (first && nsgif_options.info) {
+ print_gif_info(info);
+ }
+ if (first && nsgif_options.palette && info->global_palette) {
+ save_global_palette(gif);
+ }
+
+ /* decode the frames */
+ while (true) {
+ nsgif_bitmap_t *bitmap;
+ const uint8_t *image;
+ uint32_t frame_new;
+ uint32_t delay_cs;
+ nsgif_rect_t area;
+
+ err = nsgif_frame_prepare(gif, &area,
+ &delay_cs, &frame_new);
+ if (err != NSGIF_OK) {
+ warning("nsgif_frame_prepare", err);
+ return;
+ }
+
+ if (frame_new < frame_prev) {
+ /* Must be an animation that loops. We only care about
+ * decoding each frame once in this utility. */
+ return;
+ }
+ frame_prev = frame_new;
+
+ if (first && nsgif_options.info) {
+ const nsgif_frame_info_t *f_info;
+
+ f_info = nsgif_get_frame_info(gif, frame_new);
+ if (f_info != NULL) {
+ print_gif_frame_info(f_info, frame_new);
+ }
+ }
+ if (first && nsgif_options.palette) {
+ save_local_palette(gif, frame_new);
+ }
+
+ err = nsgif_frame_decode(gif, frame_new, &bitmap);
+ if (err != NSGIF_OK) {
+ fprintf(stderr, "Frame %"PRIu32": "
+ "nsgif_decode_frame failed: %s\n",
+ frame_new, nsgif_strerror(err));
+ /* Continue decoding the rest of the frames. */
+
+ } else if (first && ppm != NULL) {
+ fprintf(ppm, "# frame %u:\n", frame_new);
+ image = (const uint8_t *) bitmap;
+ for (uint32_t y = 0; y != info->height; y++) {
+ for (uint32_t x = 0; x != info->width; x++) {
+ size_t z = (y * info->width + x) * 4;
+ fprintf(ppm, "%u %u %u ",
+ image[z],
+ image[z + 1],
+ image[z + 2]);
+ }
+ fprintf(ppm, "\n");
+ }
+ }
+
+ if (delay_cs == NSGIF_INFINITE) {
+ /** This frame is the last. */
+ return;
+ }
+ }
+}
+
+int main(int argc, char *argv[])
+{
+ const nsgif_bitmap_cb_vt bitmap_callbacks = {
+ .create = bitmap_create,
+ .destroy = bitmap_destroy,
+ .get_buffer = bitmap_get_buffer,
+ };
+ size_t size;
+ nsgif_t *gif;
+ uint8_t *data;
+ nsgif_error err;
+ FILE *ppm = NULL;
+
+ /* Override default options with any command line args */
+ if (!cli_parse(&cli, argc, (void *)argv)) {
+ cli_help(&cli, argv[0]);
+ return EXIT_FAILURE;
+ }
+
+ if (nsgif_options.help) {
+ cli_help(&cli, argv[0]);
+ return EXIT_SUCCESS;
+ }
+
+ if (nsgif_options.version) {
+ printf("%s %s\n", STR_VAL(NSGIF_NAME), STR_VAL(NSGIF_VERSION));
+ return EXIT_SUCCESS;
+ }
+
+ if (nsgif_options.ppm != NULL) {
+ ppm = fopen(nsgif_options.ppm, "w+");
+ if (ppm == NULL) {
+ fprintf(stderr, "Unable to open %s for writing\n",
+ nsgif_options.ppm);
+ return EXIT_FAILURE;
+ }
+ }
+
+ /* create our gif animation */
+ err = nsgif_create(&bitmap_callbacks, NSGIF_BITMAP_FMT_R8G8B8A8, &gif);
+ if (err != NSGIF_OK) {
+ warning("nsgif_create", err);
+ return EXIT_FAILURE;
+ }
+
+ /* load file into memory */
+ data = load_file(nsgif_options.file, &size);
+
+ /* Scan the raw data */
+ err = nsgif_data_scan(gif, size, data);
+ if (err != NSGIF_OK) {
+ /* Not fatal; some GIFs are nasty. Can still try to decode
+ * any frames that were decoded successfully. */
+ warning("nsgif_data_scan", err);
+ }
+
+ nsgif_data_complete(gif);
+
+ if (nsgif_options.loops == 0) {
+ nsgif_options.loops = 1;
+ }
+
+ for (uint64_t i = 0; i < nsgif_options.loops; i++) {
+ decode(ppm, nsgif_options.file, gif, i == 0);
+
+ /* We want to ignore any loop limit in the GIF. */
+ nsgif_reset(gif);
+ }
+
+ if (ppm != NULL) {
+ fclose(ppm);
+ }
+
+ /* clean up */
+ nsgif_destroy(gif);
+ free(data);
+
+ return 0;
+}
diff --git a/test/runtest.sh b/test/runtest.sh
index fd5a32b..fd84847 100755
--- a/test/runtest.sh
+++ b/test/runtest.sh
@@ -1,4 +1,4 @@
-#!/bin/sh
+#!/bin/sh
# run test images through libnsgif and count results
@@ -20,25 +20,25 @@ GIFTESTS="${GIFTESTS} test/ns-afl-gif/*.gif"
gifdecode()
{
- OUTF=$(basename ${1} .gif)
- CMPF=$(dirname ${1})/${OUTF}.ppm
- echo "GIF:${1}" >> ${TEST_LOG}
- ${TEST_PATH}/test_decode_gif ${1} ${TEST_OUT}/${OUTF}.ppm 2>> ${TEST_LOG}
- ECODE=$?
-
- echo "Exit code:${ECODE}" >> ${TEST_LOG}
- if [ "${ECODE}" -gt 0 ];then
- return ${ECODE}
- fi
-
- if [ -f "${CMPF}" ]; then
- cmp ${CMPF} ${TEST_OUT}/${OUTF}.ppm >> ${TEST_LOG} 2>> ${TEST_LOG}
- if [ "$?" -ne 0 ]; then
- return 128
+ OUTF=$(basename ${1} .gif)
+ CMPF=$(dirname ${1})/${OUTF}.ppm
+ echo "GIF:${1}" >> ${TEST_LOG}
+ ${TEST_PATH}/test_nsgif ${1} --ppm ${TEST_OUT}/${OUTF}.ppm 2>> ${TEST_LOG}
+ ECODE=$?
+
+ echo "Exit code:${ECODE}" >> ${TEST_LOG}
+ if [ "${ECODE}" -gt 0 ];then
+ return ${ECODE}
fi
- fi
- return 0
+ if [ -f "${CMPF}" ]; then
+ cmp ${CMPF} ${TEST_OUT}/${OUTF}.ppm >> ${TEST_LOG} 2>> ${TEST_LOG}
+ if [ "$?" -ne 0 ]; then
+ return 128
+ fi
+ fi
+
+ return 0
}
GIFTESTTOTC=0
@@ -49,25 +49,27 @@ GIFTESTERRC=0
echo "Testing GIF decode"
for GIF in $(ls ${GIFTESTS});do
- GIFTESTTOTC=$((GIFTESTTOTC+1))
- gifdecode ${GIF}
- ECODE=$?
- if [ "${ECODE}" -gt 127 ];then
- GIFTESTERRC=$((GIFTESTERRC+1))
- else
- if [ "${ECODE}" -gt 0 ];then
- GIFTESTFAILC=$((GIFTESTFAILC+1))
+ GIFTESTTOTC=$((GIFTESTTOTC+1))
+ #echo "${GIF}"
+ gifdecode ${GIF}
+ ECODE=$?
+ if [ "${ECODE}" -gt 127 ];then
+ GIFTESTERRC=$((GIFTESTERRC+1))
+ echo "Error ${GIF}"
else
- GIFTESTPASSC=$((GIFTESTPASSC+1))
+ if [ "${ECODE}" -gt 0 ];then
+ GIFTESTFAILC=$((GIFTESTFAILC+1))
+ else
+ GIFTESTPASSC=$((GIFTESTPASSC+1))
+ fi
fi
- fi
done
echo "Tests:${GIFTESTTOTC} Pass:${GIFTESTPASSC} Fail:${GIFTESTFAILC} Error:${GIFTESTERRC}"
# exit code
if [ "${GIFTESTERRC}" -gt 0 ]; then
- exit 1
+ exit 1
fi
exit 0