summaryrefslogtreecommitdiff
path: root/src/host/timing_marker.zig
blob: 2d641c99f322355682dd3b0eb6962e112df07635 (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
//! Opt-in video marker: submitted frame ID and draw sample time, LSB-first.
const std = @import("std");
const abi = @import("abi");

pub fn draw(out: *std.ArrayList(abi.Command), arena: std.mem.Allocator, canvas: [2]u32, frame: u64, now: u64) !void {
    if (canvas[0] < 320 or canvas[1] < 8) return;
    const y: f32 = @floatFromInt(canvas[1] - 8);
    const milliseconds: u32 = @truncate(now / std.time.ns_per_ms);
    const bits: u80 = 0xD3A7 | (@as(u80, @as(u32, @truncate(frame))) << 16) | (@as(u80, milliseconds) << 48);
    try out.append(arena, .{ .clip = null });
    try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = y, .w = 320, .h = 8 }, .color = .black } });
    for (0..80) |i| {
        if ((bits >> @intCast(i)) & 1 == 0) continue;
        try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(i * 4), .y = y, .w = 4, .h = 8 }, .color = .white } });
    }
}

test "timing marker encodes LSB-first fields, wraps counters and fits the canvas" {
    const a = std.testing.allocator;
    var commands: std.ArrayList(abi.Command) = .empty;
    defer commands.deinit(a);
    try draw(&commands, a, .{ 960, 600 }, 0x1_0000_1234, 0x1_0000_5678 * std.time.ns_per_ms + 999999);
    try std.testing.expect(commands.items[0] == .clip and commands.items[0].clip == null);
    const background = commands.items[1].rect;
    try std.testing.expectEqual(abi.Rect{ .x = 0, .y = 592, .w = 320, .h = 8 }, background.dst);
    try std.testing.expectEqual(abi.Color.black, background.color);
    var decoded: u80 = 0;
    for (commands.items[2..]) |command| {
        const rect = command.rect;
        try std.testing.expectEqual(abi.Color.white, rect.color);
        try std.testing.expectEqual(@as(f32, 592), rect.dst.y);
        try std.testing.expectEqual(@as(f32, 4), rect.dst.w);
        try std.testing.expectEqual(@as(f32, 8), rect.dst.h);
        try std.testing.expect(rect.dst.x >= 0 and rect.dst.x < 320 and @mod(rect.dst.x, 4) == 0);
        const bit: u7 = @intFromFloat(rect.dst.x / 4);
        decoded |= @as(u80, 1) << bit;
    }
    try std.testing.expectEqual(@as(u16, 0xD3A7), @as(u16, @truncate(decoded)));
    try std.testing.expectEqual(@as(u32, 0x1234), @as(u32, @truncate(decoded >> 16)));
    try std.testing.expectEqual(@as(u32, 0x5678), @as(u32, @truncate(decoded >> 48)));
    commands.clearRetainingCapacity();
    try draw(&commands, a, .{ 319, 8 }, 0, 0);
    try draw(&commands, a, .{ 320, 7 }, 0, 0);
    try std.testing.expectEqual(@as(usize, 0), commands.items.len);
}