diff --git a/README.md b/README.md index f2b2f04..2b3b8e4 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,9 @@ cargo build --release **Tray (Windows):** start `podbeam.exe` without arguments. A grey dot appears in the notification area; right-click it to choose a speaker. The dot turns green while streaming. The menu -also has the latency setting, Stop and Quit. +also has the latency setting, Stop, Quit and **Open log**. The tray writes everything it +reports, including errors, to `%LOCALAPPDATA%\podbeam\podbeam.log` (moved to +`podbeam.log.1` once it passes 1 MB). Attach it when you report a problem. **Command line (Windows and Linux):** diff --git a/src/main.rs b/src/main.rs index fa006ed..c9d26aa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,7 +28,7 @@ mod tray; fn main() { if let Err(e) = run() { - eprintln!("error: {e}"); + log(format!("error: {e}")); std::process::exit(1); } } @@ -54,6 +54,36 @@ fn run() -> Res<()> { play(addr, latency_ms, &Arc::default()) } +/// Every message podbeam prints goes through here, with a UTC timestamp. On the command line that is +/// the terminal; the Windows tray points stderr at its log file. +fn log(msg: impl std::fmt::Display) { + eprintln!("{} {msg}", utc(SystemTime::now())); +} + +/// `2026-11-09T13:53:07Z`, without pulling in a date crate. +fn utc(t: SystemTime) -> String { + let secs = t.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); + let (days, rem) = ((secs / 86_400) as i64, secs % 86_400); + // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let (d, m) = ( + doy - (153 * mp + 2) / 5 + 1, + if mp < 10 { mp + 3 } else { mp - 9 }, + ); + let y = yoe + era * 400 + (m <= 2) as i64; + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + rem / 60 % 60, + rem % 60 + ) +} + /// Shared between a streaming session and whoever started it (the command line or the tray). #[derive(Default)] struct Ctl { @@ -64,7 +94,7 @@ struct Ctl { impl Ctl { fn say(&self, msg: String) { - println!("{msg}"); + log(&msg); *self.status.lock().unwrap() = msg; } @@ -93,7 +123,7 @@ fn discover() -> Res> { let rx = mdns.browse("_raop._tcp.local.")?; let deadline = Instant::now() + Duration::from_secs(3); let mut found = Vec::new(); - println!("searching for AirPlay devices..."); + log("searching for AirPlay devices..."); while let Ok(ev) = rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { let mdns_sd::ServiceEvent::ServiceResolved(s) = ev else { continue; @@ -191,7 +221,7 @@ where // WASAPI flags a "discontinuity" whenever playback starts or stops; the gap is harmless here. let on_err = |e: cpal::Error| { if !e.to_string().contains("underrun or overrun") { - eprintln!("capture error: {e}") + log(format!("capture error: {e}")) } }; Ok((dev.build_input_stream(cfg, on_data, on_err, None)?, rate)) @@ -578,7 +608,7 @@ fn serve_events(mut tcp: TcpStream, key: [u8; 64]) -> Res<()> { tcp.write_all( &out.seal(format!("RTSP/1.0 200 OK\r\n{cseq}Content-Length: 0\r\n\r\n").as_bytes()), )?; - eprintln!("event: {first}"); + log(format!("event: {first}")); } } @@ -1017,11 +1047,11 @@ fn stream_to( if let Err(e) = serve_events(tcp, key) && !c.stopped() { - eprintln!("event channel closed: {e}"); + log(format!("event channel closed: {e}")); } }); } - Err(e) => eprintln!("no event channel ({e}), continuing without"), + Err(e) => log(format!("no event channel ({e}), continuing without")), } let c = ctl.clone(); std::thread::spawn(move || serve_timing(timing, c)); @@ -1302,6 +1332,15 @@ mod tests { assert!((v.level().unwrap() - 1.0).abs() < 0.01); } + #[test] + fn utc_formats_known_instants() { + let at = |secs| utc(UNIX_EPOCH + Duration::from_secs(secs)); + assert_eq!(at(0), "1970-01-01T00:00:00Z"); + assert_eq!(at(951_782_400), "2000-02-29T00:00:00Z"); // leap day in a century leap year + assert_eq!(at(1_794_232_387), "2026-11-09T13:53:07Z"); + assert_eq!(at(4_102_444_799), "2099-12-31T23:59:59Z"); + } + #[test] fn find_by_name_part() { let d: Vec<(String, SocketAddr)> = ["Kitchen", "Living Room"] diff --git a/src/tray.rs b/src/tray.rs index d927478..76da2e1 100644 --- a/src/tray.rs +++ b/src/tray.rs @@ -1,11 +1,15 @@ //! Windows tray icon: pick an AirPlay device and a latency from the menu; streaming runs in a background thread. use super::*; +use std::os::windows::io::IntoRawHandle; +use std::path::PathBuf; use std::sync::mpsc; use std::thread::JoinHandle; use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu}; use tray_icon::{Icon, TrayIconBuilder}; -use windows_sys::Win32::System::Console::FreeConsole; +use windows_sys::Win32::System::Console::{ + FreeConsole, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE, SetStdHandle, +}; use windows_sys::Win32::UI::WindowsAndMessaging::{ DispatchMessageW, GetMessageW, MSG, SetTimer, TranslateMessage, }; @@ -62,6 +66,7 @@ fn menu( current: Option, latency_ms: u32, status: &str, + has_log: bool, ) -> Res { let m = Menu::new(); m.append(&MenuItem::new(status, false, None))?; @@ -105,12 +110,38 @@ fn menu( } m.append(&lat)?; m.append(&MenuItem::with_id("stop", "Stop", current.is_some(), None))?; + m.append(&MenuItem::with_id("log", "Open log", has_log, None))?; m.append(&MenuItem::with_id("quit", "Quit", true, None))?; Ok(m) } +/// Send everything podbeam prints (status, errors, panics) to `%LOCALAPPDATA%\podbeam\podbeam.log`. +/// A log over 1 MB is moved to `podbeam.log.1` first, so the previous run survives one restart. +fn log_to_file() -> Option { + let dir = PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("podbeam"); + std::fs::create_dir_all(&dir).ok()?; + let path = dir.join("podbeam.log"); + if std::fs::metadata(&path).is_ok_and(|m| m.len() > 1 << 20) { + let _ = std::fs::rename(&path, dir.join("podbeam.log.1")); + } + let file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .ok()?; + // SAFETY: a valid handle that is never closed; std looks the std handles up on every write. + unsafe { + let handle = file.into_raw_handle(); + SetStdHandle(STD_OUTPUT_HANDLE, handle); + SetStdHandle(STD_ERROR_HANDLE, handle); + } + Some(path) +} + pub fn run(mut latency_ms: u32) -> Res<()> { unsafe { FreeConsole() }; // the tray needs no console window + let log_path = log_to_file(); + log(format!("podbeam {} started", env!("CARGO_PKG_VERSION"))); let (found_tx, found) = mpsc::channel(); let search = move || { let tx = found_tx.clone(); @@ -155,6 +186,11 @@ pub fn run(mut latency_ms: u32) -> Res<()> { if let Some(addr) = session.as_ref().filter(|s| s.running()).map(|s| s.addr) { session = restart(session.take(), addr, ms); } + } else if id == "log" { + // Explorer opens the file with whatever the user has set for .log files. + if let Some(p) = &log_path { + let _ = std::process::Command::new("explorer").arg(p).spawn(); + } } else if id == "stop" || id == "quit" { if let Some(s) = session.take() { s.end(); @@ -178,7 +214,12 @@ pub fn run(mut latency_ms: u32) -> Res<()> { let state = (status.clone(), running, current, latency_ms); if dirty || shown.as_ref() != Some(&state) { tray.set_menu(Some(Box::new(menu( - &devices, searching, current, latency_ms, &status, + &devices, + searching, + current, + latency_ms, + &status, + log_path.is_some(), )?))); tray.set_tooltip(Some(format!("podbeam: {status}")))?; tray.set_icon(Some(icon(running)))?;