summaryrefslogtreecommitdiff
path: root/src/host/root.zig
blob: 5889b42ff41e36b5938fee58312ab22a1a561a33 (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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//! The sketchbook host: runs a sketch linked in, or loaded from a library
//! that it hot-reloads whenever a build replaces it.
//!
//!     sketchbook [options] [LIBRARY]
//!       --state FILE         persistent state (default: $XDG_DATA_HOME/<name>/<name>.state;
//!                            sketch.state for a script or an export)
//!       --headless           offscreen video, silent audio
//!       --script FILE        play a script instead of reading devices
//!       --fresh              start from default state (sessions, marks and clips are kept)
//!       --timing-marker      encode frame ID and draw sample time for video analysis
//!       --profile-gpu        time each GPU command alone, print the times at exit
//!       --console LINE       run a console line once the sketch is loaded (repeatable)
//!       --define NAME=VALUE  substitute {NAME} in the script
//!       --export DIR|-       headless, from fresh state: every frame as DIR/000000.png, ...
//!                            or for - as raw RGBA on stdout, until the sketch quits
//!       --fps N              export: frames a second (60); each tick is exactly 1/N s
//!       --frames N           export: stop after N frames
//!       --size WxH           the first canvas and, headless, the room for it
const std = @import("std");
const c = @import("c");
const abi = @import("abi");
pub const Host = @import("Host.zig");
pub const memory = @import("memory.zig");
pub const fields = @import("fields.zig");
pub const script = @import("script.zig");
pub const timeline = @import("timeline.zig");

/// Entry point for both the generic host (`linked == null`) and apps that
/// link their sketch in.
pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
    const gpa = init.gpa;
    var options: Host.Options = .{};
    var script_path: ?[]const u8 = null;
    var defines: std.ArrayList([2][]const u8) = .empty;
    defer defines.deinit(gpa);
    var lines: std.ArrayList([]const u8) = .empty;
    defer lines.deinit(gpa);

    var args = init.minimal.args.iterate();
    _ = args.skip();
    while (args.next()) |arg| {
        if (std.mem.eql(u8, arg, "--state")) {
            options.state = args.next() orelse fatal("--state needs a file");
        } else if (std.mem.eql(u8, arg, "--9p")) {
            options.ninep = args.next() orelse fatal("--9p needs a socket path");
        } else if (std.mem.eql(u8, arg, "--fresh")) {
            options.fresh = true;
        } else if (std.mem.eql(u8, arg, "--headless")) {
            options.headless = true;
        } else if (std.mem.eql(u8, arg, "--timing-marker")) {
            options.timing_marker = true;
        } else if (std.mem.eql(u8, arg, "--profile-gpu")) {
            options.profile_gpu = true;
        } else if (std.mem.eql(u8, arg, "--console")) {
            try lines.append(gpa, args.next() orelse fatal("--console needs a line"));
        } else if (std.mem.eql(u8, arg, "--script")) {
            script_path = args.next() orelse fatal("--script needs a file");
            options.script = true;
        } else if (std.mem.eql(u8, arg, "--define")) {
            const pair = args.next() orelse fatal("--define needs NAME=VALUE");
            const eq = std.mem.indexOfScalar(u8, pair, '=') orelse fatal("--define needs NAME=VALUE");
            try defines.append(gpa, .{ pair[0..eq], pair[eq + 1 ..] });
        } else if (std.mem.eql(u8, arg, "--export")) {
            options.export_to = args.next() orelse fatal("--export needs a directory, or - for stdout");
            options.headless = true;
            options.fresh = true;
        } else if (std.mem.eql(u8, arg, "--fps")) {
            options.fps = std.fmt.parseInt(u32, args.next() orelse "", 10) catch 0;
            if (options.fps == 0) fatal("--fps needs a whole number of frames a second");
        } else if (std.mem.eql(u8, arg, "--frames")) {
            options.frames = std.fmt.parseInt(u64, args.next() orelse "", 10) catch fatal("--frames needs a number");
        } else if (std.mem.eql(u8, arg, "--size")) {
            const size = args.next() orelse "";
            const x = std.mem.indexOfScalar(u8, size, 'x') orelse fatal("--size needs WxH");
            const w = std.fmt.parseInt(u32, size[0..x], 10) catch 0;
            const h = std.fmt.parseInt(u32, size[x + 1 ..], 10) catch 0;
            if (w == 0 or h == 0) fatal("--size needs WxH");
            options.size = .{ w, h };
        } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) {
            std.debug.print("{s}", .{usage});
            return;
        } else if (std.mem.startsWith(u8, arg, "-")) {
            fatal("unknown option (see --help)");
        } else {
            options.library = arg;
        }
    }
    if (linked == null and options.library == null) fatal("no sketch library given (see --help)");
    if (options.export_to) |to| {
        if (script_path != null) fatal("--export plays no script: it runs the sketch on its own");
        if (!std.mem.eql(u8, to, "-")) {
            try std.Io.Dir.cwd().createDirPath(init.io, to);
        } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg");
    }

    // A scripted run from fresh state works on files of its own, moved to
    // the given path at exit: two runs of one build step (two `zig build`s
    // at once share its output path) never share a state or store file,
    // nor fail on the store's lock (its sessions are in memory). An export's are
    // removed instead: nothing reads them, and a player may have the given
    // ones open.
    var private_buf: [std.fs.max_path_bytes]u8 = undefined;
    if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.state";
    const given = options.state;
    const private = (script_path != null or options.export_to != null) and options.fresh;
    if (!private) sketchbookDir(init.io, given);
    if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long");
    defer if (private) for ([_][]const u8{ "", ".store" }) |suffix| {
        var from: [std.fs.max_path_bytes + 16]u8 = undefined;
        var to: [std.fs.max_path_bytes + 16]u8 = undefined;
        const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue;
        const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue;
        _ = if (options.export_to != null) std.os.linux.unlink(a.ptr) else std.os.linux.rename(a.ptr, b.ptr);
    };

    sdl_heap.install();
    {
        var host: Host = undefined;
        try host.init(gpa, init.io, init.environ_map, options, linked);
        defer host.deinit();
        for (lines.items) |line| host.runLine(line, c.SDL_GetTicksNS()) catch {};
        if (script_path) |path| {
            const source = try std.Io.Dir.cwd().readFileAlloc(init.io, path, gpa, .limited(1 << 20));
            defer gpa.free(source);
            try script.run(&host, source, defines.items);
        } else try host.run();
    }
    if (sdl_heap.leaked()) return error.LeakedSdlMemory;
}

