aboutsummaryrefslogtreecommitdiff
path: root/src/main.zig
blob: 9fccdeda3cf68bffc11193b4669bc14473d330e1 (plain)
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
const std = @import("std");
const posix = std.posix;
const io = std.Io;

const sdl3 = @import("sdl3");
const mixer = sdl3.mixer;

/// How long to sleep between event-loop iterations, in milliseconds.
const poll_interval_ms = 50;

const song = "assets/chico.wav";

// isso pra sistemas linux
const STDIN_FD: posix.fd_t = 0;

pub fn main(
    init: std.process.Init,
) !void
{
    defer sdl3.shutdown();

    const log_app = sdl3.log.Category.application;

    try sdl3.init(.{ .audio = true });
    defer sdl3.quit(.{ .audio = true });

    try mixer.init();
    defer mixer.quit();

    const compiled_version = mixer.Version.compiled_against;
    const linked_version = mixer.Version.get();
    try log_app.logInfo("Using SDL_mixer {d}.{d}.{d}", .{ compiled_version.getMajor(), compiled_version.getMinor(), compiled_version.getMicro() });
    try log_app.logInfo("Linked against SDL_mixer {d}.{d}.{d}", .{ linked_version.getMajor(), linked_version.getMinor(), linked_version.getMicro() });

    // Open a mixer on the default playback device, letting SDL mixer pick the format.
    const mixer_device = try mixer.Mixer.initDevice(sdl3.audio.Device.default_playback, null);
    defer mixer_device.deinit();

    const wav = try mixer.Audio.init(mixer_device, song, true);
    defer wav.deinit();

    const metadata = try wav.getProperties();
    const titulo = metadata.title orelse "";
    const artista = metadata.artist orelse "";
    const album = metadata.album orelse "";

    const duracao_frames = metadata.duration_frames orelse 0;
    const duracao_ms = try wav.framesToMs(duracao_frames);
    const duracao = try msToDuration(init.gpa, duracao_ms);
    defer init.gpa.free(duracao);

    const track = try mixer.Track.init(mixer_device);
    defer track.deinit();
    try track.setAudio(wav);

    try track.play(.{});

    // estado original do terminal
    const termios_ro = try posix.tcgetattr(STDIN_FD);

    // ativa modo `raw` do terminal
    var termios_rw = termios_ro;

    termios_rw.oflag.OPOST = false;

    termios_rw.iflag.IXON = false;
    termios_rw.iflag.ICRNL = false;

    termios_rw.lflag.ECHO = false;
    termios_rw.lflag.ICANON = false;
    termios_rw.lflag.ISIG = false;
    termios_rw.lflag.IEXTEN = false;

    try posix.tcsetattr(STDIN_FD, .FLUSH, termios_rw);

    var stdout = io.File.stdout();
    var stdin = io.File.stdin();

    var w_buffer: [256]u8 = undefined;
    var stdout_writer = stdout.writer(init.io, &w_buffer);
    const writer_interface = &stdout_writer.interface;

    var quit_app = false;
    while (!quit_app) {
        try writer_interface.print("\r{s}", .{ duracao });
        try writer_interface.print("\x1B[1E", .{});
        try writer_interface.print("\r{s} | {s} | {s}", .{ titulo, artista, album });
        try writer_interface.print("\x1B[1F", .{});
        try writer_interface.print("\x1B[1E", .{});
        try writer_interface.print("\r<Espaço>: pausar/reproduzir | q: sair", .{});
        try writer_interface.print("\x1B[1F", .{});
        try writer_interface.flush();

        // lê comandos
        var r_buffer: [64]u8 = undefined;
        var stdin_reader = stdin.reader(init.io, &r_buffer);
        const reader_interface = &stdin_reader.interface;
        // lê apenas um caractere da stdin
        const char = try reader_interface.peek(1);
        if (std.mem.eql(u8, char, " ")) {
            if (track.isPaused()) {
                try track.resumeTrack();
            } else {
                try track.pause();
            }
        } else if (std.mem.eql(u8, char, "q")) {
            quit_app = true;
        }

        sdl3.timer.delayMilliseconds(poll_interval_ms);
    }

    // restaura terminal pro estado original ao final
    try posix.tcsetattr(0, .FLUSH, termios_ro);

    try track.stop(0);
    try log_app.logInfo("Quit.", .{});
}

/// Transforma milissegundos em duração padrão no formato MM:ss
fn msToDuration(all: std.mem.Allocator, ms: usize) std.mem.Allocator.Error![]const u8
{
    const seg_raw = ms / 1000;
    const min = seg_raw / 60;
    const seg = seg_raw % 60;

    // TODO: evitar essa alocação! retorne uma tupla com .{min, seg}
    // e só formate na hora de imprimir pro `stdout`
    // vou fazer um commit com essa parte somente pra fins de estudo
    return std.fmt.allocPrint(all, "{d}:{d}", .{min, seg});
}