Compare commits

..
12 Commits
12 changed files with 352 additions and 48 deletions
Generated
+1 -1
View File
@@ -2034,7 +2034,7 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]]
name = "lemur"
version = "0.13.1"
version = "0.15.0"
dependencies = [
"anyhow",
"atoi",
+1 -1
View File
@@ -4,7 +4,7 @@ description = "An emulator for the Virtual Boy."
repository = "https://git.virtual-boy.com/PVB/lemur"
publish = false
license = "MIT"
version = "0.13.1"
version = "0.15.0"
edition = "2024"
[dependencies]
+7
View File
@@ -424,6 +424,9 @@ impl ApplicationHandler<UserEvent> for Application {
{
self.controllers.handle_key_event(&event);
}
WindowEvent::DroppedFile(path) => {
self.app.handle_dropped_file(viewport_id, path);
}
WindowEvent::Focused(new_focused) => {
self.focused = new_focused.then_some(viewport_id);
}
@@ -464,6 +467,9 @@ impl ApplicationHandler<UserEvent> for Application {
self.controllers.handle_gamepad_event(&event);
}
}
UserEvent::LowBattery(sim_id, pwr) => {
self.controllers.handle_low_battery(sim_id, pwr);
}
UserEvent::Quit(sim_id) => match sim_id {
SimId::Player1 => event_loop.exit(),
SimId::Player2 => self.app.close(ChildWindow::Player2),
@@ -670,6 +676,7 @@ impl ViewportManager {
pub enum UserEvent {
GamepadEvent(gilrs::Event),
Quit(SimId),
LowBattery(SimId, bool),
RequestRedraw(ViewportId, Instant),
}
+157 -16
View File
@@ -1,12 +1,16 @@
use std::time::Duration;
use anyhow::{Result, bail};
use anyhow::{Context, Result, bail};
use audioadapter_buffers::direct::InterleavedSlice;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{
Device, FromSample, Sample, SampleFormat, SizedSample, StreamConfig,
traits::{DeviceTrait, HostTrait, StreamTrait},
};
use itertools::Itertools;
use rubato::{Adjustable as _, Resampler};
use tracing::warn;
pub struct Audio {
struct CpalAudio {
#[allow(unused)]
stream: cpal::Stream,
sampler: rubato::Async<f32>,
@@ -17,19 +21,31 @@ pub struct Audio {
const VB_FREQUENCY: usize = 41700;
impl Audio {
pub fn init() -> Result<Self> {
impl CpalAudio {
fn init() -> Result<Self> {
let host = cpal::default_host();
let Some(device) = host.default_output_device() else {
bail!("No output device available");
};
let device = host
.default_output_device()
.context("no output device available")?;
let default_rate = device.default_output_config()?.sample_rate();
let Some(config) = device.supported_output_configs()?.find(|c| {
c.channels() == 2 && c.sample_format().is_float() && c.contains_rate(default_rate)
}) else {
bail!("No suitable output config available");
};
let mut config = config.with_sample_rate(default_rate).config();
let supported_config = device
.supported_output_configs()?
.filter(|c| {
c.contains_rate(default_rate)
&& matches!(
c.sample_format(),
SampleFormat::F32
| SampleFormat::F64
| SampleFormat::I32
| SampleFormat::I16
)
})
.max_by(|a, b| a.cmp_default_heuristics(b))
.context("no suitable output config available")?
.with_sample_rate(default_rate);
let mut config = supported_config.config();
let resample_ratio = config.sample_rate as f64 / VB_FREQUENCY as f64;
let chunk_size = (834.0 * resample_ratio) as usize;
let sampler = rubato::Async::new_poly(
@@ -42,6 +58,23 @@ impl Audio {
)?;
config.buffer_size = cpal::BufferSize::Fixed(sampler.output_frames_max() as u32);
match supported_config.sample_format() {
SampleFormat::F32 if config.channels == 2 => {
Self::new_f32_stereo(device, config, sampler)
}
SampleFormat::F32 => Self::new::<f32>(device, config, sampler),
SampleFormat::F64 => Self::new::<f64>(device, config, sampler),
SampleFormat::I32 => Self::new::<i32>(device, config, sampler),
SampleFormat::I16 => Self::new::<i16>(device, config, sampler),
_ => bail!("unsupported sample format"),
}
}
fn new_f32_stereo(
device: Device,
config: StreamConfig,
sampler: rubato::Async<f32>,
) -> Result<Self> {
let input_buffer = Vec::with_capacity(sampler.nbr_channels() * sampler.input_frames_max());
let output_buffer = vec![0.0; sampler.nbr_channels() * sampler.output_frames_max()];
let (sample_sink, mut sample_source) =
@@ -79,7 +112,60 @@ impl Audio {
})
}
pub fn update(&mut self, mut samples: &[f32]) {
fn new<S: SizedSample + FromSample<f32>>(
device: Device,
config: StreamConfig,
sampler: rubato::Async<f32>,
) -> Result<Self> {
let input_buffer = Vec::with_capacity(sampler.nbr_channels() * sampler.input_frames_max());
let output_buffer = vec![0.0; sampler.nbr_channels() * sampler.output_frames_max()];
let (sample_sink, mut sample_source) =
rtrb::RingBuffer::new(sampler.output_frames_max() * 4);
let channels = config.channels as usize;
let stream = device.build_output_stream(
config,
move |data: &mut [S], _| {
let requested = data.len() * 2 / channels;
let chunk = match sample_source.read_chunk(requested) {
Ok(c) => c,
Err(rtrb::chunks::ChunkError::TooFewSlots(n)) => {
sample_source.read_chunk(n).unwrap()
}
};
let (first, second) = chunk.as_slices();
let new_samples = first
.iter()
.chain(second)
.map(|s: &f32| (*s).to_sample())
.chunks(2);
let buffer = data.iter_mut().chunks(channels);
for (dst, samples) in buffer.into_iter().zip(&new_samples) {
// channels beyond the first two are zeroed
let src = samples.chain(std::iter::repeat(S::EQUILIBRIUM));
for (d, s) in dst.zip(src) {
*d = s;
}
}
chunk.commit_all();
},
move |error| warn!(%error, "stream error"),
None,
)?;
stream.play()?;
Ok(Self {
stream,
sampler,
input_buffer,
output_buffer,
sample_sink,
})
}
fn update(&mut self, mut samples: &[f32]) {
while self.input_buffer.len() + samples.len() >= self.sampler.input_frames_next() * 2 {
let samples_needed =
(self.sampler.input_frames_next() * 2).saturating_sub(self.input_buffer.len());
@@ -117,9 +203,64 @@ impl Audio {
}
}
pub fn set_speed(&mut self, speed: f64) -> Result<()> {
fn set_speed(&mut self, speed: f64) -> Result<()> {
self.sampler
.set_resample_ratio_relative(1.0 / speed, false)?;
Ok(())
}
}
struct NoAudio {
speed: f64,
}
impl NoAudio {
fn new() -> Self {
Self { speed: 1.0 }
}
fn update(&mut self, samples: &[f32]) {
let samples = (samples.len() / 2) as f64;
let elapsed = Duration::from_secs_f64(samples / (VB_FREQUENCY as f64 * self.speed));
std::thread::sleep(elapsed);
}
fn set_speed(&mut self, speed: f64) -> Result<()> {
self.speed = speed;
Ok(())
}
}
#[allow(clippy::large_enum_variant)]
enum AudioInner {
Cpal(CpalAudio),
None(NoAudio),
}
pub struct Audio(AudioInner);
impl Audio {
pub fn init() -> Self {
match CpalAudio::init() {
Ok(a) => Self(AudioInner::Cpal(a)),
Err(e) => {
warn!("could not play audio: {e}");
Self(AudioInner::None(NoAudio::new()))
}
}
}
pub fn update(&mut self, samples: &[f32]) {
match &mut self.0 {
AudioInner::Cpal(a) => a.update(samples),
AudioInner::None(a) => a.update(samples),
}
}
pub fn set_speed(&mut self, speed: f64) -> Result<()> {
match &mut self.0 {
AudioInner::Cpal(a) => a.set_speed(speed),
AudioInner::None(a) => a.set_speed(speed),
}
}
}
+6
View File
@@ -141,6 +141,10 @@ pub struct SimConfig {
#[serde(default = "default_audio_enabled")]
pub audio_enabled: bool,
#[serde(default)]
pub low_battery: bool,
#[serde(default)]
pub watch_rom: bool,
#[serde(default)]
pub position: Option<Pos2>,
}
@@ -154,6 +158,8 @@ impl SimConfig {
colors: COLOR_PRESETS[0],
dimensions: DisplayMode::Anaglyph.proportions() + Vec2::new(0.0, 22.0),
audio_enabled: true,
low_battery: false,
watch_rom: false,
position: None,
}
}
+17
View File
@@ -77,6 +77,15 @@ impl Controller {
self.update_state(pressed, released)
}
pub fn low_battery(&mut self, pwr: bool) -> Option<VBKey> {
let (pressed, released) = if pwr {
(VBKey::PWR, VBKey::empty())
} else {
(VBKey::empty(), VBKey::PWR)
};
self.update_state(pressed, released)
}
fn update_state(&mut self, pressed: VBKey, released: VBKey) -> Option<VBKey> {
let old_state = self.state;
self.state = self.state.union(pressed).difference(released);
@@ -133,6 +142,14 @@ impl ControllerManager {
}
}
}
pub fn handle_low_battery(&mut self, sim_id: SimId, pwr: bool) {
let controller = &mut self.controllers[sim_id.to_index()];
if let Some(pressed) = controller.low_battery(pwr) {
self.client
.send_command(EmulatorCommand::SetKeys(controller.sim_id, pressed));
}
}
}
fn axis_presses(value: f32, pair_value: f32, neg: VBKey, pos: VBKey) -> (VBKey, VBKey) {
+5 -5
View File
@@ -138,7 +138,7 @@ impl EmulatorBuilder {
self.audio_on,
self.watch_rom,
self.linked,
)?;
);
if let Some(path) = self.rom {
emulator.load_cart(SimId::Player1, &path)?;
}
@@ -178,11 +178,11 @@ impl Emulator {
audio_on: Arc<[AtomicBool; 2]>,
watch_rom: Arc<[AtomicBool; 2]>,
linked: Arc<AtomicBool>,
) -> Result<Self> {
Ok(Self {
) -> Self {
Self {
sims: vec![],
carts: [None, None],
audio: Audio::init()?,
audio: Audio::init(),
commands,
sim_state,
state,
@@ -198,7 +198,7 @@ impl Emulator {
eye_contents: [vec![0u8; 384 * 224 * 2], vec![0u8; 384 * 224 * 2]],
audio_samples: Vec::with_capacity(EXPECTED_FRAME_SIZE),
buffer: vec![],
})
}
}
pub fn reload_cart(&mut self, sim_id: SimId) -> Result<()> {
+103
View File
@@ -0,0 +1,103 @@
#[cfg(target_os = "linux")]
use std::fmt::Write as _;
use std::{
path::PathBuf,
sync::{Arc, Weak},
};
use winit::window::Window;
pub struct FilePicker {
window: Option<Weak<Window>>,
}
impl FilePicker {
pub fn new() -> Self {
Self { window: None }
}
pub fn set_window(&mut self, window: &Arc<Window>) {
self.window = Some(Arc::downgrade(window));
}
pub fn pick_file_dialog(&self) -> FileDialogBuilder {
self.new_dialog(FileDialogAction::PickFile, false)
}
pub fn save_file_dialog(&self) -> FileDialogBuilder {
self.new_dialog(FileDialogAction::SaveFile, cfg!(not(target_os = "windows")))
}
fn new_dialog(&self, action: FileDialogAction, attach_window: bool) -> FileDialogBuilder {
#[cfg(not(target_os = "macos"))]
let mut dialog = rfd::AsyncFileDialog::new();
#[cfg(target_os = "macos")]
let mut dialog = rfd::FileDialog::new();
if attach_window && let Some(window) = self.window.as_ref().and_then(|w| w.upgrade()) {
dialog = dialog.set_parent(&window);
}
FileDialogBuilder { dialog, action }
}
}
pub struct FileDialogBuilder {
#[cfg(not(target_os = "macos"))]
dialog: rfd::AsyncFileDialog,
#[cfg(target_os = "macos")]
dialog: rfd::FileDialog,
action: FileDialogAction,
}
impl FileDialogBuilder {
pub fn add_filter(self, name: impl Into<String>, extensions: &[impl ToString]) -> Self {
#[cfg(target_os = "linux")]
let exts = extensions
.iter()
.map(|ext| {
let mut normalized = String::new();
for char in ext.to_string().chars() {
if char.is_ascii_lowercase() {
let _ = write!(&mut normalized, "[{char}{}]", char.to_ascii_uppercase());
} else {
normalized.push(char);
}
}
normalized
})
.collect::<Vec<_>>();
#[cfg(target_os = "linux")]
let extensions = &exts;
Self {
dialog: self.dialog.add_filter(name, extensions),
..self
}
}
pub fn set_file_name(self, file_name: impl Into<String>) -> Self {
Self {
dialog: self.dialog.set_file_name(file_name),
..self
}
}
pub fn open(self) -> Option<PathBuf> {
#[cfg(not(target_os = "macos"))]
fn resolve(action: impl Future<Output = Option<rfd::FileHandle>>) -> Option<PathBuf> {
pollster::block_on(action).map(Into::into)
}
#[cfg(target_os = "macos")]
fn resolve(action: Option<PathBuf>) -> Option<PathBuf> {
action
}
match self.action {
FileDialogAction::PickFile => resolve(self.dialog.pick_file()),
FileDialogAction::SaveFile => resolve(self.dialog.save_file()),
}
}
}
enum FileDialogAction {
PickFile,
SaveFile,
}
+1
View File
@@ -23,6 +23,7 @@ mod audio;
mod config;
mod controller;
mod emulator;
mod filepicker;
mod gdbserver;
mod graphics;
mod images;
+5 -1
View File
@@ -1,4 +1,4 @@
use std::sync::Arc;
use std::{path::PathBuf, sync::Arc};
pub use about::AboutWindow;
use egui::{Ui, ViewportBuilder};
@@ -47,6 +47,10 @@ pub trait AppWindow {
let _ = event;
false
}
fn handle_dropped_file(&mut self, path: PathBuf) -> bool {
let _ = path;
false
}
}
pub struct InitArgs<'a> {
+39 -13
View File
@@ -1,5 +1,6 @@
use std::{
ops::{Deref, DerefMut},
path::PathBuf,
sync::{Arc, Mutex, atomic::AtomicBool, mpsc},
time::Duration,
};
@@ -8,6 +9,7 @@ use crate::{
app::UserEvent,
config::{COLOR_PRESETS, SimConfig},
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId, SimState},
filepicker::FilePicker,
images::ImageTextureLoader,
input::{Command, MappingProvider, ShortcutProvider},
memory::MemoryClient,
@@ -46,7 +48,7 @@ pub struct GameWindow {
messages: mpsc::Receiver<Toast>,
message_sink: mpsc::Sender<Toast>,
color_picker: Option<ColorPickerState>,
window: Option<Arc<winit::window::Window>>,
file_picker: FilePicker,
memory: Arc<MemoryClient>,
images: Arc<ImageTextureLoader>,
mappings: MappingProvider,
@@ -70,6 +72,8 @@ impl GameWindow {
sim_id: SimId,
) -> Self {
let config = SimConfig::load(&persistence, sim_id);
let _ = proxy.send_event(UserEvent::LowBattery(sim_id, config.low_battery));
client.send_command(EmulatorCommand::WatchRom(sim_id, config.watch_rom));
let toasts = Toasts::new()
.with_anchor(Anchor::BottomLeft)
.with_margin((10.0, 10.0).into())
@@ -88,7 +92,7 @@ impl GameWindow {
messages,
message_sink,
color_picker: None,
window: None,
file_picker: FilePicker::new(),
memory: memory.clone(),
images: images.clone(),
mappings: mappings.clone(),
@@ -213,6 +217,10 @@ impl GameWindow {
self.handle_event(viewport_id, |window| window.handle_gamepad_event(event))
}
pub fn handle_dropped_file(&mut self, viewport_id: ViewportId, path: PathBuf) -> bool {
self.handle_event(viewport_id, |window| window.handle_dropped_file(path))
}
fn handle_event<F, R>(&mut self, viewport_id: ViewportId, cb: F) -> R
where
F: FnOnce(&mut dyn AppWindow) -> R,
@@ -249,9 +257,11 @@ impl GameWindow {
for command in ui.input_mut(|input| self.shortcuts.consume_all(input)) {
match command {
Command::OpenRom => {
let rom = rfd::FileDialog::new()
let rom = self
.file_picker
.pick_file_dialog()
.add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"])
.pick_file();
.open();
if let Some(path) = rom {
self.client
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
@@ -305,9 +315,11 @@ impl GameWindow {
.add(self.button_for(ui.ctx(), "Open ROM", Command::OpenRom))
.clicked()
{
let rom = rfd::FileDialog::new()
let rom = self
.file_picker
.pick_file_dialog()
.add_filter("Virtual Boy ROMs", &["vb", "vbrom", "elf", "isx"])
.pick_file();
.open();
if let Some(path) = rom {
self.client
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
@@ -322,6 +334,7 @@ impl GameWindow {
}
let watch_rom = self.client.is_rom_watched(self.sim_id);
if ui.selectable_button(watch_rom, "Watch ROM").clicked() {
self.update_config(|c| c.watch_rom = !watch_rom);
self.client
.send_command(EmulatorCommand::WatchRom(self.sim_id, !watch_rom));
}
@@ -379,6 +392,14 @@ impl GameWindow {
{
pollster::block_on(self.take_screenshot());
}
ui.separator();
let low_battery = self.config.low_battery;
if ui.selectable_button(low_battery, "Low Battery").clicked() {
self.update_config(|c| c.low_battery = !low_battery);
let _ = self
.proxy
.send_event(UserEvent::LowBattery(self.sim_id, !low_battery));
}
});
ui.menu_button("Options", |ui| self.show_options_menu(ui));
ui.menu_button("Multiplayer", |ui| {
@@ -459,13 +480,12 @@ impl GameWindow {
self.client
.send_command(EmulatorCommand::Screenshot(self.sim_id, tx));
let bytes = rx.await.context("Could not take screenshot")?;
let mut file_dialog = rfd::FileDialog::new()
let file = self
.file_picker
.save_file_dialog()
.add_filter("PNG images", &["png"])
.set_file_name("screenshot.png");
if let Some(window) = self.window.as_ref() {
file_dialog = file_dialog.set_parent(window);
}
let file = file_dialog.save_file();
.set_file_name("screenshot.png")
.open();
let Some(path) = file else {
return Ok(None);
};
@@ -759,7 +779,13 @@ impl AppWindow for GameWindow {
));
self.screen = Some(screen);
}
self.window = Some(args.window.clone());
self.file_picker.set_window(args.window);
}
fn handle_dropped_file(&mut self, path: PathBuf) -> bool {
self.client
.send_command(EmulatorCommand::LoadGame(self.sim_id, path));
true
}
}
+10 -11
View File
@@ -1,12 +1,12 @@
use std::{fs, sync::Arc, time::Duration};
use std::{fs, time::Duration};
use anyhow::Result;
use egui::{Button, CentralPanel, Checkbox, Label, ViewportBuilder};
use egui_notify::{Anchor, Toast, Toasts};
use winit::window::Window;
use crate::{
emulator::{EmulatorClient, EmulatorCommand, EmulatorState, SimId},
filepicker::FilePicker,
profiler::{Profiler, ProfilerStatus},
window::{AppWindow, InitArgs},
};
@@ -16,7 +16,7 @@ pub struct ProfileWindow {
client: EmulatorClient,
profiler: Profiler,
toasts: Toasts,
window: Option<Arc<Window>>,
file_picker: FilePicker,
}
impl ProfileWindow {
@@ -29,7 +29,7 @@ impl ProfileWindow {
.with_anchor(Anchor::BottomLeft)
.with_margin((10.0, 10.0).into())
.reverse(true),
window: None,
file_picker: FilePicker::new(),
}
}
@@ -62,13 +62,12 @@ impl ProfileWindow {
fn try_finish_recording(&mut self) -> Result<Option<String>> {
let bytes_receiver = self.profiler.finish_recording();
let mut file_dialog = rfd::FileDialog::new()
let file = self
.file_picker
.save_file_dialog()
.add_filter("Profiler files", &["json"])
.set_file_name("profile.json");
if let Some(window) = self.window.as_ref() {
file_dialog = file_dialog.set_parent(window);
}
let file = file_dialog.save_file();
.set_file_name("profile.json")
.open();
if let Some(path) = file {
let bytes = pollster::block_on(bytes_receiver)?;
let _ = fs::remove_file(&path);
@@ -164,6 +163,6 @@ impl AppWindow for ProfileWindow {
}
fn on_init(&mut self, args: InitArgs) {
self.window = Some(args.window.clone());
self.file_picker.set_window(args.window);
}
}