aboutsummaryrefslogtreecommitdiff
path: root/src/main.zig
blob: d024892afbbb800131943eb407fe03e77a65f1d4 (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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
const std = @import("std");
const posix = std.posix;

const sdl3 = @import("sdl3");

/// para mais informações, ler `termios(3)`
/// número mínimo de caracteres a serem lidos no modo `raw`
/// timeout para ler a stdin, em decisegundos
const VMIN = @intFromEnum(std.os.linux.V.MIN);
const VTIME = @intFromEnum(std.os.linux.V.TIME);

/// ANSI escape codes
/// https://en.wikipedia.org/wiki/ANSI_escape_code#Control_Sequence_Introducer_commands
const CNL = "\x1B[1E";
const CPL = "\x1B[1F";
const REVERSE = "\x1B[7m";
const NOT_REVERSE = "\x1B[27m";

/// interface
const BARRA = "█";
const PONTO = "•";

var stdout = std.Io.File.stdout();
var stdin = std.Io.File.stdin();

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

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

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

    const mixer = try sdl3.mixer.Mixer.initDevice(sdl3.audio.Device.default_playback, null);
    defer mixer.deinit();

    var args = try init.minimal.args.iterateAllocator(init.gpa);
    defer args.deinit();

    const page_allocator = std.heap.page_allocator;
    var playlist = Queue.init(page_allocator);
    defer playlist.deinit();
    _ = args.skip(); //  primeiro argumento é o nome do arquivo
                     // TODO: aceitar múltiplos arquivos e colocá-los em uma FILA!!
    while (args.next()) |arg| {
        const path = std.fs.path.parsePath(arg);
        var dir: std.Io.Dir = std.Io.Dir.cwd();
        if (path.kind == .absolute) {
            std.Io.Dir.accessAbsolute(init.io, path.root, .{}) catch |err| switch (err) {
                error.FileNotFound => {
                    std.debug.print("[ERROR] Directory {s} not found.\n", .{path.root});
                    return err;
                },
                else => {
                    std.debug.print("Unknown: {t}\n", .{err});
                    return err;
                },
            };
        } else {
            dir.access(init.io, ".", .{}) catch |err| switch (err) {
                error.FileNotFound => {
                    std.debug.print("[ERROR] File {s} not found.\n", .{arg});
                    return err;
                },
                else => {
                    std.debug.print("Unknown: {t}.\n", .{err});
                    return err;
                },
            };
        }

        const audio = sdl3.mixer.Audio.init(mixer, arg, true) catch |err| {
            std.debug.print("[ERROR] file {s} is not a valid audio file.\n", .{arg});
            return err;
        };

        const song = try Song.from_audio(audio);

        try playlist.enqueue(song);
    }

    const track = try sdl3.mixer.Track.init(mixer);
    defer track.deinit();

    const termios_original = try terminal_raw_mode();

    for (playlist.buf.items) |cur| {

        try track.setAudio(cur.audio);

        try track.play(.{});
        // só por enquanto pq toda vez estoura meu tímpano
        try mixer.setGain(0.2);

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

        var ms_atual: usize = 0;
        var duracao_loop: usize = 0;

        var quit_app = false;
        while (!quit_app) {
            const inicio_loop = std.Io.Clock.now(.real, init.io);

            // lê comandos
            var r_buffer: [64]u8 = undefined;
            var stdin_reader = stdin.reader(init.io, &r_buffer);
            const reader_interface = &stdin_reader.interface;
            // https://github.com/rockorager/libvaxis/blob/d4c3b3666e0c090e2b5092ca09893c6db15e0b79/src/widgets/terminal/Parser.zig
            const byte = reader_interface.takeByte() catch 0;
            switch (byte) {
                0x1B => {
                    var next = try reader_interface.takeByte();
                    if (next != '[') {
                        continue;
                    }
                    next = try reader_interface.takeByte();
                    switch (next) {
                        // https://en.wikipedia.org/wiki/ANSI_escape_code#Terminal_input_sequences
                        // seta pra esquerda
                        'D' => {
                            const cur_frame = try track.getPlaybackPosition();
                            const framesFromMs = try track.msToFrames(5000);
                            if (cur_frame <= framesFromMs) {
                                try track.setPlaybackPosition(0);
                                ms_atual = 0;
                                continue;
                            }

                            const frames_decorridos = cur_frame - framesFromMs;
                            if (track.getRemaining()) |frames_restantes| {
                                if (frames_restantes == 0) {
                                    try track.play(.{ .start_frame = (cur.duration() - framesFromMs) });
                                } else if (frames_restantes > 0) {
                                    try track.setPlaybackPosition(frames_decorridos);
                                } else {
                                    return error.Unknown;
                                }
                            }
                            ms_atual = if (ms_atual <= 5000) 0 else ms_atual - 5000;
                        },
                        // seta pra direita
                        'C' => {
                            const cur_frame = try track.getPlaybackPosition();
                            const framesFromMs = try track.msToFrames(5000);
                            if ((cur.duration() - cur_frame) <= framesFromMs) {
                                try track.setPlaybackPosition(cur.duration());
                                continue;
                            }

                            const frames_decorridos = cur_frame + framesFromMs;
                            try track.setPlaybackPosition(frames_decorridos);
                            ms_atual = if ((try playlist.cur.duration_ms() - ms_atual) <= 5000) try playlist.cur.duration_ms() else ms_atual + 5000;
                        },
                        else => {
                            continue;
                        },
                    }
                },
                ' ' => {
                    if (track.isPaused()) {
                        try track.resumeTrack();
                    } else {
                        try track.pause();
                    }
                },
                'q' => quit_app = true,
                '=', '+' => {
                    const cur_gain = mixer.getGain();
                    try mixer.setGain(cur_gain + 0.1);
                },
                '-' => {
                    const cur_gain = mixer.getGain();
                    try track.setGain(cur_gain - 0.1);
                },
                else => {},
            }

            try print_interface(&stdout_writer.interface, mixer, &playlist.cur, ms_atual);

            const fim_loop = std.Io.Clock.now(.real, init.io);
            duracao_loop = @as(usize, @intCast(inicio_loop.durationTo(fim_loop).toMilliseconds()));
            if (!track.isPaused()) {
                ms_atual += duracao_loop;
            }
        }
    }

    try reset_terminal(termios_original);
    try track.stop(0);
}

