summaryrefslogtreecommitdiff
path: root/addons/image/image.zig
blob: 09b17ca70627d7ec0f1760ebe84eda7ddc30e3c4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//! image.zig: pictures as a pardes addon (.png .jpg .gif .bmp .ppm .pgm .tga).
//! A pane decodes its file's bytes on a job with stb_image (stb.c), at most
//! max_dim pixels a side; the core shows the RGBA fitted to the pane (or as
//! glyph art, its Petscii word). It has no record: a Restore reads the file.
const std = @import("std");
const addon = @import("addon");

const max_dim = 1280; // the longest side kept
const max_pixels = 64 << 20; // refused before decoding

extern fn pa_image_info(bytes: [*]const u8, n: c_int, w: *c_int, h: *c_int) c_int;
extern fn pa_image_load(bytes: [*]const u8, n: c_int, w: *c_int, h: *c_int) ?[*]const u8;
extern fn pa_image_resize(in: [*]const u8, w: c_int, h: c_int, out: [*]u8, nw: c_int, nh: c_int) c_int;

/// stb's memory (stb.c): the job's on a worker, else the pane's arena.
threadlocal var job: ?std.mem.Allocator = null;
export fn pa_image_mem(n: usize) ?*anyopaque {
    return ((job orelse addon.arena).alignedAlloc(u8, .@"16", n) catch return null).ptr;
}
export fn pa_image_remem(p: ?*anyopaque, old: usize, n: usize) ?*anyopaque {
    const q: [*]u8 = @ptrCast(pa_image_mem(n) orelse return null);
    if (p) |from| @memcpy(q[0..@min(old, n)], @as([*]const u8, @ptrCast(from)));
    return q;
}

/// Its width and height, if stb can read it.
fn info(bytes: []const u8) ?[2]u32 {
    var w: c_int, var h: c_int = .{ 0, 0 };
    if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int) or pa_image_info(bytes.ptr, @intCast(bytes.len), &w, &h) == 0) return null;
    return .{ @intCast(w), @intCast(h) };
}

pub const Image = struct {
    w: u32 = 0,
    h: u32 = 0,
    rgba: ?[]const u8 = null, // w x h, once its job is done

    pub const head: addon.Head = .{ .name = "image", .version = 1, .exts = ".png .jpg .jpeg .gif .bmp .ppm .pgm .tga", .pictures = true };

    /// Decoded on a job; one it cannot read (corrupt, truncated, not what
    /// its name says) is refused, rather than shown as a blank pane.
    pub fn open(_: *Image, _: ?[]const u8, bytes: ?[]const u8) void {
        const b = bytes orelse return;
        if (info(b) == null) return addon.say("not an image pardes can read", .err);
        _ = addon.job(b);
    }

    /// The core follows it with its art words and the path.
    pub fn prefix(_: *const Image, w: *std.Io.Writer) !void {
        try w.writeAll("img");
    }

    pub fn paint(im: *const Image, w: addon.Window, out: addon.Paint) void {
        const rgba = im.rgba orelse return;
        out.place(.{ .rgba = rgba.ptr, .w = im.w, .h = im.h, .src = .{ .w = im.w, .h = im.h }, .dst = .{ .w = w.cols, .h = w.rows } });
    }

    /// On a worker: width and height (little endian), then the RGBA.
    pub fn jobRun(in: []const u8, gpa: std.mem.Allocator) ?[]u8 {
        job = gpa;
        defer job = null;
        const wh = info(in) orelse return null;
        if (@as(u64, wh[0]) * wh[1] > max_pixels) return null;
        var w: c_int, var h: c_int = .{ 0, 0 };
        var px = pa_image_load(in.ptr, @intCast(in.len), &w, &h) orelse return null;
        const longest: u64 = @max(wh[0], wh[1]);
        var nw, var nh = wh;
        if (longest > max_dim) {
            nw = @max(1, @as(u32, @intCast(@as(u64, wh[0]) * max_dim / longest)));
            nh = @max(1, @as(u32, @intCast(@as(u64, wh[1]) * max_dim / longest)));
            const small = gpa.alloc(u8, @as(usize, nw) * nh * 4) catch return null;
            if (pa_image_resize(px, w, h, small.ptr, @intCast(nw), @intCast(nh)) == 0) return null;
            px = small.ptr;
        }
        const a = gpa.alloc(u8, 8 + @as(usize, nw) * nh * 4) catch return null; // the last: the answer
        std.mem.writeInt(u32, a[0..4], nw, .little);
        std.mem.writeInt(u32, a[4..8], nh, .little);
        @memcpy(a[8..], px[0 .. a.len - 8]);
        return a;
    }

    pub fn jobDone(im: *Image, _: u32, out: []const u8) void {
        if (out.len < 8) return;
        const w = std.mem.readInt(u32, out[0..4], .little);
        const h = std.mem.readInt(u32, out[4..8], .little);
        if (@as(u64, w) * h * 4 != out.len - 8) return;
        im.rgba = addon.arena.dupe(u8, out[8..]) catch return;
        im.w, im.h = .{ w, h };
    }
};

pub const pardes_addon = addon.ops(Image);
comptime {
    addon.exportLib(&pardes_addon);
}

test "a job decodes a picture to its size and pixels, and one past max_dim is scaled to fit" {
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    const png = "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\xcf\xc0\x00\x00\x03\x01\x01\x00\xc9\xfe\x92\xef\x00\x00\x00\x00IEND\xaeB`\x82";
    const got = Image.jobRun(png, arena.allocator()).?;
    try std.testing.expectEqualSlices(u8, &.{ 1, 0, 0, 0, 1, 0, 0, 0, 0xff, 0, 0, 0xff }, got);
    // A PPM 2600x1: 1280x1 after.
    var ppm: std.ArrayList(u8) = .empty;
    try ppm.print(arena.allocator(), "P6\n2600 1\n255\n", .{});
    try ppm.appendNTimes(arena.allocator(), 0x80, 2600 * 3);
    const wide = Image.jobRun(ppm.items, arena.allocator()).?;
    try std.testing.expectEqual(1280, std.mem.readInt(u32, wide[0..4], .little));
    try std.testing.expectEqual(8 + 1280 * 4, wide.len);
    try std.testing.expect(Image.jobRun("not a picture", arena.allocator()) == null);
}