Explorar el Código

Add phase-2 image formats and GIF animation

- progressive JPEG (successive approximation, spectral scans, restarts)
- EXIF orientation, ICO/CUR and PAM/P7 support
- animated GIF frame compositing and viewer playback
- sampling-aware image estimates and non-zeroed decode-arena growth
- host tests for progressive, oriented, ICO and PAM images
Johannes Zellner hace 2 semanas
padre
commit
70c55c8734

+ 25 - 17
AGENTS.md

@@ -356,9 +356,12 @@ below the run area), so adding code no longer moves any address.
   `USER_BASE` (`0x40000000`)..`USER_STACK_TOP` (`0x40200000`) window, which is
   `USER_BASE` (`0x40000000`)..`USER_STACK_TOP` (`0x40200000`) window, which is
   too small for a full-frame image.  `SYS_MEM_ALLOC`/`SYS_MEM_GROW`/`SYS_MEM_FREE`
   too small for a full-frame image.  `SYS_MEM_ALLOC`/`SYS_MEM_GROW`/`SYS_MEM_FREE`
   (`sys_mem.c/h`) map/grow/delete a single anonymous arena at
   (`sys_mem.c/h`) map/grow/delete a single anonymous arena at
-  `USER_HEAP_BASE` (`0x60000000`), capped at 32 MB; the reaper frees it with
-  the rest of the process and `top` counts its pages.  The canvas mapping at
-  `USER_GFX_BASE` (`0x50000000`) and the WM mappings are separate.
+  `USER_HEAP_BASE` (`0x60000000`), capped at 32 MB; the initial allocation is
+  zeroed but pages appended by `SYS_MEM_GROW` are not (decoders initialize
+  what they use), which keeps large image arenas fast to map.  The reaper
+  frees it with the rest of the process and `top` counts its pages.  The
+  canvas mapping at `USER_GFX_BASE` (`0x50000000`) and the WM mappings are
+  separate.
 - **Ring-3 commands**: `ucmd_*.c`, `ucmd_lib.h`, `ucmd.ld`, `mkpack.c`,
 - **Ring-3 commands**: `ucmd_*.c`, `ucmd_lib.h`, `ucmd.ld`, `mkpack.c`,
   `ramfs.c/h` — freestanding ELFs linked at `USER_BASE` (`0x40000000`), packed
   `ramfs.c/h` — freestanding ELFs linked at `USER_BASE` (`0x40000000`), packed
   by `mkpack` into `cmds.pack` (as `bin/<name>`), embedded in the kernel
   by `mkpack` into `cmds.pack` (as `bin/<name>`), embedded in the kernel
@@ -390,12 +393,14 @@ below the run area), so adding code no longer moves any address.
   zlib, gzip, CRC32/Adler32) is shared with the boot pack.  `img_sniff()` is a
   zlib, gzip, CRC32/Adler32) is shared with the boot pack.  `img_sniff()` is a
   cheap header probe; `img_decode()` returns `struct img_image`; `img_draw()`
   cheap header probe; `img_decode()` returns `struct img_image`; `img_draw()`
   is a clipped, scaled (box-filter down, bilinear up) RGB565 blit with alpha
   is a clipped, scaled (box-filter down, bilinear up) RGB565 blit with alpha
-  over a checkerboard or over the destination (for a browser).  The viewer,
-  `ucmd_view.c`, owns a canvas window and reads its file through
-  `SYS_READ_FILE`; it uses fit/1:1/zoom/pan, shows format/dimensions/size and
-  a clear error for unsupported variants.  Host tests: `make test-images`
-  (`img_test.c`, corpus in `testdata/images/`, generator
-  `tools/gen_img_tests.py`).
+  over a checkerboard or over the destination (for a browser).  Progressive
+  JPEG (successive approximation), EXIF orientation, ICO/CUR, PAM and
+  animated GIF frames are supported as well; arithmetic JPEG/CMYK are not.
+  The viewer, `ucmd_view.c`, owns a canvas window and reads its file through
+  `SYS_READ_FILE`; it uses fit/1:1/zoom/pan, shows format/dimensions/size,
+  animates GIFs, and gives a clear error for unsupported variants.  Host
+  tests: `make test-images` (`img_test.c`, corpus in `testdata/images/`,
+  generator `tools/gen_img_tests.py`).
 - **Network service**: `sys_net.c/h` — the NIC and the stack stay in the
 - **Network service**: `sys_net.c/h` — the NIC and the stack stay in the
   kernel; ring-3 commands get `SYS_NET_INFO`/config, the DNS and DHCP clients
   kernel; ring-3 commands get `SYS_NET_INFO`/config, the DNS and DHCP clients
   and the raw frame paths (`NET_TX/RX/DECODE/REPLY/LOOPBACK/REGS/RESET`), so
   and the raw frame paths (`NET_TX/RX/DECODE/REPLY/LOOPBACK/REGS/RESET`), so
@@ -443,7 +448,7 @@ below the run area), so adding code no longer moves any address.
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <name>|<file>`, `space`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <name>|<file>`, `space`,
 `prog`,
 `prog`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk),
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk),
-`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [hlt|c2|c3|c2ap|c3ap]`, `spin [ms]`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`, and `view <file>` (image viewer; PNG, baseline JPEG, GIF first frame, BMP, TGA, PNM).
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [hlt|c2|c3|c2ap|c3ap]`, `spin [ms]`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`, and `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM).
 
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 DHCP client), `pong` (responds to ARP/ICMP for our IP for 30 s),
 DHCP client), `pong` (responds to ARP/ICMP for our IP for 30 s),
@@ -855,17 +860,20 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     rely on not-present TLB entries not being cached; there is no cross-CPU
     rely on not-present TLB entries not being cached; there is no cross-CPU
     TLB shootdown.  No process shares an address space with another, so normal
     TLB shootdown.  No process shares an address space with another, so normal
     process teardown is unaffected.
     process teardown is unaffected.
-15. Image library limits: progressive/arithmetic JPEG and CMYK are rejected;
-    GIF shows only the first frame; EXIF orientation and ICC/gamma are ignored;
-    the whole file is read into memory (4 MB cap in the viewer); decoding uses
-    a 32 MB arena, so very large photos need DCT-scaled/streamed decode before
-    they fit.  Arithmetic-coded JPEGs are not supported.
+15. Image library limits: arithmetic JPEG and CMYK are rejected; EXIF
+    orientation is applied but ICC/gamma is ignored; animated GIF frames are
+    composited (the viewer plays them), but APNG/WebP remain unsupported.  The
+    whole file is read into memory (4 MB cap in the viewer) and very large
+    photos still need DCT-scaled/streamed decode before they fit the 32 MB
+    arena.
 16. `img_draw()`'s box-filter downscale runs on the CPU.  It is fine for the
 16. `img_draw()`'s box-filter downscale runs on the CPU.  It is fine for the
     viewer's static frames, but a browser showing many large inline images
     viewer's static frames, but a browser showing many large inline images
     should cache a scaled bitmap (or use decode-at-display-scale) instead of
     should cache a scaled bitmap (or use decode-at-display-scale) instead of
     rescaling on every repaint.
     rescaling on every repaint.
