Compare commits

...

4 Commits

Author SHA1 Message Date
Rekai Nyangadzayi Musuka 937e4f67fb fix: update GpioData extern union
u4's are no longer supported in extern unions :\
2022-09-09 05:17:20 -03:00
Rekai Nyangadzayi Musuka 0ffccde402 tmp: incomplete impl of GPIO + RTC 2022-09-09 05:17:20 -03:00
Rekai Nyangadzayi Musuka 65cfc97f28 feat: reimplement audio sync
APU will now drop samples if the Audio Queue is already full, therefore
creating a "sped-up" effect when the emulator runs faster than 100%
2022-09-08 20:38:42 -03:00
Rekai Nyangadzayi Musuka fa862f095a chore: move arm/thumb lut idx functions 2022-09-06 23:58:24 -03:00
6 changed files with 482 additions and 56 deletions

View File

@ -180,11 +180,11 @@ const Audio = struct {
export fn callback(userdata: ?*anyopaque, stream: [*c]u8, len: c_int) void {
const apu = @ptrCast(*Apu, @alignCast(@alignOf(*Apu), userdata));
const written = SDL.SDL_AudioStreamGet(apu.stream, stream, len);
_ = 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)], 0x40);
// if (written == 0) std.mem.set(u8, stream[0..@intCast(usize, len)], 0x40);
}
};

View File