const usage =
    \\usage: sketchbook [options] [LIBRARY]
    \\  --9p SOCKET          local 9P controls: ctl, status, log, screen.png
    \\  --state FILE         persistent state; sessions are kept beside it (default:
    \\                       $XDG_DATA_HOME/<name>/<name>.state, sketch.state for --script, --export)
    \\  --headless           offscreen video, silent audio, no vsync
    \\  --script FILE        play a script instead of reading devices
    \\  --fresh              start from default state (sessions, marks and clips are kept)
    \\  --timing-marker      encode frame ID and draw sample time for video analysis
    \\  --profile-gpu        time each GPU command alone, print the times at exit
    \\  --console LINE       run a console line once the sketch is loaded (repeatable)
    \\  --define NAME=VALUE  substitute {NAME} in the script
    \\  --export DIR|-       headless, from fresh state: every frame as DIR/000000.png, ...
    \\                       or for - as raw RGBA on stdout, until the sketch quits
    \\  --fps N              export: frames a second (60); each tick is exactly 1/N s
    \\  --frames N           export: stop after N frames
    \\  --size WxH           the first canvas and, headless, the room for it
    \\
;

/// A state file in a directory named `.sketchbook` (`zig build run`'s):
/// the directory is made, with a `.gitignore` of `*` (its sessions database
/// grows, and a jj snapshot would commit it), and the state and store files
/// an older build kept beside it are moved in, once. A file is never
/// replaced: when both exist, nothing moves.
fn sketchbookDir(io: std.Io, state: []const u8) void {
    const dir = std.fs.path.dirname(state) orelse return;
    if (!std.mem.eql(u8, std.fs.path.basename(dir), ".sketchbook")) return;
    const cwd = std.Io.Dir.cwd();
    cwd.createDirPath(io, dir) catch return;
    var buf: [std.fs.max_path_bytes]u8 = undefined;
    const ignore = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{dir}) catch return;
    cwd.writeFile(io, .{ .sub_path = ignore, .data = "*\n", .flags = .{ .exclusive = true } }) catch {};
    for ([_][]const u8{ "", ".store" }) |suffix| {
        var from_buf: [std.fs.max_path_bytes]u8 = undefined;
        var to_buf: [std.fs.max_path_bytes]u8 = undefined;
        const parent = std.fs.path.dirname(dir) orelse ".";
        const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}{s}", .{ parent, std.fs.path.basename(state), suffix }, 0) catch return;
        const to = std.fmt.bufPrintSentinel(&to_buf, "{s}{s}", .{ state, suffix }, 0) catch return;
        switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) {
            .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }),
            .EXIST => {
                std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to });
                return;
            },
            else => {},
        }
    }
}