/// Transforma milissegundos em duração padrão no formato MM:ss
fn msToElapsedTime(ms: usize) [2]usize {
    if (ms == 0) {
        return .{ 0, 0 };
    }

    const seg_raw = ms / 1000;
    const min = seg_raw / 60;
    const seg = seg_raw % 60;

    return .{ min, seg };
}

fn print_interface(
    writer: *std.Io.Writer,
    mixer: sdl3.mixer.Mixer,
    song: *Song,
    ms_atual: usize,
) !void {
    const duracao_ms = try song.duration_ms();
    const minutos, const segundos = msToElapsedTime(duracao_ms);
    const ms_por_parcela: usize = duracao_ms / 100;
    const min_decorrido, const seg_decorrido = msToElapsedTime(ms_atual);

    // BARRA DE PROGRESSO:
    // dividir a duração da música em 100 parcelas de x segundos
    // para cada x segundos decorridos, renderizar x * █
    // depois disso, renderizar (100 - x) * • para os segundos não decorridos
    const num_parcelas = duracao_ms / ms_por_parcela;
    _ = try writer.writeAll("\r");
    _ = try writer.splatBytesAll(BARRA, num_parcelas);
    _ = try writer.splatBytesAll(PONTO, (100 - num_parcelas));
    try writer.flush();
    try writer.print(CNL, .{});

    try writer.print("\r{d}:{d:02} / {d}:{d:02}", .{
        min_decorrido,
        seg_decorrido,
        minutos,
        segundos,
    });
    try writer.print(CNL, .{});
    try writer.print("\rVolume: {d}\r", .{@round(mixer.getGain() * 100)});
    try writer.print(CNL, .{});
    try writer.print("\r{s} | {s} | {s}", .{ song.title, song.artist, song.album });
    try writer.print(CNL, .{});
    try writer.print("\r{s}<Espaço>{s}: pausar/reproduzir | =/+: aumentar volume | -: diminuir volume | q: sair", .{
        REVERSE,
        NOT_REVERSE,
    });
    try writer.print(CPL, .{});
    try writer.print(CPL, .{});
    try writer.print(CPL, .{});
    try writer.print(CPL, .{});
    try writer.flush();
}

/// Ativa modo `raw` ou `não-canônico` do terminal
fn terminal_raw_mode() !std.posix.termios {
    // estado original do terminal
    const termios_ro = try posix.tcgetattr(stdin.handle);

    var termios_rw = termios_ro;

    termios_rw.oflag.OPOST = false;

    termios_rw.iflag.IGNBRK = false;
    termios_rw.iflag.BRKINT = false;
    termios_rw.iflag.PARMRK = false;
    termios_rw.iflag.ISTRIP = false;
    termios_rw.iflag.INLCR = false;
    termios_rw.iflag.ICRNL = false;
    termios_rw.iflag.IGNCR = false;
    termios_rw.iflag.IXON = false;

    termios_rw.oflag.OPOST = false;

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

    termios_rw.cflag.CSIZE = .CS8;
    termios_rw.cflag.PARENB = false;

    termios_rw.cc[VMIN] = 0;
    termios_rw.cc[VTIME] = 1;

    try posix.tcsetattr(stdin.handle, .FLUSH, termios_rw);

    return termios_ro;
}

/// Restaura terminal pro estado original
fn reset_terminal(original: std.posix.termios) !void {
    try posix.tcsetattr(0, .FLUSH, original);
}

const Queue = struct {
    const Self = @This();

    alloc: std.mem.Allocator,

    cur: Song,
    // TODO: caso decida usar `miniaudio` no futuro, alterar o tipo
    buf: std.ArrayList(Song),

    pub fn length(self: Self) usize {
        return self.buf.len;
    }

    pub fn init(alloc: std.mem.Allocator) Queue {
        return Queue{
            .alloc = alloc,
            .cur = undefined,
            .buf = .empty,
        };
    }

    pub fn deinit(self: *Self) void {
        for (self.buf.items) |item| {
            item.audio.deinit();
        }
        self.buf.deinit(self.alloc);
    }

    pub fn enqueue(self: *Self, song: Song) !void {
        try self.buf.append(self.alloc, song);
    }

    pub fn dequeue(self: *Self) sdl3.mixer.Audio {
        // TODO: nem sempre a música a se retirar é a última
        return self.buf.pop();
    }
};

const Song = struct {
    const Self = @This();

    audio: sdl3.mixer.Audio,
    title: []const u8,
    artist: []const u8,
    album: []const u8,

    pub fn duration(self: Self) usize {
        const audio_duration = self.audio.getDuration() orelse unreachable;

        return audio_duration.frames;
    }

    pub fn duration_ms(self: *Self) !usize {
        return try self.audio.framesToMs(self.duration());
    }

    pub fn from_audio(audio: sdl3.mixer.Audio) !Song {
        const metadata = try audio.getProperties();
        const title = metadata.title orelse "";
        const artist = metadata.artist orelse "";
        const album = metadata.album orelse "";

        return Song{
            .audio = audio,
            .title = title,
            .artist = artist,
            .album = album,
        };
    }
};