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}{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, }; } };