about summary refs log tree commit diff
path: root/src/brr.zig
blob: bbacdd793c6a0ad8b0230573c7860f4bf3f8ab30 (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
const std = @import("std");
const c = @cImport({
    @cInclude("mpg123.h");
    @cInclude("alsa/asoundlib.h");
});

pub fn brr(allocator: std.mem.Allocator, file: [*:0]const u8) !void {
    _ = c.mpg123_init();
    const handle = c.mpg123_new(null, null) orelse {
        std.log.warn("Failed to create mpg123 handle\n", .{});
        return;
    };

    if (c.mpg123_open(handle, file) != c.MPG123_OK) {
        std.log.warn("Failed to open the file: {s}\n", .{file});
        return;
    }

    var encoding: c_int = 0;
    var channels: c_int = 0;
    var rate: c_long = 0;
    if (c.mpg123_getformat(handle, &rate, &channels, &encoding) != c.MPG123_OK) {
        std.log.warn("Failed to get format\n", .{});
        return;
    }

    var pcm: ?*c.snd_pcm_t = undefined;
    if (c.snd_pcm_open(&pcm, "default", c.SND_PCM_STREAM_PLAYBACK, 0) < 0) {
        std.log.warn("Failed to open ALSA device\n", .{});
        return;
    }

    var dir: c_int = 0;
    var params: ?*c.snd_pcm_hw_params_t = null;
    if (c.snd_pcm_hw_params_malloc(&params) < 0) {
        std.log.warn("Failed to allocate ALSA hardware parameters\n", .{});
        return;
    }

    _ = c.snd_pcm_hw_params_any(pcm, params);
    _ = c.snd_pcm_hw_params_set_access(pcm, params, c.SND_PCM_ACCESS_RW_INTERLEAVED);
    _ = c.snd_pcm_hw_params_set_format(pcm, params, c.SND_PCM_FORMAT_S16_LE);
    _ = c.snd_pcm_hw_params_set_channels(pcm, params, @as(c_uint, @intCast(channels)));
    _ = c.snd_pcm_hw_params_set_rate_near(pcm, params, @as(*c_uint, @ptrCast(&rate)), &dir);
    if (c.snd_pcm_hw_params(pcm, params) < 0) {
        std.log.warn("Failed to set ALSA hardware parameters\n", .{});
        return;
    }

    const buffer_size = c.mpg123_outblock(handle);
    var done: usize = 0;

    var mpg123_buffer: []u8 = try allocator.alloc(u8, buffer_size);
    _ = &mpg123_buffer;
    defer allocator.free(mpg123_buffer);

    var result: c_int = 0;
    while (true) {
        result = c.mpg123_read(handle, @as(?*anyopaque, @ptrCast(mpg123_buffer.ptr)), buffer_size, &done);
        switch (result) {
            c.MPG123_OK => {
                _ = c.snd_pcm_writei(pcm, @as(?*anyopaque, @ptrCast(mpg123_buffer.ptr)), done / 4);
            },
            else => {
                const err_str = c.mpg123_strerror(handle);
                std.log.warn("Failed to read from file\n {}, {s}", .{ result, err_str });
                break;
            },
        }
    }

    _ = c.mpg123_delete(handle);
    _ = c.snd_pcm_hw_params_free(params);
    _ = c.snd_pcm_close(pcm);
    _ = c.mpg123_exit();
}