@ -163,6 +163,8 @@ pub const Apu = struct {
fs: FrameSequencer,
capacitor: f32,
is_buffer_full: bool,
pub fn init(sched: *Scheduler) Self {
const apu: Self = .{
.ch1 = ToneSweep.init(sched),
@ -178,11 +180,12 @@ pub const Apu = struct {
.bias = .{ .raw = 0x0200 },
.sampling_cycle = 0b00,
.stream = SDL.SDL_NewAudioStream(SDL.AUDIO_U16, 2, 1 << 15, SDL.AUDIO_U16, 2, host_sample_rate) orelse unreachable,
.stream = SDL.SDL_NewAudioStream(SDL.AUDIO_U16, 2, 1 << 15, SDL.AUDIO_U16, 2, host_sample_rate).?,
.sched = sched,
.capacitor = 0,
.fs = FrameSequencer.init(),
.is_buffer_full = false,
};
sched.push(.SampleAudio, apu.sampleTicks());
@ -277,6 +280,13 @@ pub const Apu = struct {
}
pub fn sampleAudio(self: *Self, late: u64) void {
self.sched.push(.SampleAudio, self.sampleTicks() -| late);
// Whether the APU is busy or not is determined by the main loop in emu.zig
// This should only ever be true (because this side of the emu is single threaded)
// When audio sync is disaabled
if (self.is_buffer_full) return;
var left: i16 = 0;
var right: i16 = 0;
@ -325,28 +335,30 @@ pub const Apu = struct {
left += bias;
right += bias;
const tmp_left = std.math.clamp(@bitCast(u16, left), std.math.minInt(u11), std.math.maxInt(u11));
const tmp_right = std.math.clamp(@bitCast(u16, right), std.math.minInt(u11), std.math.maxInt(u11));
const clamped_left = std.math.clamp(@bitCast(u16, left), std.math.minInt(u11), std.math.maxInt(u11));
const clamped_right = std.math.clamp(@bitCast(u16, right), std.math.minInt(u11), std.math.maxInt(u11));
// Extend to 16-bit signed audio samples
const final_left = (tmp_left << 5) | (tmp_left >> 6);
const final_right = (tmp_right << 5) | (tmp_right >> 6);
const ext_left = (clamped_left << 5) | (clamped_left >> 6);
const ext_right = (clamped_right << 5) | (clamped_right >> 6);
if (self.sampling_cycle != self.bias.sampling_cycle.read()) {
const new_sample_rate = Self.sampleRate(self.bias.sampling_cycle.read());
log.info("Sample Rate changed from {}Hz to {}Hz", .{ Self.sampleRate(self.sampling_cycle), new_sample_rate });
// FIXME: This rarely happens
if (self.sampling_cycle != self.bias.sampling_cycle.read()) self.replaceSDLResampler();
// Sample Rate Changed, Create a new Resampler since i can't figure out how to change
// the parameters of the old one
const old = self.stream;
defer SDL.SDL_FreeAudioStream(old);
_ = SDL.SDL_AudioStreamPut(self.stream, &[2]u16{ ext_left, ext_right }, 2 * @sizeOf(u16));
}
self.sampling_cycle = self.bias.sampling_cycle.read();
self.stream = SDL.SDL_NewAudioStream(SDL.AUDIO_U16, 2, @intCast(c_int, new_sample_rate), SDL.AUDIO_U16, 2, host_sample_rate) orelse unreachable;
}
fn replaceSDLResampler(self: *Self) void {
const sample_rate = Self.sampleRate(self.bias.sampling_cycle.read());
log.info("Sample Rate changed from {}Hz to {}Hz", .{ Self.sampleRate(self.sampling_cycle), sample_rate });
_ = SDL.SDL_AudioStreamPut(self.stream, &[2]u16{ final_left, final_right }, 2 * @sizeOf(u16));
self.sched.push(.SampleAudio, self.sampleTicks() -| late);
// Sampling Cycle (Sample Rate) changed, Craete a new SDL Audio Resampler
// FIXME: Replace SDL's Audio Resampler with either a custom or more reliable one
const old_stream = self.stream;
defer SDL.SDL_FreeAudioStream(old_stream);
self.sampling_cycle = self.bias.sampling_cycle.read();
self.stream = SDL.SDL_NewAudioStream(SDL.AUDIO_U16, 2, @intCast(c_int, sample_rate), SDL.AUDIO_U16, 2, host_sample_rate).?;
}
fn sampleTicks(self: *const Self) u64 {

View File

@ -1,5 +1,7 @@
const std = @import("std");
const Bit = @import("bitfield").Bit;
const Bitfield = @import("bitfield").Bitfield;
const Backup = @import("backup.zig").Backup;
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.GamePak);
@ -10,6 +12,7 @@ title: [12]u8,
buf: []u8,
allocator: Allocator,
backup: Backup,
gpio: Gpio,
pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) !Self {
const file = try std.fs.cwd().openFile(rom_path, .{});
@ -19,17 +22,36 @@ pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8)
const title = parseTitle(file_buf);
const kind = Backup.guessKind(file_buf) orelse .None;
const pak = Self{
var pak = Self{
.buf = file_buf,
.allocator = allocator,
.title = title,
.backup = try Backup.init(allocator, kind, title, save_path),
.gpio = Gpio.init(allocator, .Rtc),
};
pak.parseHeader();
return pak;
}
/// Configures any GPIO Device that may be enabled
///
/// Fundamentally, this just passes a pointer to the initialized GPIO struct to whatever heap allocated GPIO Device struct
/// we happen to be using
///
/// WARNIG: As far as I know, this method must be called in main() or else we'll have a dangling pointer issue
/// Despite using the General Purpose Allocator, Zig doesn't prevent me from doing this :sadface:
pub fn setupGpio(self: *Self) void {
switch (self.gpio.device.kind) {
.Rtc => {
const ptr = self.gpio.device.ptr orelse @panic("RTC ptr is missing despite GPIO Device Kind");
const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr));
Clock.init(clock, &self.gpio);
},
.None => {},
}
}
fn parseHeader(self: *const Self) void {
const title = parseTitle(self.buf);
const code = self.buf[0xAC..0xB0];
@ -60,6 +82,7 @@ inline fn isLarge(self: *const Self) bool {
pub fn deinit(self: *Self) void {
self.backup.deinit();
self.gpio.deinit(self.allocator);
self.allocator.free(self.buf);
self.* = undefined;
}
@ -83,6 +106,35 @@ pub fn read(self: *Self, comptime T: type, address: u32) T {
}
}
if (self.gpio.cnt == 1) {
// GPIO Can be read from
// We assume that this will only be true when a ROM actually does want something from GPIO
switch (T) {
u32 => switch (address) {
// TODO: Do I even need to implement these?
0x0800_00C4 => std.debug.panic("Handle 32-bit GPIO Data/Direction Reads", .{}),
0x0800_00C6 => std.debug.panic("Handle 32-bit GPIO Direction/Control Reads", .{}),
0x0800_00C8 => std.debug.panic("Handle 32-bit GPIO Control Reads", .{}),
else => {},
},
u16 => switch (address) {
// FIXME: What do 16-bit GPIO Reads look like?
0x0800_00C4 => return self.gpio.read(.Data),
0x0800_00C6 => return self.gpio.read(.Direction),
0x0800_00C8 => return self.gpio.read(.Control),
else => {},
},
u8 => switch (address) {
0x0800_00C4 => return self.gpio.read(.Data),
0x0800_00C6 => return self.gpio.read(.Direction),
0x0800_00C8 => return self.gpio.read(.Control),
else => {},
},
else => @compileError("GamePak[GPIO]: Unsupported read width"),
}
}
return switch (T) {
u32 => (@as(T, self.get(addr + 3)) << 24) | (@as(T, self.get(addr + 2)) << 16) | (@as(T, self.get(addr + 1)) << 8) | (@as(T, self.get(addr))),
u16 => (@as(T, self.get(addr + 1)) << 8) | @as(T, self.get(addr)),
@ -141,17 +193,23 @@ pub fn write(self: *Self, comptime T: type, word_count: u16, address: u32, value
switch (T) {
u32 => switch (address) {
0x0800_00C4 => log.debug("Wrote {} 0x{X:} to I/O Port Data and Direction", .{ T, value }),
0x0800_00C6 => log.debug("Wrote {} 0x{X:} to I/O Port Direction and Control", .{ T, value }),
else => {},
0x0800_00C4 => {
self.gpio.write(.Data, @truncate(u4, value));
self.gpio.write(.Direction, @truncate(u4, value >> 16));
},
0x0800_00C6 => {
self.gpio.write(.Direction, @truncate(u4, value));
self.gpio.write(.Control, @truncate(u1, value >> 16));
},
else => log.err("Wrote {} 0x{X:0>8} to 0x{X:0>8}, Unhandled", .{ T, value, address }),
},
u16 => switch (address) {
0x0800_00C4 => log.debug("Wrote {} 0x{X:} to I/O Port Data", .{ T, value }),
0x0800_00C6 => log.debug("Wrote {} 0x{X:} to I/O Port Direction", .{ T, value }),
0x0800_00C8 => log.debug("Wrote {} 0x{X:} to I/O Port Control", .{ T, value }),
else => {},
0x0800_00C4 => self.gpio.write(.Data, @truncate(u4, value)),
0x0800_00C6 => self.gpio.write(.Direction, @truncate(u4, value)),
0x0800_00C8 => self.gpio.write(.Control, @truncate(u1, value)),
else => log.err("Wrote {} 0x{X:0>4} to 0x{X:0>8}, Unhandled", .{ T, value, address }),
},
u8 => log.debug("Wrote {} 0x{X:} to 0x{X:0>8}, Ignored.", .{ T, value, address }),
u8 => log.debug("Wrote {} 0x{X:0>2} to 0x{X:0>8}, Ignored.", .{ T, value, address }),
else => @compileError("GamePak: Unsupported write width"),
}
}
@ -183,3 +241,343 @@ test "OOB Access" {
std.debug.assert(pak.get(4) == 0x02); // 0x0002
std.debug.assert(pak.get(5) == 0x00);
}
/// GPIO Register Implementation
const Gpio = struct {
const This = @This();
data: u4,
direction: u4,
cnt: u1,
device: Device,
const Device = struct {
ptr: ?*anyopaque,
// TODO: Maybe make this comptime known? Removes some if statements
kind: Kind,
const Kind = enum {
Rtc,
None,
};
fn step(self: *Device, value: u4) void {
switch (self.kind) {
.Rtc => {
const ptr = self.ptr orelse @panic("Device.ptr should != null when Device.kind == .Rtc");
const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr));
clock.step(Clock.GpioData{ .raw = value });
},
.None => {},
}
}
fn init(kind: Kind, ptr: ?*anyopaque) Device {
return .{ .kind = kind, .ptr = ptr };
}
};
const Register = enum {
Data,
Direction,
Control,
};
fn init(allocator: Allocator, kind: Device.Kind) This {
return .{
.data = 0b0000,
.direction = 0b1111, // TODO: What is GPIO Direction set to by default?
.cnt = 0b0,
.device = switch (kind) {
.Rtc => blk: {
const ptr = allocator.create(Clock) catch @panic("Failed to allocate RTC struct on heap");
break :blk Device{ .kind = kind, .ptr = ptr };
},
.None => Device{ .kind = kind, .ptr = null },
},
};
}
fn deinit(self: This, allocator: Allocator) void {
switch (self.device.kind) {
.Rtc => {
const ptr = self.device.ptr orelse @panic("Device.ptr should != null when Device.kind == .Rtc");
allocator.destroy(@ptrCast(*Clock, @alignCast(@alignOf(*Clock), ptr)));
},
.None => {},
}
}
fn write(self: *This, comptime reg: Register, value: if (reg == .Control) u1 else u4) void {
log.debug("RTC: Wrote 0b{b:0>4} to {}", .{ value, reg });
// if (reg == .Data)
// log.err("original: 0b{b:0>4} masked: 0b{b:0>4} result: 0b{b:0>4}", .{ self.data, value & self.direction, self.data | (value & self.direction) });
switch (reg) {
.Data => {
const masked_value = value & self.direction;
self.device.step(masked_value);
self.data = masked_value;
},
.Direction => self.direction = value,
.Control => self.cnt = value,
}
}
fn read(self: *const This, comptime reg: Register) if (reg == .Control) u1 else u4 {
if (self.cnt == 0) return 0;
return switch (reg) {
.Data => self.data & ~self.direction,
.Direction => self.direction,
.Control => self.cnt,
};
}
};
/// GBA Real Time Clock
const Clock = struct {
const This = @This();
cmd: Command,
writer: Writer,
state: State,
cnt: Control,
year: u8,
month: u5,
day: u6,
day_of_week: u3,
hour: u6,
minute: u7,
second: u7,
gpio: *const Gpio,
const Register = enum {
Control,
DateTime,
Time,
};
const State = union(enum) {
Idle,
CommandInput,
Write: Register,
Read: Register,
};
const Writer = struct {
buf: u8,
i: u4,
/// The Number of bytes written to since last reset
count: u8,
fn push(self: *Writer, value: u1) void {
const idx = @intCast(u3, self.i);
self.buf = (self.buf & ~(@as(u8, 1) << idx)) | @as(u8, value) << idx;
self.i += 1;
}
fn lap(self: *Writer) void {
self.buf = 0;
self.i = 0;
self.count += 1;
}
fn reset(self: *Writer) void {
self.buf = 0;
self.i = 0;
self.count = 0;
}
fn isFinished(self: *const Writer) bool {
return self.i >= 8;
}
fn getCount(self: *const Writer) u8 {
return self.count;
}
fn getValue(self: *const Writer) u8 {
return self.buf;
}
};
const Command = struct {
buf: u8,
i: u4,
fn push(self: *Command, value: u1) void {
const idx = @intCast(u3, self.i);
self.buf = (self.buf & ~(@as(u8, 1) << idx)) | @as(u8, value) << idx;
self.i += 1;
}
fn reset(self: *Command) void {
self.buf = 0;
self.i = 0;
}
fn isFinished(self: *const Command) bool {
return self.i >= 8;
}
fn getCommand(self: *const Command) u8 {
// If high Nybble does not contain 0x6, reverse the order of the nybbles.
// For some reason RTC commands can be LSB or MSB which is funny
return if (self.buf >> 4 & 0xF == 0x6) self.buf else (self.buf & 0xF) << 4 | (self.buf >> 4 & 0xF);
}
fn handleCommand(self: *const Command, rtc: *Clock) State {
log.info("RTC: Failed to handle Command 0b{b:0>8} aka 0x{X:0>2}", .{ self.buf, self.buf });
const command = self.getCommand();
const is_write = command & 1 == 0;
const rtc_register = @intCast(u3, command >> 1 & 0x7); // TODO: Make Truncate
if (is_write) {
return switch (rtc_register) {
0 => blk: {
rtc.reset();
break :blk .Idle;
},
1 => .{ .Write = .Control },
2 => .{ .Write = .DateTime },
3 => .{ .Write = .Time },
6 => blk: {
rtc.irq();
break :blk .Idle;
},
4, 5, 7 => .Idle,
};
} else {
return switch (rtc_register) {
1 => .{ .Read = .Control },
2 => .{ .Read = .DateTime },
3 => .{ .Read = .Time },
0, 4, 5, 6, 7 => .Idle, // Do Nothing
};
}
}
};
const GpioData = extern union {
sck: Bit(u8, 0),
sio: Bit(u8, 1),
cs: Bit(u8, 2),
raw: u8,
};
const Control = extern union {
/// Unknown, value should be preserved though
unk: Bit(u8, 1),
/// Per-minute IRQ
/// If set, fire a Gamepak IRQ every 30s,
irq: Bit(u8, 3),
/// 12/24 Hour Bit
/// If set, 12h mode
/// If cleared, 24h mode
mode: Bit(u8, 6),
/// Read-Only, bit cleared on read
/// If is set, means that there has been a failure / time has been lost
off: Bit(u8, 7),
raw: u8,
};
fn init(ptr: *This, gpio: *const Gpio) void {
ptr.* = .{
.cmd = .{ .buf = 0, .i = 0 },
.writer = .{ .buf = 0, .i = 0, .count = 0 },
.state = .Idle,
.cnt = .{ .raw = 0 },
.year = 0,
.month = 0,
.day = 0,
.day_of_week = 0,
.hour = 0,
.minute = 0,
.second = 0,
.gpio = gpio,
};
}
fn attachGpio(self: *This, gpio: *const Gpio) void {
self.gpio = gpio;
}
fn step(self: *This, value: GpioData) void {
const cache: GpioData = .{ .raw = self.gpio.data };
switch (self.state) {
.Idle => {
// If SCK is high and CS rises, then prepare for Command
// FIXME: Maybe check incoming value to see if SCK is also high?
if (cache.sck.read()) {
if (!cache.cs.read() and value.cs.read()) {
log.err("RTC: Entering Command Mode", .{});
self.state = .CommandInput;
self.cmd.reset();
}
}
},
.CommandInput => {
if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state});
if (!cache.sck.read() and value.sck.read()) {
// If SCK rises, sample SIO
log.debug("RTC: Sampled 0b{b:0>1} from SIO", .{@boolToInt(value.sio.read())});
self.cmd.push(@boolToInt(value.sio.read()));
if (self.cmd.isFinished()) {
self.state = self.cmd.handleCommand(self);
}
}
},
State{ .Write = .Control } => {
if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state});
if (!cache.sck.read() and value.sck.read()) {
// If SCK rises, sample SIO
log.debug("RTC: Sampled 0b{b:0>1} from SIO", .{@boolToInt(value.sio.read())});
self.writer.push(@boolToInt(value.sio.read()));
if (self.writer.isFinished()) {
self.writer.lap();
self.cnt.raw = self.writer.getValue();
// FIXME: Move this to a constant or something
if (self.writer.getCount() == 1) {
self.writer.reset();
self.state = .Idle;
}
}
}
},
else => {
// TODO: Implement Read/Writes for Date/Time and Time and Control
log.err("RTC: Ignored request to handle {} command", .{self.state});
self.state = .Idle;
},
}
}
fn reset(self: *This) void {
// mGBA and NBA only zero the control register
// we'll do the same
self.cnt.raw = 0;
log.info("RTC: Reset executed (control register was zeroed)", .{});
}
fn irq(_: *const This) void {
// TODO: Force GamePak IRQ
log.err("RTC: TODO: Force GamePak IRQ", .{});
}
};