fn fatal(message: []const u8) noreturn {
    std.debug.print("sketchbook: {s}\n", .{message});
    std.process.exit(2);
}

/// SDL's allocations go through a leak-checking allocator of their own, so a
/// session that leaks SDL memory fails loudly at exit.
const sdl_heap = struct {
    var debug: std.heap.DebugAllocator(.{ .backing_allocator_zeroes = false }) = .{};
    const alignment: std.mem.Alignment = .of(std.c.max_align_t);
    const header = alignment.forward(@sizeOf(usize));

    fn install() void {
        _ = c.SDL_SetMemoryFunctions(malloc, calloc, realloc, free);
    }
    fn leaked() bool {
        return debug.deinit() == .leak;
    }
    fn block(size: usize) ?[*]u8 {
        const total = std.math.add(usize, header, size) catch return null;
        const base = debug.allocator().rawAlloc(total, alignment, @returnAddress()) orelse return null;
        @as(*usize, @ptrCast(@alignCast(base))).* = total;
        return base + header;
    }
    fn whole(mem: *anyopaque) []u8 {
        const base: [*]u8 = @as([*]u8, @ptrCast(mem)) - header;
        return base[0..@as(*const usize, @ptrCast(@alignCast(base))).*];
    }
    fn malloc(size: usize) callconv(.c) ?*anyopaque {
        return block(size);
    }
    fn calloc(n: usize, size: usize) callconv(.c) ?*anyopaque {
        const bytes = std.math.mul(usize, n, size) catch return null;
        const mem = block(bytes) orelse return null;
        @memset(mem[0..bytes], 0);
        return mem;
    }
    fn realloc(maybe: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque {
        const old = whole(maybe orelse return malloc(size));
        const total = std.math.add(usize, header, size) catch return null;
        if (debug.allocator().rawRemap(old, alignment, total, @returnAddress())) |base| {
            @as(*usize, @ptrCast(@alignCast(base))).* = total;
            return base + header;
        }
        const new = block(size) orelse return null;
        @memcpy(new[0..@min(size, old.len - header)], old[header..][0..@min(size, old.len - header)]);
        debug.allocator().rawFree(old, alignment, @returnAddress());
        return new;
    }
    fn free(maybe: ?*anyopaque) callconv(.c) void {
        debug.allocator().rawFree(whole(maybe orelse return), alignment, @returnAddress());
    }
};

test {
    _ = Host;
    _ = memory;
    _ = fields;
    _ = timeline;
    _ = @import("Sessions.zig");
    _ = @import("audio.zig");
    _ = @import("Console.zig");
    _ = @import("control.zig");
    _ = @import("timing_marker.zig");
}