-17. `files` recognises images by file extension only; a magic-based fallback
-    would also open extensionless files in the viewer.
+17. `files` recognises images by file extension only (`.png .jpg .jpeg .gif
+    .bmp .tga .ppm .pgm .pbm .ico .cur .pam`); a magic-based fallback would
+    also open extensionless files in the viewer.  Automatic decode-at-scale
+    for oversized images is still missing.
 
 
 18. WebDAV limits: one request at a time (one active connection plus 7
 18. WebDAV limits: one request at a time (one active connection plus 7
     queued; the queue holds each connection's first 1 KB with a zero window),
     queued; the queue holds each connection's first 1 KB with a zero window),

+ 3 - 3
Makefile

@@ -453,7 +453,7 @@ ucmd_mines.elf: ucmd_mines.o ngui.o font_8x16.o ucmd.ld
 # Image library: pure freestanding decoders + RGB565 compositing.  Only the
 # Image library: pure freestanding decoders + RGB565 compositing.  Only the
 # viewer links them today; a browser can link the same objects later.
 # viewer links them today; a browser can link the same objects later.
 IMGLIB_OBJS = img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o \
 IMGLIB_OBJS = img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o \
-              img_jpeg.o img_tga.o img_pnm.o img_file.o
+              img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o
 
 
 $(IMGLIB_OBJS): %.o: %.c img.h img_internal.h inflate.h ucmd_lib.h syscall.h
 $(IMGLIB_OBJS): %.o: %.c img.h img_internal.h inflate.h ucmd_lib.h syscall.h
 	$(CC) $(CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -o $@ $<
@@ -503,7 +503,7 @@ test-crypto: tls_test
 # Host image-library tests (no kernel needed).  The corpus and expected hashes
 # Host image-library tests (no kernel needed).  The corpus and expected hashes
 # are committed; tools/gen_img_tests.py regenerates them.
 # are committed; tools/gen_img_tests.py regenerates them.
 IMGTEST_SRCS = img_test.c img.c img_mem.c img_blit.c img_png.c img_bmp.c \
 IMGTEST_SRCS = img_test.c img.c img_mem.c img_blit.c img_png.c img_bmp.c \
-               img_gif.c img_jpeg.c img_tga.c img_pnm.c inflate.c
+               img_gif.c img_gif_anim.c img_jpeg.c img_tga.c img_pnm.c img_ico.c img_pam.c inflate.c
 IMGTEST_DEPS = img.h img_internal.h inflate.h testdata/images/expected.h
 IMGTEST_DEPS = img.h img_internal.h inflate.h testdata/images/expected.h
 
 
 img_test: $(IMGTEST_SRCS) $(IMGTEST_DEPS)
 img_test: $(IMGTEST_SRCS) $(IMGTEST_DEPS)
@@ -729,4 +729,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 
 clean:
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o thermal.o it87.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack_gz.bin cmds_pack.o ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_file.o img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o thermal.o it87.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack_gz.bin cmds_pack.o ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 47 - 3
img.c

@@ -69,6 +69,9 @@ int img_sniff(const void *data, unsigned int len, struct img_info *out)
 	out->format = IMG_FMT_UNKNOWN;
 	out->format = IMG_FMT_UNKNOWN;
 	out->width = out->height = 0;
 	out->width = out->height = 0;
 	out->has_alpha = 0;
 	out->has_alpha = 0;
+	out->progressive = 0;
+	out->components = 1;
+	out->max_h = out->max_v = 1;
 	if (!d || len == 0)
 	if (!d || len == 0)
 		return IMG_ERR_EMPTY;
 		return IMG_ERR_EMPTY;
 
 
@@ -81,9 +84,18 @@ int img_sniff(const void *data, unsigned int len, struct img_info *out)
 		fmt = img_sniff_gif(d, len, out);
 		fmt = img_sniff_gif(d, len, out);
 	else if (len >= 2 && d[0] == 'B' && d[1] == 'M')
 	else if (len >= 2 && d[0] == 'B' && d[1] == 'M')
 		fmt = img_sniff_bmp(d, len, out);
 		fmt = img_sniff_bmp(d, len, out);
+	else if (len >= 2 && d[0] == 'P' && d[1] == '7')
+		fmt = img_sniff_pam(d, len, out);
 	else if (len >= 2 && d[0] == 'P' && d[1] >= '1' && d[1] <= '6')
 	else if (len >= 2 && d[0] == 'P' && d[1] >= '1' && d[1] <= '6')
 		fmt = img_sniff_pnm(d, len, out);
 		fmt = img_sniff_pnm(d, len, out);
-	else
+	else if (len >= 4 && d[0] == 0 && d[1] == 0 && d[3] == 0 &&
+		 (d[2] == 1 || d[2] == 2)) {
+		/* TGA type 2 also starts with 00 00 02 00.  Only accept the
+		 * ICO interpretation when its directory is valid. */
+		fmt = img_sniff_ico(d, len, out);
+		if (fmt == IMG_FMT_UNKNOWN)
+			fmt = img_sniff_tga(d, len, out);
+	} else
 		fmt = img_sniff_tga(d, len, out);   /* no magic: strict parse */
 		fmt = img_sniff_tga(d, len, out);   /* no magic: strict parse */
 
 
 	if (fmt == IMG_FMT_UNKNOWN)
 	if (fmt == IMG_FMT_UNKNOWN)
@@ -129,6 +141,12 @@ int img_decode(const void *data, unsigned int len,
 	case IMG_FMT_PNM:
 	case IMG_FMT_PNM:
 		r = img_decode_pnm(d, len, opt, m, out);
 		r = img_decode_pnm(d, len, opt, m, out);
 		break;
 		break;
+	case IMG_FMT_ICO:
+		r = img_decode_ico(d, len, opt, m, out);
+		break;
+	case IMG_FMT_PAM:
+		r = img_decode_pam(d, len, opt, m, out);
+		break;
 	default:
 	default:
 		r = IMG_ERR_UNSUPPORTED;
 		r = IMG_ERR_UNSUPPORTED;
 		break;
 		break;
@@ -149,8 +167,33 @@ unsigned int img_estimate(const struct img_info *info)
 	bytes = px * 2;                       /* RGB565 output */
 	bytes = px * 2;                       /* RGB565 output */
 	if (info->has_alpha)
 	if (info->has_alpha)
 		bytes += px;                  /* alpha plane */
 		bytes += px;                  /* alpha plane */
-	if (info->format == IMG_FMT_JPEG)
-		bytes += px * 3;              /* worst case: 4:4:4 planes */
+	if (info->format == IMG_FMT_JPEG) {
+		/* Component pixel count relative to luma.  Keep this in 32-bit
+		 * for the target (no 64-bit division in ring 3). */
+		unsigned int samp = info->max_h * info->max_v;
+		unsigned int comp_px;
+		unsigned int p;
+
+		if (px > 0xFFFFFFFFull)
+			return 0xFFFFFFFFu;
+		p = (unsigned int)px;
+
+		if (samp == 0)
+			samp = 1;
+		if (info->components == 3) {
+			/* p + 2*p/samp, using only 32-bit division. */
+			comp_px = p + (p / samp) * 2 + 2;
+			if (comp_px < p)
+				return 0xFFFFFFFFu;
+		} else {
+			comp_px = p;
+		}
+		if (info->progressive)
+			bytes += (unsigned long long)comp_px * 3; /* coef+plane */
+		else
+			bytes += comp_px;        /* planes */
+	}
+
 	bytes += 2u * 1024u * 1024u;          /* inflate/row/Huffman scratch */
 	bytes += 2u * 1024u * 1024u;          /* inflate/row/Huffman scratch */
 	if (bytes > 0xFFFFFFFFull)
 	if (bytes > 0xFFFFFFFFull)
 		return 0xFFFFFFFFu;
 		return 0xFFFFFFFFu;
@@ -167,6 +210,7 @@ const char *img_format_name(unsigned int format)
 	case IMG_FMT_TGA:  return "TGA";
 	case IMG_FMT_TGA:  return "TGA";
 	case IMG_FMT_PNM:  return "PNM";
 	case IMG_FMT_PNM:  return "PNM";
 	case IMG_FMT_ICO:  return "ICO";
 	case IMG_FMT_ICO:  return "ICO";
+	case IMG_FMT_PAM:  return "PAM";
 	default:           return "image";
 	default:           return "image";
 	}
 	}
 }
 }

+ 12 - 0
img.h

@@ -22,6 +22,7 @@
 #define IMG_FMT_TGA     5
 #define IMG_FMT_TGA     5
 #define IMG_FMT_PNM     6
 #define IMG_FMT_PNM     6
 #define IMG_FMT_ICO     7
 #define IMG_FMT_ICO     7
+#define IMG_FMT_PAM     8
 
 
 #define IMG_FLAG_ALPHA  1
 #define IMG_FLAG_ALPHA  1
 
 