View File

@ -28,9 +28,14 @@ pub const arm = struct {
const multiply = @import("cpu/arm/multiply.zig").multiply;
const multiplyLong = @import("cpu/arm/multiply.zig").multiplyLong;
/// Determine index into ARM InstrFn LUT
fn idx(opcode: u32) u12 {
return @truncate(u12, opcode >> 20 & 0xFF) << 4 | @truncate(u12, opcode >> 4 & 0xF);
}
// Undefined ARM Instruction handler
fn und(cpu: *Arm7tdmi, _: *Bus, opcode: u32) void {
const id = armIdx(opcode);
const id = idx(opcode);
cpu.panic("[CPU/Decode] ID: 0x{X:0>3} 0x{X:0>8} is an illegal opcode", .{ id, opcode });
}
@ -120,9 +125,14 @@ pub const thumb = struct {
const swi = @import("cpu/thumb/software_interrupt.zig").fmt17;
const branch = @import("cpu/thumb/branch.zig");
/// Determine index into THUMB InstrFn LUT
fn idx(opcode: u16) u10 {
return @truncate(u10, opcode >> 6);
}
/// Undefined THUMB Instruction Handler
fn und(cpu: *Arm7tdmi, _: *Bus, opcode: u16) void {
const id = thumbIdx(opcode);
const id = idx(opcode);
cpu.panic("[CPU/Decode] ID: 0b{b:0>10} 0x{X:0>2} is an illegal opcode", .{ id, opcode });
}
@ -420,13 +430,13 @@ pub const Arm7tdmi = struct {
const opcode = self.fetch(u16);
if (cpu_logging) self.logger.?.mgbaLog(self, opcode);
thumb.lut[thumbIdx(opcode)](self, self.bus, opcode);
thumb.lut[thumb.idx(opcode)](self, self.bus, opcode);
} else {
const opcode = self.fetch(u32);
if (cpu_logging) self.logger.?.mgbaLog(self, opcode);
if (checkCond(self.cpsr, @truncate(u4, opcode >> 28))) {
arm.lut[armIdx(opcode)](self, self.bus, opcode);
arm.lut[arm.idx(opcode)](self, self.bus, opcode);
}
}
}
@ -517,11 +527,11 @@ pub const Arm7tdmi = struct {
if (self.cpsr.t.read()) {
const opcode = self.bus.dbgRead(u16, self.r[15] - 4);
const id = thumbIdx(opcode);
const id = thumb.idx(opcode);
std.debug.print("opcode: ID: 0x{b:0>10} 0x{X:0>4}\n", .{ id, opcode });
} else {
const opcode = self.bus.dbgRead(u32, self.r[15] - 4);
const id = armIdx(opcode);
const id = arm.idx(opcode);
std.debug.print("opcode: ID: 0x{X:0>3} 0x{X:0>8}\n", .{ id, opcode });
}
@ -601,14 +611,6 @@ pub const Arm7tdmi = struct {
}
};
inline fn armIdx(opcode: u32) u12 {
return @truncate(u12, opcode >> 20 & 0xFF) << 4 | @truncate(u12, opcode >> 4 & 0xF);
}
inline fn thumbIdx(opcode: u16) u10 {
return @truncate(u10, opcode >> 6);
}
pub fn checkCond(cpsr: PSR, cond: u4) bool {
return switch (cond) {
0x0 => cpsr.z.read(), // EQ - Equal

View File

@ -70,12 +70,21 @@ pub fn runFrame(sched: *Scheduler, cpu: *Arm7tdmi) void {
}
}
fn syncToAudio(cpu: *const Arm7tdmi) void {
const stream = cpu.bus.apu.stream;
const min_sample_count = 0x800;
fn syncToAudio(stream: *SDL.SDL_AudioStream, is_buffer_full: *bool) void {
const sample_size = 2 * @sizeOf(u16);
const max_buf_size: c_int = 0x400;
// Busy Loop while we wait for the Audio system to catch up
while (SDL.SDL_AudioStreamAvailable(stream) > (@sizeOf(u16) * 2) * min_sample_count) {}
// Determine whether the APU is busy right at this moment
var still_full: bool = SDL.SDL_AudioStreamAvailable(stream) > sample_size * if (is_buffer_full.*) max_buf_size >> 1 else max_buf_size;
defer is_buffer_full.* = still_full; // Update APU Busy status right before exiting scope
// If Busy is false, there's no need to sync here
if (!still_full) return;
while (true) {
still_full = SDL.SDL_AudioStreamAvailable(stream) > sample_size * max_buf_size >> 1;
if (!sync_audio or !still_full) break;
}
}
pub fn runUnsynchronized(quit: *Atomic(bool), sched: *Scheduler, cpu: *Arm7tdmi, fps: ?*FpsTracker) void {
@ -86,21 +95,21 @@ pub fn runUnsynchronized(quit: *Atomic(bool), sched: *Scheduler, cpu: *Arm7tdmi,
while (!quit.load(.SeqCst)) {
runFrame(sched, cpu);
if (sync_audio) syncToAudio(cpu);
syncToAudio(cpu.bus.apu.stream, &cpu.bus.apu.is_buffer_full);
tracker.tick();
}
} else {
while (!quit.load(.SeqCst)) {
runFrame(sched, cpu);
if (sync_audio) syncToAudio(cpu);
syncToAudio(cpu.bus.apu.stream, &cpu.bus.apu.is_buffer_full);
}
}
}
pub fn runSynchronized(quit: *Atomic(bool), sched: *Scheduler, cpu: *Arm7tdmi, fps: ?*FpsTracker) void {
log.info("Emulation thread w/ video sync", .{});
var timer = Timer.start() catch unreachable;
var timer = Timer.start() catch std.debug.panic("Failed to initialize std.timer.Timer", .{});
var wake_time: u64 = frame_period;
if (fps) |tracker| {
@ -108,13 +117,14 @@ pub fn runSynchronized(quit: *Atomic(bool), sched: *Scheduler, cpu: *Arm7tdmi, f
while (!quit.load(.SeqCst)) {
runFrame(sched, cpu);
const new_wake_time = syncToVideo(&timer, wake_time);
const new_wake_time = blockOnVideo(&timer, wake_time);
// Spin to make up the difference of OS scheduler innacuracies
// If we happen to also be syncing to audio, we choose to spin on
// the amount of time needed for audio to catch up rather than
// our expected wake-up time
if (sync_audio) syncToAudio(cpu) else spinLoop(&timer, wake_time);
syncToAudio(cpu.bus.apu.stream, &cpu.bus.apu.is_buffer_full);
if (!sync_audio) spinLoop(&timer, wake_time);
wake_time = new_wake_time;
tracker.tick();
@ -122,16 +132,17 @@ pub fn runSynchronized(quit: *Atomic(bool), sched: *Scheduler, cpu: *Arm7tdmi, f
} else {
while (!quit.load(.SeqCst)) {
runFrame(sched, cpu);
const new_wake_time = syncToVideo(&timer, wake_time);
// see above comment
if (sync_audio) syncToAudio(cpu) else spinLoop(&timer, wake_time);
const new_wake_time = blockOnVideo(&timer, wake_time);
// see above comment
syncToAudio(cpu.bus.apu.stream, &cpu.bus.apu.is_buffer_full);
if (!sync_audio) spinLoop(&timer, wake_time);
wake_time = new_wake_time;
}
}
}
inline fn syncToVideo(timer: *Timer, wake_time: u64) u64 {
inline fn blockOnVideo(timer: *Timer, wake_time: u64) u64 {
// Use the OS scheduler to put the emulation thread to sleep
const maybe_recalc_wake_time = sleep(timer, wake_time);
@ -149,6 +160,8 @@ pub fn runBusyLoop(quit: *Atomic(bool), sched: *Scheduler, cpu: *Arm7tdmi) void
runFrame(sched, cpu);
spinLoop(&timer, wake_time);
syncToAudio(cpu.bus.apu.stream, &cpu.bus.apu.is_buffer_full);
// Update to the new wake time
wake_time += frame_period;
}

View File

@ -52,6 +52,7 @@ pub fn main() anyerror!void {
if (paths.bios == null) cpu.fastBoot();
try bus.init(allocator, &scheduler, &cpu, paths);
bus.pak.setupGpio(); // FIXME: Can I not call this in main()?
defer bus.deinit();
var gui = Gui.init(bus.pak.title, width, height);