snippet/uncompng: support APNG (Animated PNG)

This commit is contained in:
Nigel Tao committed 2026-09-15 10:42:51 +10:00
1 parent 742e8b78d9
commit 1ca418ef16
7 files changed
+1008 -106

No files matched your search

+260
View File
@@ -0,0 +1,260 @@
// Copyright 2026 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
//go:build ignore
// +build ignore
package main
// convert-nie-to-png.go decodes NIA from stdin and encodes (animated) PNG to
// stdout.
//
// Usage: go run convert-nia-to-apng.go < foo.nia > foo.png
import (
"bytes"
"errors"
"io"
"os"
"github.com/google/wuffs/lib/uncompng"
)
func main() {
if err := main1(); err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
}
}
func main1() error {
// When writing APNG, we need to know (at the start of the file) the
// animation's number of frames, but when reading NIA, we only know that at
// the end of the file.
//
// We therefore use io.ReadAll, slurping the entire NIA data into memory
// instead of using the io.Reader streaming API directly, so that we can
// make two passes over the NIA data.
niaBytes, err := io.ReadAll(os.Stdin)
if err != nil {
return err
} else if len(niaBytes) < 24 {
return errors.New("input is not in the NIA format")
}
premultiplied := niaBytes[6] == 'p'
depth8 := niaBytes[7] == '8'
width := u32le(niaBytes[8:])
height := u32le(niaBytes[12:])
padded := !depth8 && ((width & 1) != 0) && ((height & 1) != 0)
if (u32le(niaBytes[:]) != 0x41AF_C36E) || // 0x41AF_C36E is 'nïA'le.
(niaBytes[4] != 0xFF) ||
(niaBytes[5] != 'b') ||
((niaBytes[6] != 'n') && (niaBytes[6] != 'p')) ||
((niaBytes[7] != '4') && (niaBytes[7] != '8')) ||
(width >= 0x8000_0000) ||
(height >= 0x8000_0000) {
return errors.New("input is not in the NIA format")
} else if (width > 0xFF_FFFF) || (height > 0xFF_FFFF) {
return errors.New("input is in an unsupported NIA format")
}
nieSize := calculateNIESize(depth8, width, height)
if nieSize < 0 {
return errors.New("input image dimensions are unsupported (too large)")
} else if nieSize < 16 {
panic("unreachable")
}
// NIA's depth8 is measured in *bytes* per *pixel*, but uncompng's depth is
// measured *bits* per *channel* (times four channels, for BGRA).
depth := uncompng.Depth8
if depth8 {
depth = uncompng.Depth16
}
expectedNieHeader := append([]byte(nil), niaBytes[:16]...)
expectedNieHeader[3] = 'E'
numFrames := uint64(0)
prevCDD := uint64(0)
lastCDD := uint64(0)
for buf := niaBytes[16:]; len(buf) >= 8; numFrames++ {
cdd := u64le(buf)
if (cdd >> 32) == 0x8000_0000 {
lastCDD = cdd
break
} else if ((cdd >> 32) > 0x8000_0000) || (cdd < prevCDD) {
return errors.New("bad CDD (Cumulative Display Duration)")
}
buf = buf[8:]
if int64(len(buf)) < nieSize {
return errors.New("bad NIE frame")
} else if !bytes.Equal(buf[:16], expectedNieHeader) {
return errors.New("bad NIE header")
}
buf = buf[nieSize:]
if padded {
if len(buf) < 4 {
return errors.New("bad NIE padding")
}
buf = buf[4:]
}
prevCDD = cdd
}
enc := uncompng.AnimationEncoder{}
if err := enc.EncodeHeader(
os.Stdout, depth, uncompng.ColorTypeNRGBA,
int(width), int(height), uint32(numFrames), uint32(lastCDD)); err != nil {
return err
}
prevCDD = 0
for buf := niaBytes[16:]; len(buf) >= 8; {
cdd := u64le(buf)
if (cdd >> 32) >= 0x8000_0000 {
break
}
buf = buf[8:]
if depth8 {
swapBlueRedEndian8(buf[16:nieSize])
if premultiplied {
unpremultiply8(buf[16:nieSize])
}
} else {
swapBlueRedEndian4(buf[16:nieSize])
if premultiplied {
unpremultiply4(buf[16:nieSize])
}
}
numer, denom := calculateDurationRatio(cdd - prevCDD)
if err := enc.EncodeFrame(
os.Stdout, buf[16:nieSize], 4*int(width), numer, denom); err != nil {
return err
}
buf = buf[nieSize:]
if padded {
buf = buf[4:]
}
prevCDD = cdd
}
return nil
}
// swapBlueRedEndian4 corrects for the fact that NIA uses little-endian BGRA
// order but the *Go* lib/uncompng library (unlike the *C* snippet/uncompng.c)
// uses big-endian RGBA order, the same as the Go standard library (and PNG).
func swapBlueRedEndian4(buf []byte) {
for ; len(buf) >= 4; buf = buf[4:] {
buf[0], buf[2] = buf[2], buf[0]
}
}
func swapBlueRedEndian8(buf []byte) {
for ; len(buf) >= 8; buf = buf[8:] {
buf[0], buf[1], buf[4], buf[5] = buf[5], buf[4], buf[1], buf[0]
buf[2], buf[3], buf[6], buf[7] = buf[3], buf[2], buf[7], buf[6]
}
}
func unpremultiply4(buf []byte) {
for ; len(buf) >= 4; buf = buf[4:] {
r := 0x101 * uint32(buf[0])
g := 0x101 * uint32(buf[1])
b := 0x101 * uint32(buf[2])
a := 0x101 * uint32(buf[3])
if (a == 0xFFFF) || (a == 0x0000) {
continue
}
r = (r * 0xFFFF) / a
g = (g * 0xFFFF) / a
b = (b * 0xFFFF) / a
buf[0] = byte(r >> 8)
buf[1] = byte(g >> 8)
buf[2] = byte(b >> 8)
}
}
func unpremultiply8(buf []byte) {
for ; len(buf) >= 4; buf = buf[4:] {
r := (uint32(buf[0]) << 8) | uint32(buf[1])
g := (uint32(buf[2]) << 8) | uint32(buf[3])
b := (uint32(buf[4]) << 8) | uint32(buf[5])
a := (uint32(buf[6]) << 8) | uint32(buf[7])
if (a == 0xFFFF) || (a == 0x0000) {
continue
}
r = (r * 0xFFFF) / a
g = (g * 0xFFFF) / a
b = (b * 0xFFFF) / a
buf[0] = byte(r >> 8)
buf[1] = byte(r >> 0)
buf[2] = byte(g >> 8)
buf[3] = byte(g >> 0)
buf[4] = byte(b >> 8)
buf[5] = byte(b >> 0)
}
}
// calculateDurationRatio converts from a time duration measured in flicks
// (frame-ticks, 1 / 705600000 of a second, to APNG's representation, which is
// a ratio of two uint16 values.
//
// TODO: be smarter about how to express a durationInFlicks that isn't an
// integer number of milliseconds (or is over 65.535 seconds). For now, just
// hard-code the denominator to 1000, meaning milliseconds, and round to
// nearest (capped at 65535) to get the numerator.
func calculateDurationRatio(durationInFlicks uint64) (numerator uint16, denominator uint16) {
const flicksPerMillisecond = 705600
millis := (durationInFlicks + (flicksPerMillisecond / 2)) / flicksPerMillisecond
return uint16(min(0xFFFF, millis)), 1000
}
func calculateNIESize(depth8 bool, width uint32, height uint32) int64 {
const maxInt64 = (1 << 63) - 1
const maxUint64 = (1 << 64) - 1
n := uint64(width) * uint64(height) * 4
if depth8 {
if n > (maxUint64 / 2) {
return -1
}
n *= 2
}
if n > (maxInt64 - 16) {
return -1
}
return int64(n + 16)
}
func u32le(b []byte) uint32 {
return (uint32(b[0]) << 0) |
(uint32(b[1]) << 8) |
(uint32(b[2]) << 16) |
(uint32(b[3]) << 24)
}
func u64le(b []byte) uint64 {
return (uint64(b[0]) << 0) |
(uint64(b[1]) << 8) |
(uint64(b[2]) << 16) |
(uint64(b[3]) << 24) |
(uint64(b[4]) << 32) |
(uint64(b[5]) << 40) |
(uint64(b[6]) << 48) |
(uint64(b[7]) << 56)
}
+193
View File
@@ -0,0 +1,193 @@
// Copyright 2026 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
// ----------------
// This exercises snippet/uncompng.c to write a large APNG image to stdout.
//
// It is a C port of lib/uncompng's TestAnimationEncoderLarge.
//
// Run it from the Wuffs root directory, the one that contains the
// wuffs-root-directory.txt file, so that it can find and read the
// test/data/hibiscus.regular.bmp file.
#include <errno.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>
#define UNCOMPNG_CONFIG__STATIC_FUNCTIONS
#define UNCOMPNG_IMPLEMENTATION
#include "../snippet/uncompng.c"
#define WUFFS_CONFIG__MODULES
#define WUFFS_CONFIG__MODULE__BASE
#define WUFFS_CONFIG__MODULE__BMP
#define WUFFS_CONFIG__STATIC_FUNCTIONS
#define WUFFS_IMPLEMENTATION
#include "../release/c/wuffs-unsupported-snapshot.c"
#define IMAGE_HEIGHT 442
#define IMAGE_WIDTH 312
#define NUM_FRAMES 5
#define NUM_PLAYS 0
#define SRC_BMP_SIZE 413850
static uint8_t g_src_bmp[SRC_BMP_SIZE];
static uint8_t g_src_pixels[IMAGE_WIDTH * IMAGE_HEIGHT * 4];
bool //
load_src_bmp() {
int fd = open("test/data/hibiscus.regular.bmp", O_RDONLY, 0);
if (fd == -1) {
fprintf(stderr, "FAIL: open: %s\n", strerror(errno));
return false;
}
for (ssize_t num_read = 0; num_read < SRC_BMP_SIZE;) {
ssize_t n = read(fd, g_src_bmp + num_read, sizeof(g_src_bmp) - num_read);
if (n > 0) {
num_read += n;
} else if (n == 0) {
break;
} else if (errno == EINTR) {
// No-op.
} else {
close(fd);
fprintf(stderr, "FAIL: read: %s\n", strerror(errno));
return false;
}
}
close(fd);
return true;
}
bool //
load_src_pixels() {
static wuffs_bmp__decoder dec;
wuffs_base__io_buffer src = wuffs_base__make_io_buffer(
wuffs_base__make_slice_u8(g_src_bmp, SRC_BMP_SIZE),
wuffs_base__make_io_buffer_meta(SRC_BMP_SIZE, 0, 0, true));
wuffs_base__status status = wuffs_bmp__decoder__initialize(
&dec, sizeof dec, WUFFS_VERSION, WUFFS_INITIALIZE__DEFAULT_OPTIONS);
if (!wuffs_base__status__is_ok(&status)) {
fprintf(stderr, "FAIL: initialize: %s\n",
wuffs_base__status__message(&status));
return false;
}
wuffs_base__image_config ic;
status = wuffs_bmp__decoder__decode_image_config(&dec, &ic, &src);
if (!wuffs_base__status__is_ok(&status)) {
fprintf(stderr, "FAIL: decode_image_config: %s\n",
wuffs_base__status__message(&status));
return false;
}
uint32_t w = wuffs_base__pixel_config__width(&ic.pixcfg);
uint32_t h = wuffs_base__pixel_config__height(&ic.pixcfg);
uint32_t pixfmt = wuffs_base__pixel_config__pixel_format(&ic.pixcfg).repr;
if ((w != IMAGE_WIDTH) || (h != IMAGE_HEIGHT) ||
(pixfmt != WUFFS_BASE__PIXEL_FORMAT__BGRX)) {
fprintf(stderr, "FAIL: decode_image_config: unexpected configuration\n");
return false;
}
if ((WUFFS_BASE__PIXEL_FORMAT__BGRX != UNCOMPNG__PIXEL_FORMAT__BGRX) ||
(WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL !=
UNCOMPNG__PIXEL_FORMAT__BGRA_NONPREMUL)) {
fprintf(stderr, "FAIL: wuffs and uncompng are incompatible\n");
return false;
}
wuffs_base__pixel_config__set(&ic.pixcfg,
WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL,
WUFFS_BASE__PIXEL_SUBSAMPLING__NONE, w, h);
wuffs_base__pixel_buffer pb;
status = wuffs_base__pixel_buffer__set_from_slice(
&pb, &ic.pixcfg,
wuffs_base__make_slice_u8(&g_src_pixels[0], sizeof g_src_pixels));
if (!wuffs_base__status__is_ok(&status)) {
fprintf(stderr, "FAIL: set_from_slice: %s\n",
wuffs_base__status__message(&status));
return false;
}
status = wuffs_bmp__decoder__decode_frame(&dec, &pb, &src,
WUFFS_BASE__PIXEL_BLEND__SRC,
wuffs_base__empty_slice_u8(), NULL);
if (!wuffs_base__status__is_ok(&status)) {
fprintf(stderr, "FAIL: decode_frame: %s\n",
wuffs_base__status__message(&status));
return false;
}
return true;
}
int //
my_write_func(void* context, const uint8_t* data_ptr, size_t data_len) {
static const int stdout_fd = 1;
return (write(stdout_fd, data_ptr, data_len) < 0) ? -errno : 0;
}
int //
main(int argc, char** argv) {
if (!load_src_bmp() || !load_src_pixels()) {
return 1;
}
// Change "if (0)" to "if (1)" to write a still (not animated) PNG.
if (0) {
const int frame = 0;
return uncompng__encode( //
&my_write_func, NULL, //
UNCOMPNG__PIXEL_FORMAT__BGRA_NONPREMUL, IMAGE_WIDTH, IMAGE_HEIGHT, //
&g_src_pixels[0], sizeof(g_src_pixels), IMAGE_WIDTH * 4);
}
static uint16_t delay_millis[NUM_FRAMES] = {300, 500, 600, 400, 200};
int err0 = uncompng__encode_apng_header( //
&my_write_func, NULL, //
UNCOMPNG__PIXEL_FORMAT__BGRA_NONPREMUL, IMAGE_WIDTH, IMAGE_HEIGHT, //
NUM_FRAMES, NUM_PLAYS);
if (err0) {
return err0;
}
for (int frame = 0; frame < NUM_FRAMES; frame++) {
int err1 = uncompng__encode_apng_frame( //
&my_write_func, NULL, //
delay_millis[frame], 1000, //
&g_src_pixels[0], sizeof(g_src_pixels), IMAGE_WIDTH * 4);
if (err1) {
return err1;
}
// Over time, set the R, G, B, A channel values to 0x80.
//
// Use RGBA order, not BGRA, to match the output of lib/uncompng's
// TestAnimationEncoderLarge, in Go.
if (frame < 4) {
static size_t order[4] = {2, 1, 0, 3};
for (size_t i = order[frame]; i < sizeof(g_src_pixels); i += 4) {
g_src_pixels[i] = 0x80;
}
}
}
return 0;
}
+87
View File
@@ -0,0 +1,87 @@
// Copyright 2026 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
// ----------------
// This exercises snippet/uncompng.c to write a small APNG image to stdout.
//
// It is a C port of lib/uncompng's TestAnimationEncoderSmall.
#include <errno.h>
#include <unistd.h>
#define UNCOMPNG_CONFIG__STATIC_FUNCTIONS
#define UNCOMPNG_IMPLEMENTATION
#include "../snippet/uncompng.c"
#define IMAGE_HEIGHT 2
#define IMAGE_WIDTH 3
#define NUM_FRAMES 2
#define NUM_PLAYS 10
int //
my_write_func(void* context, const uint8_t* data_ptr, size_t data_len) {
static const int stdout_fd = 1;
return (write(stdout_fd, data_ptr, data_len) < 0) ? -errno : 0;
}
int //
main(int argc, char** argv) {
static uint8_t pixels[NUM_FRAMES][IMAGE_WIDTH * IMAGE_HEIGHT * 4] = {
{
0xFF, 0x00, 0x00, 0xFF, // Blue.
0xFF, 0xFF, 0xFF, 0xFF, // White.
0x00, 0x00, 0xFF, 0xFF, // Red.
0xFF, 0x00, 0x00, 0xFF, // Blue.
0xFF, 0xFF, 0xFF, 0xFF, // White.
0x00, 0x00, 0xFF, 0xFF, // Red.
},
{
0x00, 0xFF, 0x00, 0xFF, // Green.
0xFF, 0xFF, 0xFF, 0xFF, // White.
0x00, 0x00, 0xFF, 0xFF, // Red.
0x00, 0xFF, 0x00, 0xFF, // Green.
0xFF, 0xFF, 0xFF, 0xFF, // White.
0x00, 0x00, 0xFF, 0xFF, // Red.
}};
// Change "if (0)" to "if (1)" to write a still (not animated) PNG.
if (0) {
const int frame = 0;
return uncompng__encode( //
&my_write_func, NULL, //
UNCOMPNG__PIXEL_FORMAT__BGRX, IMAGE_WIDTH, IMAGE_HEIGHT, //
&pixels[frame][0], sizeof(pixels[frame]), IMAGE_WIDTH * 4);
}
static uint16_t delay_millis[NUM_FRAMES] = {1000, 2000};
int err0 = uncompng__encode_apng_header( //
&my_write_func, NULL, //
UNCOMPNG__PIXEL_FORMAT__BGRX, IMAGE_WIDTH, IMAGE_HEIGHT, //
NUM_FRAMES, NUM_PLAYS);
if (err0) {
return err0;
}
for (int frame = 0; frame < NUM_FRAMES; frame++) {
int err1 = uncompng__encode_apng_frame( //
&my_write_func, NULL, //
delay_millis[frame], 1000, //
&pixels[frame][0], sizeof(pixels[frame]), IMAGE_WIDTH * 4);
if (err1) {
return err1;
}
}
return 0;
}
+67
View File
@@ -0,0 +1,67 @@
// Copyright 2026 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
// ----------------
// This exercises snippet/uncompng.c to write a Julia Set image to stdout.
//
// See also
// https://nigeltao.github.io/blog/2025/uncompressed-png.html
#include <errno.h>
#include <unistd.h>
#define UNCOMPNG_CONFIG__STATIC_FUNCTIONS
#define UNCOMPNG_IMPLEMENTATION
#include "../snippet/uncompng.c"
#define CONFIG_CX -0.70000f
#define CONFIG_CY +0.27015f
#define CONFIG_IMAGE_WIDTH 256
#define CONFIG_IMAGE_HEIGHT 256
int //
my_write_func(void* context, const uint8_t* data_ptr, size_t data_len) {
static const int stdout_fd = 1;
return (write(stdout_fd, data_ptr, data_len) < 0) ? -errno : 0;
}
uint8_t //
my_pixel_func(float fx, float fy) {
static const float escape_distance_squared = 100.0f;
for (int i = 255; i > 0; i--) {
float distance_squared = (fx * fx) + (fy * fy);
if (distance_squared >= escape_distance_squared) {
return i;
}
float gx = CONFIG_CX + (fx * fx) - (fy * fy);
float gy = CONFIG_CY + (2 * fx * fy);
fx = gx;
fy = gy;
}
return 0;
}
int //
main(int argc, char** argv) {
static const float w2 = CONFIG_IMAGE_WIDTH / 2;
static const float h2 = CONFIG_IMAGE_HEIGHT / 2;
static uint8_t pixels[CONFIG_IMAGE_HEIGHT][CONFIG_IMAGE_WIDTH];
for (int iy = 0; iy < CONFIG_IMAGE_HEIGHT; iy++) {
float fy = (iy - h2) / h2;
for (int ix = 0; ix < CONFIG_IMAGE_WIDTH; ix++) {
float fx = (ix - w2) / w2;
pixels[iy][ix] = my_pixel_func(fx, fy);
}
}
return uncompng__encode(&my_write_func, NULL, UNCOMPNG__PIXEL_FORMAT__Y,
CONFIG_IMAGE_WIDTH, CONFIG_IMAGE_HEIGHT,
&pixels[0][0], sizeof(pixels), CONFIG_IMAGE_WIDTH);
}