@@ -41,6 +42,9 @@ struct img_info {
 	unsigned int format;
 	unsigned int format;
 	unsigned int width, height;
 	unsigned int width, height;
 	unsigned int has_alpha;
 	unsigned int has_alpha;
+	unsigned int progressive;  /* JPEG only */
+	unsigned int components;   /* JPEG only */
+	unsigned int max_h, max_v; /* JPEG sampling factors */
 };
 };
 
 
 struct img_options {
 struct img_options {
@@ -86,6 +90,14 @@ int  img_sniff(const void *data, unsigned int len, struct img_info *out);
 int  img_decode(const void *data, unsigned int len,
 int  img_decode(const void *data, unsigned int len,
 		const struct img_options *opt, struct img_mem *m,
 		const struct img_options *opt, struct img_mem *m,
 		struct img_image *out);
 		struct img_image *out);
+
+/* Animated GIF: count frames / decode one composited frame.  The first call
+ * with an empty out image allocates it; later calls may reuse the same image. */
+int  img_gif_frames(const void *data, unsigned int len, unsigned int *frames,
+		    unsigned int *first_delay_ms, int *has_alpha);
+int  img_decode_gif_frame(const void *data, unsigned int len,
+			  unsigned int frame, struct img_mem *m,
+			  struct img_image *out, unsigned int *delay_ms);
 unsigned int img_estimate(const struct img_info *info);
 unsigned int img_estimate(const struct img_info *info);
 
 
 const char *img_format_name(unsigned int format);
 const char *img_format_name(unsigned int format);

+ 574 - 0
img_gif_anim.c

@@ -0,0 +1,574 @@
+/* Animated GIF frames: decode up to frame N, applying disposal methods. */
+
+#include "img_internal.h"
+struct ga_rd {
+	const unsigned char *d;
+	unsigned int n, pos, blk_left;
+};
+
+struct ga_rect {
+	unsigned int x, y, w, h;
+};
+
+struct ga_lzw {
+	struct ga_rd *r;
+	unsigned int bitbuf;
+	int bitcnt;
+};
+
+static int ga_u8(struct ga_rd *r, unsigned int *v)
+{
+	if (r->pos >= r->n)
+		return -1;
+	*v = r->d[r->pos++];
+	return 0;
+}
+
+static int ga_subblock(struct ga_rd *r)
+{
+	unsigned int len;
+
+	if (r->blk_left)
+		return 0;
+	if (ga_u8(r, &len))
+		return -1;
+	r->blk_left = len;
+	return len ? 0 : 1;
+}
+
+static int ga_skip_subblocks(struct ga_rd *r)
+{
+	int e;
+
+	do {
+		e = ga_subblock(r);
+		if (e < 0)
+			return -1;
+		if (e > 0)
+			return 0;
+		while (r->blk_left) {
+			r->blk_left--;
+			if (r->pos >= r->n)
+				return -1;
+			r->pos++;
+		}
+	} while (1);
+}
+
+static int ga_palette(const unsigned char *d, unsigned int n,
+		      unsigned int off, unsigned int entries,
+		      unsigned char pal[256][3])
+{
+	unsigned int i;
+
+	if (off > n || entries * 3u > n - off)
+		return -1;
+	for (i = 0; i < entries && i < 256; i++) {
+		pal[i][0] = d[off + i * 3];
+		pal[i][1] = d[off + i * 3 + 1];
+		pal[i][2] = d[off + i * 3 + 2];
+	}
+	return 0;
+}
+
+static int ga_header(const unsigned char *d, unsigned int n,
+		     unsigned int *w, unsigned int *h, unsigned int *packed,
+		     unsigned int *bg, unsigned int *goff, unsigned int *gent,
+		     unsigned int *pos)
+{
+	if (n < 13 || d[0] != 'G' || d[1] != 'I' || d[2] != 'F' ||
+	    d[3] != '8' || (d[4] != '7' && d[4] != '9') || d[5] != 'a')
+		return -1;
+	*w = img_le16(d + 6);
+	*h = img_le16(d + 8);
+	*packed = d[10];
+	*bg = d[11];
+	*gent = 0;
+	*goff = 13;
+	if (*packed & 0x80) {
+		*gent = 1u << ((*packed & 7) + 1);
+		if (*goff + *gent * 3u > n)
+			return -1;
+	}
+	*pos = *goff + *gent * 3u;
+	return (*w && *h && *w <= 32768 && *h <= 32768) ? 0 : -1;
+}
+
+static unsigned int ga_scan_row(unsigned int fh, unsigned int n)
+{
+	static const unsigned int start[4] = {0, 4, 2, 1};
+	static const unsigned int step[4] = {8, 8, 4, 2};
+	unsigned int p;
+
+	for (p = 0; p < 4; p++) {
+		unsigned int count = 0;
+
+		if (fh > start[p])
+			count = (fh - start[p] + step[p] - 1) / step[p];
+		if (n < count)
+			return start[p] + n * step[p];
+		n -= count;
+	}
+	return fh ? fh - 1 : 0;
+}
+
+static int ga_code(struct ga_lzw *z, int bits, int *out)
+{
+	int v;
+
+	while (z->bitcnt < bits) {
+		int e = ga_subblock(z->r);
+		unsigned int b;
+
+		if (e < 0 || e > 0)
+			return -1;
+		if (ga_u8(z->r, &b))
+			return -1;
+		z->r->blk_left--;
+		z->bitbuf |= b << z->bitcnt;
+		z->bitcnt += 8;
+	}
+	v = (int)(z->bitbuf & ((1u << bits) - 1u));
+	z->bitbuf >>= bits;
+	z->bitcnt -= bits;
+	*out = v;
+	return 0;
+}
+
+/* Decode one frame's LZW stream into `idx` in display order. */
+static int ga_decode_lzw(struct ga_rd *rd, unsigned int min_code,
+			 unsigned int fw, unsigned int fh, int interlaced,
+			 unsigned char *idx, struct img_mem *m)
+{
+	int *prefix;
+	unsigned char *suffix, *stack;
+	int clear = 1 << min_code;
+	int end = clear + 1;
+	int avail = end + 1;
+	int code_size = (int)min_code + 1;
+	int prev = -1;
+	struct ga_lzw z;
+	unsigned int done = 0;
+	int rcode = -1;
+
+	prefix = (int *)img_mem_alloc(m, 4096 * sizeof(int), 16);
+	suffix = (unsigned char *)img_mem_alloc(m, 4096, 16);
+	stack = (unsigned char *)img_mem_alloc(m, 4096, 16);
+	if (!prefix || !suffix || !stack)
+		return -1;
+	{
+		unsigned int i;
+
+		for (i = 0; i < (unsigned int)clear; i++) {
+			prefix[i] = -1;
+			suffix[i] = (unsigned char)i;
+		}
+	}
+	z.r = rd;
+	z.bitbuf = 0;
+	z.bitcnt = 0;
+
+	for (;;) {
+		int code, stack_len = 0, cur;
+		unsigned int first;
+
+		if (ga_code(&z, code_size, &code)) {
+			if (done >= fw * fh) {
+				rcode = 0;
+				break;
+			}
+			goto out;
+		}
+		if (code == clear) {
+			avail = end + 1;
+			code_size = (int)min_code + 1;
+			prev = -1;
+			continue;
+		}
+		if (code == end) {
+			rcode = 0;
+			break;
+		}
+		if (prev < 0) {
+			if (code < 0 || code >= clear)
+				goto out;
+			first = (unsigned int)code;
+			if (done < fw * fh) {
+				unsigned int fr = done / fw;
+				unsigned int oy = interlaced ? ga_scan_row(fh, fr) : fr;
+
+				idx[oy * fw + done % fw] = (unsigned char)code;
+				done++;
+			}
+			prev = code;
+			continue;
+		}
+		cur = code;
+		if (code >= avail) {
+			if (code != avail)
+				goto out;
+			stack[stack_len++] = (unsigned char)suffix[prev];
+			cur = prev;
+		}
+		while (cur >= 0 && cur < avail && stack_len < 4096) {
+			stack[stack_len++] = suffix[cur];
+			cur = prefix[cur];
+		}
+		first = stack[stack_len - 1];
+		if (avail < 4096) {
+			prefix[avail] = prev;
+			suffix[avail] = (unsigned char)first;
+			avail++;
+			if (avail == (1 << code_size) && code_size < 12)
+				code_size++;
+		}
+		while (stack_len > 0) {
+			unsigned int v = stack[--stack_len];
+			unsigned int fr, oy;
+
+			if (done >= fw * fh)
+				break;
+			fr = done / fw;
+			oy = interlaced ? ga_scan_row(fh, fr) : fr;
+			idx[oy * fw + done % fw] = (unsigned char)v;
+			done++;
+		}
+		prev = code;
+		if (done >= fw * fh)
+			break;
+	}
+out:
+	rcode = (done >= fw * fh) ? 0 : -1;
+	return rcode;
+}
+
+static void ga_fill(struct img_image *im, unsigned int x, unsigned int y,
+		    unsigned int w, unsigned int h, unsigned int r,
+		    unsigned int g, unsigned int b, unsigned int a)
+{
+	unsigned int i, j;
+
+	if (x >= im->w || y >= im->h)
+		return;
+	if (x + w > im->w) w = im->w - x;
+	if (y + h > im->h) h = im->h - y;
+	for (j = 0; j < h; j++) {
+		for (i = 0; i < w; i++) {
+			unsigned int o = (y + j) * im->w + x + i;
+
+			im->px[o] = img_rgb565(r, g, b);
+			if (im->alpha)
+				im->alpha[o] = (unsigned char)a;
+		}
+	}
+}
+
+static int ga_ensure_output(struct img_image *out, unsigned int w,
+			    unsigned int h)
+{
+	if (out->px)
+		return (out->w == w && out->h == h) ? 0 : -1;
+	return -1;
+}
+
+int img_gif_frames(const void *data, unsigned int len, unsigned int *frames,
+		   unsigned int *first_delay, int *has_alpha)
+{
+	const unsigned char *d = (const unsigned char *)data;
+	unsigned int w, h, packed, bg, goff, gent, pos;
+	struct ga_rd rd;
+	unsigned int count = 0, delay = 0;
+	int alpha = 0;
+
+	if (ga_header(d, len, &w, &h, &packed, &bg, &goff, &gent, &pos))
+		return -1;
+	rd.d = d;
+	rd.n = len;
+	rd.pos = pos;
+	rd.blk_left = 0;
+	(void)w;
+	(void)h;
+	(void)packed;
+	(void)bg;
+	(void)goff;
+	(void)gent;
+	while (rd.pos < len) {
+		unsigned int b;
+
+		if (ga_u8(&rd, &b))
+			break;
+		if (b == 0x3B)
+			break;
+		if (b == 0x21) {
+			unsigned int label;
+
+			if (ga_u8(&rd, &label))
+				break;
+			if (label == 0xF9) {
+				unsigned int l, i, pk = 0, dl = 0;
+
+				if (ga_u8(&rd, &l) || l < 4)
+					break;
+				for (i = 0; i < l; i++) {
+					unsigned int v;
+
+					if (ga_u8(&rd, &v))
+						break;
+					if (i == 0) pk = v;
+					if (i == 1) dl = v;
+					if (i == 2) dl |= v << 8;
+				}
+				if (pk & 1) alpha = 1;
+				if (!count && !delay) delay = dl;
+				if (ga_u8(&rd, &b) || b != 0)
+					break;
+			} else if (ga_skip_subblocks(&rd)) {
+				break;
+			}
+			continue;
+		}
+		if (b == 0x2C) {
+			unsigned int fw, fh, fp, lct = 0;
+
+			if (rd.pos + 9 > len)
+				break;
+			fw = img_le16(d + rd.pos + 4);
+			fh = img_le16(d + rd.pos + 6);
+			fp = d[rd.pos + 8];
+			(void)fw;
+			(void)fh;
+			rd.pos += 9;
+			if (fp & 0x80) {
+				lct = 1u << ((fp & 7) + 1);
+				rd.pos += lct * 3;
+			}
+			if (rd.pos >= len)
+				break;
+			rd.pos++;  /* min code size */
+			if (ga_skip_subblocks(&rd))
+				break;
+			count++;
+			continue;
+		}
+		if (b == 0x00) {
+			while (rd.pos < len && d[rd.pos] == 0)
+				rd.pos++;
+			continue;
+		}
+		break;
+	}
+	if (frames) *frames = count;
+	if (first_delay) *first_delay = delay ? delay : 10;
+	if (has_alpha) *has_alpha = alpha;
+	return count ? 0 : -1;
+}
+
+/* Decode frame `target` (0-based) into `out`.  The caller may pass a
+ * preallocated image of the logical screen size for animation. */
+int img_decode_gif_frame(const void *data, unsigned int len,
+			 unsigned int target, struct img_mem *m,
+			 struct img_image *out, unsigned int *delay_ms)
+{
+	const unsigned char *d = (const unsigned char *)data;
+	unsigned int w, h, packed, bg, goff, gent, pos;
+	unsigned char gpal[256][3], lpal[256][3];
+	unsigned int lpal_n = 0;
+	struct ga_rd rd;
+	struct img_image *im = out;
+	unsigned int frame = 0;
+	unsigned int prev_disp = 0;
+	struct ga_rect prev_rect = {0, 0, 0, 0};
+	unsigned int cur_disp = 0, cur_trans = 0, cur_delay = 0;
+	int cur_has_trans = 0;
+	unsigned char *snapshot = 0;
+	unsigned char *idx = 0;
+	unsigned int idx_cap = 0;
+	unsigned int entry_mark, scratch_mark;
+	int rcode = -1;
+
+	entry_mark = img_mem_mark(m);
+	scratch_mark = entry_mark;
+	if (ga_header(d, len, &w, &h, &packed, &bg, &goff, &gent, &pos))
+		return IMG_ERR_FORMAT;
+	for (frame = 0; frame < 256; frame++)
+		gpal[frame][0] = gpal[frame][1] = gpal[frame][2] = 0;
+	if (gent && ga_palette(d, len, goff, gent, gpal))
+		return IMG_ERR_CORRUPT;
+	if (!im->px) {
+		int r = img_alloc(m, w, h, IMG_FMT_GIF, 1, im);
+		if (r)
+			return r;
+	} else if (ga_ensure_output(im, w, h)) {
+		return IMG_ERR_CORRUPT;
+	}
+	scratch_mark = img_mem_mark(m);
+	ga_fill(im, 0, 0, w, h,
+		gent && bg < gent ? gpal[bg][0] : 0,
+		gent && bg < gent ? gpal[bg][1] : 0,
+		gent && bg < gent ? gpal[bg][2] : 0, 255);
+
+	rd.d = d;
+	rd.n = len;
+	rd.pos = pos;
+	rd.blk_left = 0;
+	frame = 0;
+	while (rd.pos < len) {
+		unsigned int b;
+
+		if (ga_u8(&rd, &b))
+			break;
+		if (b == 0x3B)
+			break;
+		if (b == 0x21) {
+			unsigned int label;
+
+			if (ga_u8(&rd, &label))
+				break;
+			if (label == 0xF9) {
+				unsigned int l, i, pk = 0, dl = 0, tr = 0;
+
+				if (ga_u8(&rd, &l) || l < 4)
+					break;
+				for (i = 0; i < l; i++) {
+					unsigned int v;
+
+					if (ga_u8(&rd, &v))
+						break;
+					if (i == 0) pk = v;
+					if (i == 1) dl = v;
+					if (i == 2) dl |= v << 8;
+					if (i == 3) tr = v;
+				}
+				cur_has_trans = (pk & 1) != 0;
+				cur_disp = (pk >> 2) & 7;
+				cur_delay = dl;
+				cur_trans = tr;
+				if (ga_u8(&rd, &b) || b != 0)
+					break;
+				continue;
+			}
+			if (ga_skip_subblocks(&rd))
+				break;
+			continue;
+		}
+		if (b == 0x2C) {
+			unsigned int left, top, fw, fh, fp, min_code;
+			unsigned int i, x, y;
+
+			if (rd.pos + 9 > len)
+				break;
+			left = img_le16(d + rd.pos);
+			top = img_le16(d + rd.pos + 2);
+			fw = img_le16(d + rd.pos + 4);
+			fh = img_le16(d + rd.pos + 6);
+			fp = d[rd.pos + 8];
+			(void)fw;
+			(void)fh;
+			rd.pos += 9;
+			if (fw == 0 || fh == 0)
+				break;
+			lpal_n = 0;
+			if (fp & 0x80) {
+				lpal_n = 1u << ((fp & 7) + 1);
+				if (ga_palette(d, len, rd.pos, lpal_n, lpal))
+					break;
+				rd.pos += lpal_n * 3u;
+			}
+			if (rd.pos >= len)
+				break;
+			min_code = d[rd.pos++];
+			if (min_code < 2 || min_code > 8)
+				break;
+
+			if (frame > 0 && prev_disp == 2) {
+				ga_fill(im, prev_rect.x, prev_rect.y,
+					prev_rect.w, prev_rect.h,
+					gent && bg < gent ? gpal[bg][0] : 0,
+					gent && bg < gent ? gpal[bg][1] : 0,
+					gent && bg < gent ? gpal[bg][2] : 0, 255);
+			} else if (frame > 0 && prev_disp == 3 && snapshot) {
+				for (i = 0; i < w * h; i++) {
+					im->px[i] = ((unsigned short *)snapshot)[i];
+					if (im->alpha)
+						im->alpha[i] = snapshot[w * h * 2 + i];
+				}
+			}
+			if (cur_disp == 3) {
+				if (!snapshot) {
+					snapshot = (unsigned char *)img_mem_alloc(m,
+						w * h * 3u, 16);
+					if (!snapshot)
+						goto out;
+				}
+				for (i = 0; i < w * h; i++) {
+					((unsigned short *)snapshot)[i] = im->px[i];
+					if (im->alpha)
+						snapshot[w * h * 2 + i] = im->alpha[i];
+					else
+						snapshot[w * h * 2 + i] = 255;
+				}
+			}
+			if (fw * fh > idx_cap) {
+				idx = (unsigned char *)img_mem_alloc(m, fw * fh, 16);
+				if (!idx)
+					goto out;
+				idx_cap = fw * fh;
+			}
+			if (ga_decode_lzw(&rd, min_code, fw, fh,
+					  (fp & 0x40) != 0, idx, m))
+				goto out;
+			if (ga_skip_subblocks(&rd))
+				goto out;
+			for (y = 0; y < fh; y++) {
+				for (x = 0; x < fw; x++) {
+					unsigned int oi = y * fw + x;
+					unsigned int v = idx[oi];
+					unsigned int ox = left + x;
+					unsigned int oy = top + y;
+					unsigned int o;
+
+					if (cur_has_trans && v == cur_trans)
+						continue;
+					if (ox >= im->w || oy >= im->h)
+						continue;
+					o = oy * im->w + ox;
+					if (lpal_n && v >= lpal_n)
+						v = 0;
+					if (lpal_n) {
+						im->px[o] = img_rgb565(lpal[v][0],
+							lpal[v][1], lpal[v][2]);
+					} else {
+						im->px[o] = img_rgb565(gpal[v][0],
+							gpal[v][1], gpal[v][2]);
+					}
+					if (im->alpha)
+						im->alpha[o] = 255;
+				}
+			}
+			if (frame == target) {
+				if (delay_ms)
+					*delay_ms = cur_delay ? cur_delay * 10u : 100u;
+				rcode = 0;
+				goto out;
+			}
+			prev_disp = cur_disp;
+			prev_rect.x = left;
+			prev_rect.y = top;
+			prev_rect.w = fw;
+			prev_rect.h = fh;
+			frame++;
+			cur_has_trans = 0;
+			cur_disp = 0;
+			continue;
+		}
+		if (b == 0x00) {
+			while (rd.pos < len && d[rd.pos] == 0)
+				rd.pos++;
+			continue;
+		}
+		break;
+	}
+out:
+	img_mem_rewind(m, rcode == 0 ? scratch_mark : entry_mark);
+	return rcode;
+}

+ 211 - 0
img_ico.c

@@ -0,0 +1,211 @@
+/* ICO/CUR: pick the largest icon; decode its PNG or BMP DIB payload. */
+
+#include "img_internal.h"
+
+struct ico_ent {
+	unsigned int w, h, bpp, size, off;
+};
+
+static int ico_choose(const unsigned char *d, unsigned int n,
+		      struct ico_ent *best, unsigned int *type)
+{
+	unsigned int count, i;
+
+	if (n < 6 || d[0] != 0 || d[1] != 0)
+		return -1;
+	*type = img_le16(d + 2);
+	if ((*type != 1 && *type != 2) || (count = img_le16(d + 4)) == 0 ||
+	    6u + count * 16u > n)
+		return -1;
+	best->w = best->h = 0;
+	best->bpp = best->size = best->off = 0;
+	for (i = 0; i < count; i++) {
+		const unsigned char *e = d + 6 + i * 16;
+		unsigned int w = e[0] ? e[0] : 256;
+		unsigned int h = e[1] ? e[1] : 256;
+		unsigned int bpp = img_le16(e + 6);
+		unsigned int size = img_le32(e + 8);
+		unsigned int off = img_le32(e + 12);
+
+		if (size == 0 || off > n || size > n - off)
+			continue;
+		if (w * h > best->w * best->h ||
+		    (w * h == best->w * best->h && bpp > best->bpp)) {
+			best->w = w;
+			best->h = h;
+			best->bpp = bpp;
+			best->size = size;
+			best->off = off;
+		}
+	}
+	return best->size ? 0 : -1;
+}
+
+static int ico_dib_info(const unsigned char *d, unsigned int n,
+			unsigned int *w, unsigned int *h, unsigned int *bpp,
+			unsigned int *dib, unsigned int *colors, int *topdown)
+{
+	unsigned int height;
+
+	if (n < 40 || img_le32(d) < 40)
+		return -1;
+	*w = img_le32(d + 4);
+	height = img_le32(d + 8);
+	*topdown = ((int)height < 0);
+	height = *topdown ? (unsigned int)(-(int)height) : height;
+	*h = height / 2;
+	*bpp = img_le16(d + 14);
+	*dib = img_le32(d);
+	*colors = img_le32(d + 32);
+	if (*w == 0 || *h == 0 || *w > 256 || *h > 256)
+		return -1;
+	if (*bpp != 1 && *bpp != 4 && *bpp != 8 && *bpp != 24 && *bpp != 32)
+		return -1;
+	return 0;
+}
+
+int img_sniff_ico(const unsigned char *d, unsigned int n, struct img_info *out)
+{
+	struct ico_ent e;
+	unsigned int type;
+	const unsigned char *p;
+
+	if (ico_choose(d, n, &e, &type))
+		return IMG_FMT_UNKNOWN;
+	p = d + e.off;
+	out->format = IMG_FMT_ICO;
+	out->has_alpha = 0;
+	out->progressive = 0;
+	if (e.size >= 8 && p[0] == 0x89 && p[1] == 'P' && p[2] == 'N' &&
+	    p[3] == 'G') {
+		struct img_info sub;
+
+		if (img_sniff_png(p, e.size, &sub) == IMG_FMT_UNKNOWN)
+			return IMG_FMT_UNKNOWN;
+		out->width = sub.width;
+		out->height = sub.height;
+		out->has_alpha = sub.has_alpha;
+		return IMG_FMT_ICO;
+	}
+	{
+		unsigned int w, h, bpp, dib, colors;
+		int topdown;
+
+		if (ico_dib_info(p, e.size, &w, &h, &bpp, &dib, &colors,
+				 &topdown))
+			return IMG_FMT_UNKNOWN;
+		(void)topdown;
+		out->width = w;
+		out->height = h;
+		out->has_alpha = 1;   /* the AND mask is always present */
+	}
+	return IMG_FMT_ICO;
+}
+
+int img_decode_ico(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out)
+{
+	struct ico_ent e;
+	unsigned int type, w, h, bpp, dib, colors, i;
+	const unsigned char *p;
+
+	if (ico_choose(d, n, &e, &type))
+		return IMG_ERR_FORMAT;
+	p = d + e.off;
+	(void)type;
+	if (e.size >= 8 && p[0] == 0x89 && p[1] == 'P' && p[2] == 'N' &&
+	    p[3] == 'G') {
+		int r = img_decode_png(p, e.size, opt, m, out);
+
+		if (r == 0)
+			out->format = IMG_FMT_ICO;
+		return r;
+	}
+	{
+		int topdown;
+		unsigned int pal_off, pal_n, row_stride, and_off, and_stride;
+		unsigned int xor_off, x, y;
+		unsigned char pal[256][3];
+		unsigned int pal_a[256];
+
+		if (ico_dib_info(p, e.size, &w, &h, &bpp, &dib, &colors,
+				 &topdown))
+			return IMG_ERR_FORMAT;
+		if (!img_size_ok(w, h, opt))
+			return IMG_ERR_TOOBIG;
+		pal_n = 0;
+		if (bpp <= 8) {
+			pal_n = colors ? colors : (1u << bpp);
+			if (pal_n > 256)
+				pal_n = 256;
+			pal_off = dib;
+			if (pal_off + pal_n * 4u > e.size)
+				return IMG_ERR_CORRUPT;
+			for (i = 0; i < pal_n; i++) {
+				const unsigned char *q = p + pal_off + i * 4;
+				pal[i][0] = q[2];
+				pal[i][1] = q[1];
+				pal[i][2] = q[0];
+				pal_a[i] = 255;
+			}
+		}
+		row_stride = ((w * bpp + 31u) / 32u) * 4u;
+		xor_off = dib + (bpp <= 8 ? pal_n * 4u : 0);
+		if (xor_off > e.size || row_stride > e.size - xor_off ||
+		    (unsigned long long)row_stride * h > e.size - xor_off)
+			return IMG_ERR_CORRUPT;
+		and_off = xor_off + row_stride * h;
+		and_stride = ((w + 31u) / 32u) * 4u;
+
+		{
+			int r = img_alloc(m, w, h, IMG_FMT_ICO, 1, out);
+			if (r)
+				return r;
+		}
+		for (y = 0; y < h; y++) {
+			const unsigned char *row = p + xor_off +
+				(topdown ? y : (h - 1 - y)) * row_stride;
+			for (x = 0; x < w; x++) {
+				unsigned int rr = 0, gg = 0, bb = 0, aa = 255;
+				unsigned int oi = y * w + x;
+
+				if (bpp <= 8) {
+					unsigned int idx;
+					if (bpp == 8)
+						idx = row[x];
+					else if (bpp == 4)
+						idx = (row[x / 2] >> ((x & 1) ? 0 : 4)) & 15;
+					else
+						idx = (row[x / 8] >> (7 - (x & 7))) & 1;
+					if (idx >= pal_n)
+						idx = 0;
+					rr = pal[idx][0];
+					gg = pal[idx][1];
+					bb = pal[idx][2];
+					aa = pal_a[idx];
+				} else if (bpp == 24) {
+					const unsigned char *q = row + x * 3;
+					bb = q[0];
+					gg = q[1];
+					rr = q[2];
+				} else {
+					const unsigned char *q = row + x * 4;
+					bb = q[0];
+					gg = q[1];
+					rr = q[2];
+					aa = q[3];
+				}
+				if (and_off + and_stride * (y + 1) <= e.size) {
+					const unsigned char *arow = p + and_off +
+						(topdown ? y : (h - 1 - y)) * and_stride;
+					if (arow[x / 8] & (0x80u >> (x & 7)))
+						aa = 0;
+				}
+				out->px[oi] = img_rgb565(rr, gg, bb);
+				out->alpha[oi] = (unsigned char)aa;
+			}
+		}
+	}
+	return 0;
+}

+ 8 - 0
img_internal.h

@@ -59,6 +59,12 @@ int img_decode_tga(const unsigned char *d, unsigned int n,
 int img_decode_pnm(const unsigned char *d, unsigned int n,
 int img_decode_pnm(const unsigned char *d, unsigned int n,
 		   const struct img_options *opt, struct img_mem *m,
 		   const struct img_options *opt, struct img_mem *m,
 		   struct img_image *out);
 		   struct img_image *out);
+int img_decode_ico(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out);
+int img_decode_pam(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out);
 
 
 /* Header-only probes used by img_sniff().  Return IMG_FMT_* or UNKNOWN. */
 /* Header-only probes used by img_sniff().  Return IMG_FMT_* or UNKNOWN. */
 int img_sniff_png(const unsigned char *d, unsigned int n, struct img_info *out);
 int img_sniff_png(const unsigned char *d, unsigned int n, struct img_info *out);
@@ -67,6 +73,8 @@ int img_sniff_gif(const unsigned char *d, unsigned int n, struct img_info *out);
 int img_sniff_bmp(const unsigned char *d, unsigned int n, struct img_info *out);
 int img_sniff_bmp(const unsigned char *d, unsigned int n, struct img_info *out);
 int img_sniff_tga(const unsigned char *d, unsigned int n, struct img_info *out);
 int img_sniff_tga(const unsigned char *d, unsigned int n, struct img_info *out);
 int img_sniff_pnm(const unsigned char *d, unsigned int n, struct img_info *out);
 int img_sniff_pnm(const unsigned char *d, unsigned int n, struct img_info *out);
+int img_sniff_ico(const unsigned char *d, unsigned int n, struct img_info *out);
+int img_sniff_pam(const unsigned char *d, unsigned int n, struct img_info *out);
 
 
 /* True when an image of w*h pixels is acceptable for the given options. */
 /* True when an image of w*h pixels is acceptable for the given options. */
 int img_size_ok(unsigned int w, unsigned int h,
 int img_size_ok(unsigned int w, unsigned int h,

La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 626 - 199
img_jpeg.c


+ 194 - 0
img_pam.c

@@ -0,0 +1,194 @@
+/* PAM (P7): binary grayscale/RGB with optional alpha. */
+
+#include "img_internal.h"
+
+struct pam_hdr {
+	unsigned int w, h, depth, maxval, data;
+};
+
+static int pam_line(const unsigned char *d, unsigned int n, unsigned int *pos,
+		    const unsigned char **start, unsigned int *len)
+{
+	unsigned int p = *pos, s;
+
+	if (p >= n)
+		return -1;
+	s = p;
+	while (p < n && d[p] != '\n')
+		p++;
+	*start = d + s;
+	*len = p - s;
+	if (p < n)
+		p++;
+	*pos = p;
+	if (*len && (*start)[*len - 1] == '\r')
+		(*len)--;
+	return 0;
+}
+
+static int pam_uint(const unsigned char *s, unsigned int len, unsigned int *v)
+{
+	unsigned int i = 0, val = 0;
+	int any = 0;
+
+	while (i < len && (s[i] == ' ' || s[i] == '\t'))
+		i++;
+	while (i < len && s[i] >= '0' && s[i] <= '9') {
+		val = val * 10 + (s[i] - '0');
+		if (val > 65535)
+			return -1;
+		i++;
+		any = 1;
+	}
+	if (!any)
+		return -1;
+	while (i < len && (s[i] == ' ' || s[i] == '\t'))
+		i++;
+	if (i != len)
+		return -1;
+	*v = val;
+	return 0;
+}
+
+static int pam_key(const unsigned char *s, unsigned int len, const char *key)
+{
+	unsigned int i = 0, k = 0;
+
+	while (i < len && s[i] == ' ')
+		i++;
+	while (key[k]) {
+		if (i >= len || s[i] != (unsigned char)key[k])
+			return 0;
+		i++;
+		k++;
+	}
+	return i == len || s[i] == ' ' || s[i] == '\t';
+}
+
+
+static int pam_header(const unsigned char *d, unsigned int n, struct pam_hdr *p)
+{
+	unsigned int pos = 2;
+	int done = 0;
+
+	p->w = p->h = p->depth = p->maxval = 0;
+	while (pos < n) {
+		const unsigned char *s;
+		unsigned int len, v;
+
+		if (pam_line(d, n, &pos, &s, &len))
+			return -1;
+		if (!len || s[0] == '#')
+			continue;
+		if (len == 6 && s[0] == 'E' && s[1] == 'N' && s[2] == 'D' &&
+		    s[3] == 'H' && s[4] == 'D' && s[5] == 'R') {
+			done = 1;
+			break;
+		}
+		if (pam_key(s, len, "WIDTH")) {
+			if (pam_uint(s + 5, len - 5, &v))
+				return -1;
+			p->w = v;
+		} else if (pam_key(s, len, "HEIGHT")) {
+			if (pam_uint(s + 6, len - 6, &v))
+				return -1;
+			p->h = v;
+		} else if (pam_key(s, len, "DEPTH")) {
+			if (pam_uint(s + 5, len - 5, &v))
+				return -1;
+			p->depth = v;
+		} else if (pam_key(s, len, "MAXVAL")) {
+			if (pam_uint(s + 6, len - 6, &v))
+				return -1;
+			p->maxval = v;
+		} else if (pam_key(s, len, "TUPLTYPE")) {
+			/* The channel count from DEPTH is sufficient. */
+		} else {
+			return -1;
+		}
+	}
+	if (!done || p->w == 0 || p->h == 0 || p->w > 32768 ||
+	    p->h > 32768 || p->depth < 1 || p->depth > 4 ||
+	    p->maxval == 0 || p->maxval > 65535)
+		return -1;
+	p->data = pos;
+	return 0;
+}
+
+int img_sniff_pam(const unsigned char *d, unsigned int n, struct img_info *out)
+{
+	struct pam_hdr p;
+
+	if (pam_header(d, n, &p))
+		return IMG_FMT_UNKNOWN;
+	out->format = IMG_FMT_PAM;
+	out->width = p.w;
+	out->height = p.h;
+	out->has_alpha = (p.depth == 2 || p.depth == 4);
+	out->progressive = 0;
+	return IMG_FMT_PAM;
+}
+
+static unsigned int pam_scale(unsigned int v, unsigned int mv)
+{
+	if (mv == 255)
+		return v;
+	if (mv == 1)
+		return v ? 255 : 0;
+	return (v * 255u + mv / 2) / mv;
+}
+
+int img_decode_pam(const unsigned char *d, unsigned int n,
+		   const struct img_options *opt, struct img_mem *m,
+		   struct img_image *out)
+{
+	struct pam_hdr p;
+	unsigned int x, y, c;
+	unsigned int step;
+	int alpha, rcode;
+
+	if (pam_header(d, n, &p))
+		return IMG_ERR_FORMAT;
+	if (!img_size_ok(p.w, p.h, opt))
+		return IMG_ERR_TOOBIG;
+	alpha = (p.depth == 2 || p.depth == 4);
+	rcode = img_alloc(m, p.w, p.h, IMG_FMT_PAM, alpha, out);
+	if (rcode)
+		return rcode;
+	step = p.maxval > 255 ? 2 : 1;
+	for (y = 0; y < p.h; y++) {
+		for (x = 0; x < p.w; x++) {
+			unsigned int s[4] = { 0, 0, 0, 0 };
+			unsigned int r, g, b, a = 255;
+
+			for (c = 0; c < p.depth; c++) {
+				if (p.data + step > n)
+					return IMG_ERR_CORRUPT;
+				if (step == 1) {
+					s[c] = d[p.data++];
+				} else {
+					s[c] = img_be16(d + p.data);
+					p.data += 2;
+				}
+				if (s[c] > p.maxval)
+					return IMG_ERR_CORRUPT;
+				s[c] = pam_scale(s[c], p.maxval);
+			}
+			if (p.depth <= 2) {
+				r = g = b = s[0];
+				if (p.depth == 2)
+					a = s[1];
+			} else {
+				r = s[0];
+				g = s[1];
+				b = s[2];
+				if (p.depth == 4)
+					a = s[3];
+			}
+			out->px[y * p.w + x] = img_rgb565(r, g, b);
+			if (out->alpha)
+				out->alpha[y * p.w + x] = (unsigned char)a;
+		}
+	}
+	return 0;
+}

+ 39 - 2
img_test.c

@@ -162,6 +162,7 @@ static int test_jpeg(const char *name)
 	unsigned char *ref;
 	unsigned char *ref;
 	struct img_mem mem;
 	struct img_mem mem;
 	struct img_options opt;
 	struct img_options opt;
+	struct img_info info;
 	struct img_image im;
 	struct img_image im;
 	int r, x, y;
 	int r, x, y;
 	unsigned long long sum = 0, count = 0;
 	unsigned long long sum = 0, count = 0;
@@ -174,6 +175,14 @@ static int test_jpeg(const char *name)
 		printf("FAIL %s: read\n", name);
 		printf("FAIL %s: read\n", name);
 		return 1;
 		return 1;
 	}
 	}
+	memset(&info, 0, sizeof(info));
+	if (img_sniff(filebuf, n, &info) != 0 || info.width != rw ||
+	    info.height != rh) {
+		printf("FAIL %s: sniff %ux%u, expected %ux%u\n", name,
+		       info.width, info.height, rw, rh);
+		free(ref);
+		return 1;
+	}
 	img_mem_init(&mem, arena, sizeof(arena));
 	img_mem_init(&mem, arena, sizeof(arena));
 	opt.max_pixels = 0;
 	opt.max_pixels = 0;
 	memset(&im, 0, sizeof(im));
 	memset(&im, 0, sizeof(im));
@@ -314,6 +323,32 @@ static void test_blit(void)
 	});
 	});
 }
 }
 
 
