From 9d839a0328de52dabe4459cb0c9aef6fe9a9a212 Mon Sep 17 00:00:00 2001 From: Rekai Musuka Date: Fri, 21 Oct 2022 05:12:45 -0300 Subject: [PATCH] fix: remove DC offset from audio output --- src/apu.zig | 5 ++++- src/main.zig | 7 +++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/apu.zig b/src/apu.zig index 5a202fb..fd3b2ea 100644 --- a/src/apu.zig +++ b/src/apu.zig @@ -200,7 +200,10 @@ pub const Apu = struct { self.stream = SDL.SDL_NewAudioStream(SDL.AUDIO_U16, 2, @intCast(c_int, self.sampleRate()), SDL.AUDIO_U16, 2, host_sample_rate) orelse unreachable; } - _ = SDL.SDL_AudioStreamPut(self.stream, &[2]u16{ final_left, final_right }, 2 * @sizeOf(u16)); + // If we add 0x4040 to each sample the DC Offset is removed + // note: found this through guess and check + // FIXME: Pretty sure this is a dirty hack and should be fixed + _ = SDL.SDL_AudioStreamPut(self.stream, &[2]u16{ final_left + 0x4040, final_right + 0x4040 }, 2 * @sizeOf(u16)); self.sched.push(.SampleAudio, self.sampleTicks() -| late); } diff --git a/src/main.zig b/src/main.zig index 58dd840..85f41d7 100644 --- a/src/main.zig +++ b/src/main.zig @@ -239,10 +239,13 @@ fn initAudio(apu: *Apu) SDL.SDL_AudioDeviceID { return dev; } -// FIXME: Sometimes, we hear garbage upon program start. Why? export fn audioCallback(userdata: ?*anyopaque, stream: [*c]u8, len: c_int) void { const apu = @ptrCast(*Apu, @alignCast(8, userdata)); - _ = SDL.SDL_AudioStreamGet(apu.stream, stream, len); + const written = SDL.SDL_AudioStreamGet(apu.stream, stream, len); + + // If we don't write anything, play silence otherwise garbage will be played + // FIXME: I don't think this hack to remove DC Offset is acceptable :thinking: + if (written == 0) std.mem.set(u8, stream[0..@intCast(usize, len)], 0x80); } fn getSavePath(alloc: std.mem.Allocator) !?[]const u8 {