+static int test_gif_anim(void)
+{
+	unsigned int n, frames = 0, delay = 0;
+	int ha = 0;
+	struct img_mem mem;
+	struct img_image im;
+	int r;
+
+	if (read_file("testdata/images/anim.gif", filebuf, sizeof(filebuf), &n))
+		return 1;
+	if (img_gif_frames(filebuf, n, &frames, &delay, &ha) != 0 || frames < 2) {
+		printf("FAIL anim.gif: frame count %u\n", frames);
+		return 1;
+	}
+	img_mem_init(&mem, arena, sizeof(arena));
+	memset(&im, 0, sizeof(im));
+	r = img_decode_gif_frame(filebuf, n, 0, &mem, &im, &delay);
+	if (r == 0)
+		r = img_decode_gif_frame(filebuf, n, 1, &mem, &im, &delay);
+	if (r != 0) {
+		printf("FAIL anim.gif: frame decode %d\n", r);
+		return 1;
+	}
+	return 0;
+}
+
 static int test_unsupported(void)
 static int test_unsupported(void)
 {
 {
 	unsigned int n;
 	unsigned int n;
@@ -321,13 +356,13 @@ static int test_unsupported(void)
 	struct img_options opt;
 	struct img_options opt;
 	struct img_image im;
 	struct img_image im;
 
 
-	if (read_file("testdata/images/prog.jpg", filebuf, sizeof(filebuf), &n))
+	if (read_file("testdata/images/cmyk.jpg", filebuf, sizeof(filebuf), &n))
 		return 1;
 		return 1;
 	img_mem_init(&mem, arena, sizeof(arena));
 	img_mem_init(&mem, arena, sizeof(arena));
 	opt.max_pixels = 0;
 	opt.max_pixels = 0;
 	memset(&im, 0, sizeof(im));
 	memset(&im, 0, sizeof(im));
 	if (img_decode(filebuf, n, &opt, &mem, &im) != IMG_ERR_UNSUPPORTED) {
 	if (img_decode(filebuf, n, &opt, &mem, &im) != IMG_ERR_UNSUPPORTED) {
-		printf("FAIL prog.jpg: not rejected\n");
+		printf("FAIL cmyk.jpg: not rejected\n");
 		return 1;
 		return 1;
 	}
 	}
 	return 0;
 	return 0;
@@ -341,6 +376,8 @@ int main(void)
 	test_inflate();
 	test_inflate();
 	if (test_unsupported())
 	if (test_unsupported())
 		failures++;
 		failures++;
+	if (test_gif_anim())
+		failures++;
 	for (i = 0; i < IMG_EXP_COUNT; i++) {
 	for (i = 0; i < IMG_EXP_COUNT; i++) {
 		if (test_lossless(&img_exp[i]))
 		if (test_lossless(&img_exp[i]))
 			failures++;
 			failures++;

+ 9 - 4
sys_mem.c

@@ -21,7 +21,8 @@ static void zero_page(unsigned int phys)
 
 
 /* Map new pages [from, to) of the arena.  On failure release only the pages
 /* Map new pages [from, to) of the arena.  On failure release only the pages
  * mapped by this call; the caller's existing arena is untouched. */
  * mapped by this call; the caller's existing arena is untouched. */
-static int map_pages(struct process *p, unsigned int from, unsigned int to)
+static int map_pages(struct process *p, unsigned int from, unsigned int to,
+		     int zero)
 {
 {
 	unsigned int i;
 	unsigned int i;
 
 
@@ -31,7 +32,8 @@ static int map_pages(struct process *p, unsigned int from, unsigned int to)
 
 
 		if (!phys)
 		if (!phys)
 			break;
 			break;
-		zero_page(phys);
+		if (zero)
+			zero_page(phys);
 		if (!paging_map_page(p->cr3, va, phys,
 		if (!paging_map_page(p->cr3, va, phys,
 				     PTE_USER | PTE_WRITABLE | PTE_PRESENT)) {
 				     PTE_USER | PTE_WRITABLE | PTE_PRESENT)) {
 			mm_free_page(phys);
 			mm_free_page(phys);
@@ -61,7 +63,7 @@ int sys_mem_alloc(unsigned int bytes)
 	pages = (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
 	pages = (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
 	if (pages == 0 || pages > USER_HEAP_MAX / PAGE_SIZE)
 	if (pages == 0 || pages > USER_HEAP_MAX / PAGE_SIZE)
 		return -1;
 		return -1;
-	if (map_pages(p, 0, pages))
+	if (map_pages(p, 0, pages, 1))
 		return -1;
 		return -1;
 	p->heap_pages = pages;
 	p->heap_pages = pages;
 	return (int)USER_HEAP_BASE;
 	return (int)USER_HEAP_BASE;
@@ -79,7 +81,10 @@ int sys_mem_grow(unsigned int bytes)
 		return 0;              /* shrinking is deliberately unsupported */
 		return 0;              /* shrinking is deliberately unsupported */
 	if (pages > USER_HEAP_MAX / PAGE_SIZE)
 	if (pages > USER_HEAP_MAX / PAGE_SIZE)
 		return -1;
 		return -1;
-	if (map_pages(p, p->heap_pages, pages))
+	/* Growth is normally used for a decode arena; the decoder fills every
+	 * byte it consumes.  Skip the zero pass, which dominates the grow
+	 * time on a large image.  The initial allocation above is zeroed. */
+	if (map_pages(p, p->heap_pages, pages, 0))
 		return -1;
 		return -1;
 	p->heap_pages = pages;
 	p->heap_pages = pages;
 	return 0;
 	return 0;

+ 1 - 1
syscall.h

@@ -113,7 +113,7 @@
  * USER_HEAP_BASE (0x60000000), at most USER_HEAP_MAX (32 MB), freed when the
  * USER_HEAP_BASE (0x60000000), at most USER_HEAP_MAX (32 MB), freed when the
  * process exits.  SYS_MEM_ALLOC returns the base address, or <0. */
  * process exits.  SYS_MEM_ALLOC returns the base address, or <0. */
 #define SYS_MEM_ALLOC      88  /* (unsigned bytes) -> VA or <0 */
 #define SYS_MEM_ALLOC      88  /* (unsigned bytes) -> VA or <0 */
-#define SYS_MEM_GROW       89  /* (unsigned total_bytes) -> 0/-1 */
+#define SYS_MEM_GROW       89  /* (unsigned total_bytes) -> 0/-1; new pages not zeroed */
 #define SYS_MEM_FREE       90  /* () -> 0/-1 */
 #define SYS_MEM_FREE       90  /* () -> 0/-1 */
 
 
 /* CPU temperature (see thermal.c): the hottest core's DTS reading. */
 /* CPU temperature (see thermal.c): the hottest core's DTS reading. */

BIN
testdata/images/cmyk.jpg


BIN
testdata/images/exif2.jpg


BIN
testdata/images/exif3.jpg


BIN
testdata/images/exif4.jpg


BIN
testdata/images/exif5.jpg


BIN
testdata/images/exif6.jpg


BIN
testdata/images/exif7.jpg


BIN
testdata/images/exif8.jpg


+ 14 - 0
testdata/images/expected.h

@@ -14,6 +14,7 @@ static const struct img_exp {
 	{ "gray.png", 97, 61, 0xea937d55u, 0 },
 	{ "gray.png", 97, 61, 0xea937d55u, 0 },
 	{ "gray16.png", 97, 61, 0x054b5854u, 0 },
 	{ "gray16.png", 97, 61, 0x054b5854u, 0 },
 	{ "gray_inter.png", 97, 61, 0xea937d55u, 0 },
 	{ "gray_inter.png", 97, 61, 0xea937d55u, 0 },
+	{ "icon.ico", 32, 32, 0x4944bc94u, 1 },
 	{ "inter.gif", 97, 61, 0x1458d06eu, 0 },
 	{ "inter.gif", 97, 61, 0x1458d06eu, 0 },
 	{ "pal.bmp", 97, 61, 0x1458d06eu, 0 },
 	{ "pal.bmp", 97, 61, 0x1458d06eu, 0 },
 	{ "pal.png", 97, 61, 0xc1cef470u, 1 },
 	{ "pal.png", 97, 61, 0xc1cef470u, 1 },
@@ -25,6 +26,7 @@ static const struct img_exp {
 	{ "rgb.tga", 97, 61, 0xcba8344eu, 0 },
 	{ "rgb.tga", 97, 61, 0xcba8344eu, 0 },
 	{ "rgb_inter.png", 97, 61, 0xcba8344eu, 0 },
 	{ "rgb_inter.png", 97, 61, 0xcba8344eu, 0 },
 	{ "rgba.bmp", 97, 61, 0xcba8344eu, 0 },
 	{ "rgba.bmp", 97, 61, 0xcba8344eu, 0 },
+	{ "rgba.pam", 97, 61, 0xaebae43eu, 1 },
 	{ "rgba.png", 97, 61, 0xaebae43eu, 1 },
 	{ "rgba.png", 97, 61, 0xaebae43eu, 1 },
 	{ "rgba.tga", 97, 61, 0xaebae43eu, 1 },
 	{ "rgba.tga", 97, 61, 0xaebae43eu, 1 },
 	{ "rgba_inter.png", 97, 61, 0xaebae43eu, 1 },
 	{ "rgba_inter.png", 97, 61, 0xaebae43eu, 1 },
@@ -40,5 +42,17 @@ static const char *const img_jpeg[] = {
 	"j420.jpg",
 	"j420.jpg",
 	"jgray.jpg",
 	"jgray.jpg",
 	"jrst.jpg",
 	"jrst.jpg",
+	"prog.jpg",
+	"prog444.jpg",
+	"prog422.jpg",
+	"proggray.jpg",
+	"progrst.jpg",
+	"exif2.jpg",
+	"exif3.jpg",
+	"exif4.jpg",
+	"exif5.jpg",
+	"exif6.jpg",
+	"exif7.jpg",
+	"exif8.jpg",
 };
 };
 #define IMG_JPEG_COUNT (sizeof(img_jpeg) / sizeof(img_jpeg[0]))
 #define IMG_JPEG_COUNT (sizeof(img_jpeg) / sizeof(img_jpeg[0]))

BIN
testdata/images/icon.ico


BIN
testdata/images/prog422.jpg


BIN
testdata/images/prog444.jpg


BIN
testdata/images/proggray.jpg


BIN
testdata/images/progrst.jpg


BIN
testdata/images/ref/exif2.jpg.ppm


BIN
testdata/images/ref/exif3.jpg.ppm


BIN
testdata/images/ref/exif4.jpg.ppm


BIN
testdata/images/ref/exif5.jpg.ppm


BIN
testdata/images/ref/exif6.jpg.ppm


BIN
testdata/images/ref/exif7.jpg.ppm


BIN
testdata/images/ref/exif8.jpg.ppm


BIN
testdata/images/ref/prog.jpg.ppm


BIN
testdata/images/ref/prog422.jpg.ppm


BIN
testdata/images/ref/prog444.jpg.ppm


La diferencia del archivo ha sido suprimido porque es demasiado grande
+ 9 - 0
testdata/images/ref/proggray.jpg.ppm


BIN
testdata/images/ref/progrst.jpg.ppm


BIN
testdata/images/rgba.pam


+ 33 - 2
tools/gen_img_tests.py

@@ -8,7 +8,7 @@ import gzip
 import os
 import os
 import struct
 import struct
 import zlib
 import zlib
-from PIL import Image, ImageDraw
+from PIL import Image, ImageDraw, ImageOps
 
 
 ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 OUT = os.path.join(ROOT, "testdata", "images")
 OUT = os.path.join(ROOT, "testdata", "images")
@@ -106,6 +106,9 @@ def main():
     files["rle.tga"] = (rgb, False)
     files["rle.tga"] = (rgb, False)
     rgba.save(os.path.join(OUT, "rgba.tga"))
     rgba.save(os.path.join(OUT, "rgba.tga"))
     files["rgba.tga"] = (rgba, True)
     files["rgba.tga"] = (rgba, True)
+    ic = rgba.resize((32, 32))
+    ic.save(os.path.join(OUT, "icon.ico"), sizes=[(32, 32)])
+    files["icon.ico"] = (Image.open(os.path.join(OUT, "icon.ico")).convert("RGBA"), True)
     save(rgb, "rgb.ppm")
     save(rgb, "rgb.ppm")
     save(gray, "gray.pgm")
     save(gray, "gray.pgm")
     save(bw, "bw.pbm")
     save(bw, "bw.pbm")
@@ -115,6 +118,11 @@ def main():
             for x in range(w):
             for x in range(w):
                 f.write("%d %d %d " % p[x, y])
                 f.write("%d %d %d " % p[x, y])
     files["ascii.ppm"] = (rgb, False)
     files["ascii.ppm"] = (rgb, False)
+    with open(os.path.join(OUT, "rgba.pam"), "wb") as f:
+        f.write(("P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 255\n"
+                 "TUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h)).encode())
+        f.write(rgba.tobytes())
+    files["rgba.pam"] = (rgba, True)
 
 
     gif_src = rgb.convert("P", palette=Image.ADAPTIVE, colors=256)
     gif_src = rgb.convert("P", palette=Image.ADAPTIVE, colors=256)
     save(gif_src, "plain.gif")
     save(gif_src, "plain.gif")
@@ -145,7 +153,30 @@ def main():
     rgb.save(os.path.join(OUT, "jrst.jpg"), quality=90, restart_marker_blocks=2)
     rgb.save(os.path.join(OUT, "jrst.jpg"), quality=90, restart_marker_blocks=2)
     rgb.save(os.path.join(OUT, "ref", "jrst.jpg.ppm"))
     rgb.save(os.path.join(OUT, "ref", "jrst.jpg.ppm"))
     jpegs.append("jrst.jpg")
     jpegs.append("jrst.jpg")
-    rgb.save(os.path.join(OUT, "prog.jpg"), quality=90, progressive=True)
+
+    for name, src, kw in [
+            ("prog.jpg", rgb, dict(subsampling=2)),
+            ("prog444.jpg", rgb, dict(subsampling=0)),
+            ("prog422.jpg", rgb, dict(subsampling=1)),
+            ("proggray.jpg", gray, {}),
+            ("progrst.jpg", rgb, dict(restart_marker_blocks=2))]:
+        src.save(os.path.join(OUT, name), quality=90, progressive=True, **kw)
+        Image.open(os.path.join(OUT, name)).convert("RGB").save(
+            os.path.join(OUT, "ref", name + ".ppm"))
+        jpegs.append(name)
+
+    # EXIF orientation: the reference is PIL's exif_transpose of the same
+    # JPEG, i.e. the upright image the viewer should show.
+    for o in range(2, 9):
+        ex = Image.Exif()
+        ex[0x0112] = o
+        name = "exif%d.jpg" % o
+        rgb.save(os.path.join(OUT, name), quality=90, exif=ex)
+        ImageOps.exif_transpose(Image.open(os.path.join(OUT, name))).convert("RGB").save(
+            os.path.join(OUT, "ref", name + ".ppm"))
+        jpegs.append(name)
+
+    rgb.convert("CMYK").save(os.path.join(OUT, "cmyk.jpg"), quality=90)
 
 
     # inflate vectors
     # inflate vectors
     raw = (b"the quick brown fox jumps over the lazy dog\n" * 500) + bytes(range(256)) * 80
     raw = (b"the quick brown fox jumps over the lazy dog\n" * 500) + bytes(range(256)) * 80

+ 2 - 1
ucmd_files.c

@@ -178,7 +178,8 @@ static int is_image_name(const char *name)
 	       ext_is(name, ".jpeg") || ext_is(name, ".gif") ||
 	       ext_is(name, ".jpeg") || ext_is(name, ".gif") ||
 	       ext_is(name, ".bmp") || ext_is(name, ".tga") ||
 	       ext_is(name, ".bmp") || ext_is(name, ".tga") ||
 	       ext_is(name, ".ppm") || ext_is(name, ".pgm") ||
 	       ext_is(name, ".ppm") || ext_is(name, ".pgm") ||
-	       ext_is(name, ".pbm");
+	       ext_is(name, ".pbm") || ext_is(name, ".ico") ||
+	       ext_is(name, ".cur") || ext_is(name, ".pam");
 }
 }
 
 
 static void path_join(const char *dir, const char *name, char *out,
 static void path_join(const char *dir, const char *name, char *out,

+ 31 - 0
ucmd_view.c

@@ -44,6 +44,7 @@ struct viewer {
 	int have_img;
 	int have_img;
 	int loading;
 	int loading;
 	int error;
 	int error;
+	unsigned int gif_frames, gif_index, gif_delay, gif_next_ms;
 	int last_w, last_h;
 	int last_w, last_h;
 	char err[64];
 	char err[64];
 	char name[20];
 	char name[20];
@@ -552,6 +553,18 @@ void _start(const char *arg)
 		v.format = v.img.format;
 		v.format = v.img.format;
 		v.fit = 1;
 		v.fit = 1;
 	}
 	}
+	if (v.have_img && v.format == IMG_FMT_GIF) {
+		unsigned int frames = 0, delay = 100;
+		int ha = 0;
+
+		if (img_gif_frames(v.heap, v.file_size, &frames, &delay, &ha) == 0 &&
+		    frames > 1) {
+			v.gif_frames = frames;
+			v.gif_index = 0;
+			v.gif_delay = delay;
+			v.gif_next_ms = u_ticks_ms() + delay;
+		}
+	}
 	v.dirty = 1;
 	v.dirty = 1;
 
 
 	for (;;) {
 	for (;;) {
@@ -559,6 +572,24 @@ void _start(const char *arg)
 		struct ngui_rect body = view_body(ui);
 		struct ngui_rect body = view_body(ui);
 		int close = 0;
 		int close = 0;
 		int k;
 		int k;
+		unsigned int now = u_ticks_ms();
+
+		if (v.gif_frames > 1 &&
+		    (int)(now - v.gif_next_ms) >= 0) {
+			unsigned int d = v.gif_delay;
+
+			v.gif_index = (v.gif_index + 1) % v.gif_frames;
+			if (img_decode_gif_frame(v.heap, v.file_size,
+						 v.gif_index, &v.mem, &v.img,
+						 &d) == 0) {
+				if (d < 20) d = 20;
+				v.gif_delay = d;
+				v.dirty = 1;
+			} else {
+				v.gif_frames = 0;
+			}
+			v.gif_next_ms = u_ticks_ms() + v.gif_delay;
+		}
 
 
 		ngui_begin(ui);
 		ngui_begin(ui);
 		if (ui->w != v.last_w || ui->h != v.last_h) {
 		if (ui->w != v.last_w || ui->h != v.last_h) {

Algunos archivos no se mostraron porque demasiados archivos cambiaron en este cambio