From a3b9f192826862a6322c25069b0401d412405230 Mon Sep 17 00:00:00 2001 From: astar76 Date: Thu, 19 Nov 2026 06:56:46 -0600 Subject: [PATCH] player: ffmpeg fallback for formats symphonia can't decode Symphonia now has all its pure-Rust codecs and formats. What it can't decode (Opus, WMA, AC-3, the sound of video files) goes through the ffmpeg CLI: ffprobe for rate and length, raw f32 PCM piped into the same output, seeking by restarting with -ss, the child killed on stop. Missing ffmpeg keeps the unsupported error. A Handle lets another thread close the playing file while it is rewritten and resume it in place (D-041). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 23 +++ Cargo.toml | 2 +- crates/tunal-player/src/ffmpeg.rs | 239 ++++++++++++++++++++++++++++ crates/tunal-player/src/lib.rs | 107 ++++++++++++- crates/tunal-player/src/source.rs | 81 ++++++++-- crates/tunal-player/src/waveform.rs | 4 +- crates/tunal-player/tests/ffmpeg.rs | 131 +++++++++++++++ docs/DECISIONS.md | 1 + 8 files changed, 572 insertions(+), 16 deletions(-) create mode 100644 crates/tunal-player/src/ffmpeg.rs create mode 100644 crates/tunal-player/tests/ffmpeg.rs diff --git a/Cargo.lock b/Cargo.lock index 1d74832..af3aca9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6397,9 +6397,11 @@ dependencies = [ "symphonia-bundle-mp3", "symphonia-codec-aac", "symphonia-codec-adpcm", + "symphonia-codec-alac", "symphonia-codec-pcm", "symphonia-codec-vorbis", "symphonia-core", + "symphonia-format-caf", "symphonia-format-isomp4", "symphonia-format-mkv", "symphonia-format-ogg", @@ -6452,6 +6454,16 @@ dependencies = [ "symphonia-core", ] +[[package]] +name = "symphonia-codec-alac" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8413fa754942ac16a73634c9dfd1500ed5c61430956b33728567f667fdd393ab" +dependencies = [ + "log", + "symphonia-core", +] + [[package]] name = "symphonia-codec-pcm" version = "0.5.5" @@ -6486,6 +6498,17 @@ dependencies = [ "log", ] +[[package]] +name = "symphonia-format-caf" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8faf379316b6b6e6bbc274d00e7a592e0d63ff1a7e182ce8ba25e24edd3d096" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", +] + [[package]] name = "symphonia-format-isomp4" version = "0.5.5" diff --git a/Cargo.toml b/Cargo.toml index 4c322e5..d8cec4b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,7 @@ ureq = { version = "3", default-features = false, features = ["rustls", "gzip"] serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1.2" -symphonia = { version = "0.5", features = ["mp3", "aac", "isomp4"] } +symphonia = { version = "0.5", features = ["all"] } cpal = "0.18" rubato = "0.16" rtrb = "0.4" diff --git a/crates/tunal-player/src/ffmpeg.rs b/crates/tunal-player/src/ffmpeg.rs new file mode 100644 index 0000000..788c401 --- /dev/null +++ b/crates/tunal-player/src/ffmpeg.rs @@ -0,0 +1,239 @@ +//! Fallback decoding through the `ffmpeg` CLI for what symphonia can't read (Opus, WMA, AC-3, +//! the audio track of a video…): `ffprobe` tells the rate and length, `ffmpeg` pipes raw +//! stereo `f32` frames. Seeking starts a new `ffmpeg` at the target. Without the tools these +//! files stay unsupported. + +use std::ffi::OsString; +use std::io::{ErrorKind, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdout, Command, Stdio}; +use std::sync::OnceLock; +use std::time::Duration; + +use crate::Error; + +/// Channels ffmpeg is asked for; the output maps them like any other source. +pub(crate) const CHANNELS: usize = 2; +const FRAME_BYTES: usize = CHANNELS * 4; +/// Bytes asked for per read: 4096 frames. +const READ: usize = 4096 * FRAME_BYTES; +/// Rate used when ffprobe names none. +const DEFAULT_RATE: u32 = 48_000; + +/// `ffmpeg` and `ffprobe` can both be started (checked once per process). +pub fn available() -> bool { + static FOUND: OnceLock = OnceLock::new(); + *FOUND.get_or_init(|| { + ["ffmpeg", "ffprobe"].iter().all(|tool| { + Command::new(tool) + .arg("-version") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + }) + }) +} + +/// The path as an ffmpeg input: `file:` keeps names like `-x.opus` or `http:a` from being +/// read as an option or another protocol. +fn input(path: &Path) -> OsString { + let mut s = OsString::from("file:"); + s.push(path.as_os_str()); + s +} + +pub(crate) struct Ffmpeg { + path: PathBuf, + pub rate: u32, + pub duration: Option, + child: Option, + stdout: Option, + /// Raw bytes read; the first `partial` of them are the start of an incomplete frame. + bytes: Vec, + partial: usize, + samples: Vec, + /// The first chunk, read by `open` to check the file decodes, is still unread. + primed: bool, + /// The current `ffmpeg` gave at least one frame. + produced: bool, +} + +impl Ffmpeg { + /// Opens the first audio stream of `path`, decoded at `rate` (its own rate when `None`). + pub fn open(path: &Path, rate: Option) -> Result { + if !available() { + return Err(Error::Unsupported); + } + let (own_rate, duration) = probe(path)?; + let mut source = Ffmpeg { + path: path.to_path_buf(), + rate: rate.unwrap_or(own_rate), + duration, + child: None, + stdout: None, + bytes: Vec::new(), + partial: 0, + samples: Vec::new(), + primed: false, + produced: false, + }; + source.spawn(Duration::ZERO)?; + if source.next()?.is_none() { + return Err(Error::Decode("no audio".into())); + } + source.primed = true; + Ok(source) + } + + /// Next interleaved stereo frames, `None` at the end of the stream. + pub fn next(&mut self) -> Result, Error> { + if self.primed { + self.primed = false; + return Ok(Some(&self.samples)); + } + let Some(stdout) = &mut self.stdout else { + return Ok(None); + }; + loop { + let start = self.partial; + self.bytes.resize(start + READ, 0); + let n = match stdout.read(&mut self.bytes[start..]) { + Ok(n) => n, + Err(e) if e.kind() == ErrorKind::Interrupted => continue, + Err(e) => return Err(Error::Io(e.to_string())), + }; + if n == 0 { + self.finish()?; + return Ok(None); + } + let total = start + n; + let whole = total - total % FRAME_BYTES; + if whole == 0 { + self.partial = total; + continue; + } + self.samples.clear(); + self.samples.extend( + self.bytes[..whole] + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])), + ); + self.bytes.copy_within(whole..total, 0); + self.partial = total - whole; + self.produced = true; + return Ok(Some(&self.samples)); + } + } + + pub fn seek(&mut self, to: Duration) -> Result<(), Error> { + self.primed = false; + self.spawn(to) + } + + fn spawn(&mut self, at: Duration) -> Result<(), Error> { + self.stop(); + let mut cmd = Command::new("ffmpeg"); + cmd.args(["-nostdin", "-v", "error"]); + if !at.is_zero() { + cmd.arg("-ss").arg(format!("{:.3}", at.as_secs_f64())); + } + cmd.arg("-i") + .arg(input(&self.path)) + .args(["-map", "0:a:0", "-vn", "-sn", "-dn", "-f", "f32le", "-ac"]) + .arg(CHANNELS.to_string()) + .arg("-ar") + .arg(self.rate.to_string()) + .arg("-"); + let mut child = cmd + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|e| Error::Io(e.to_string()))?; + self.stdout = child.stdout.take(); + self.child = Some(child); + self.partial = 0; + self.produced = false; + Ok(()) + } + + /// The stream ended: reaps `ffmpeg`; a run that failed before any frame is an error. + fn finish(&mut self) -> Result<(), Error> { + self.stdout = None; + let Some(mut child) = self.child.take() else { + return Ok(()); + }; + let status = child.wait().map_err(|e| Error::Io(e.to_string()))?; + if !status.success() && !self.produced { + return Err(Error::Decode(format!("ffmpeg exited with {status}"))); + } + Ok(()) + } + + /// Kills a running `ffmpeg` and waits for it, so it no longer reads the file. + fn stop(&mut self) { + self.stdout = None; + if let Some(mut child) = self.child.take() { + let _ = child.kill(); + let _ = child.wait(); + } + } +} + +impl Drop for Ffmpeg { + fn drop(&mut self) { + self.stop(); + } +} + +/// The first audio stream's rate and the file's length. No audio stream (or a file ffprobe +/// can't read) is unsupported. +fn probe(path: &Path) -> Result<(u32, Option), Error> { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-show_entries", + "stream=sample_rate,duration:format=duration", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(input(path)) + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .map_err(|e| Error::Io(e.to_string()))?; + if !out.status.success() { + return Err(Error::Unsupported); + } + let text = String::from_utf8_lossy(&out.stdout); + let mut rate = None; + let mut duration = None; + for line in text.lines() { + let Some((key, value)) = line.split_once('=') else { + continue; + }; + match key { + "sample_rate" => rate = value.trim().parse::().ok().filter(|&r| r > 0), + // The stream's length comes first; the container's fills in when it has none. + "duration" if duration.is_none() => { + duration = value + .trim() + .parse::() + .ok() + .filter(|d| d.is_finite() && *d > 0.0) + .map(Duration::from_secs_f64); + } + _ => {} + } + } + // A stream section always names its rate: none means no audio stream. + if !text.contains("sample_rate=") { + return Err(Error::Unsupported); + } + Ok((rate.unwrap_or(DEFAULT_RATE), duration)) +} diff --git a/crates/tunal-player/src/lib.rs b/crates/tunal-player/src/lib.rs index f38ba60..0f7117b 100644 --- a/crates/tunal-player/src/lib.rs +++ b/crates/tunal-player/src/lib.rs @@ -1,20 +1,23 @@ //! Audio playback and waveform data. //! -//! [`Player`] decodes with symphonia on its own thread and plays through cpal on the default -//! output device; [`Waveforms`] computes min/max peaks for a seek bar. +//! [`Player`] decodes with symphonia on its own thread (with the `ffmpeg` CLI for what +//! symphonia can't decode) and plays through cpal on the default output device; [`Waveforms`] +//! computes min/max peaks for a seek bar. +mod ffmpeg; mod output; mod source; mod waveform; use std::fmt; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; +pub use ffmpeg::available as ffmpeg_available; pub use waveform::{WaveTicket, Waveform, Waveforms}; use output::Output; @@ -27,7 +30,7 @@ const FILL_INTERVAL: Duration = Duration::from_millis(20); #[derive(Clone, Debug, PartialEq, Eq)] pub enum Error { - /// The container or codec can't be decoded (e.g. Opus). + /// Neither symphonia nor ffmpeg (when installed) can decode the file. Unsupported, Io(String), Decode(String), @@ -81,10 +84,57 @@ pub(crate) enum Command { Pause, Stop, Seek(Duration), + /// Closes the file when it is the open track; answers with where it was. + Release(PathBuf, Sender>), + /// Opens a released track again where it was. + Reacquire(Held), OutputError(String), Quit, } +/// A track closed by `Command::Release`. +pub(crate) struct Held { + path: PathBuf, + position: Duration, +} + +/// How long a release waits for the engine (it answers within one fill, normally ms). +const RELEASE_WAIT: Duration = Duration::from_secs(3); + +/// A sendable handle to a [`Player`]'s engine, for work on other threads. +#[derive(Clone)] +pub struct Handle { + commands: Sender, +} + +impl Handle { + /// Runs `f` with `path` closed when it is the open track, then opens it again at the same + /// position, playing on if it played: for rewriting the file in place (tag edits). + /// Blocks until the engine has let go of the file. + pub fn without(&self, path: &Path, f: impl FnOnce() -> T) -> T { + let (tx, rx) = mpsc::channel(); + let sent = self + .commands + .send(Command::Release(path.to_path_buf(), tx)) + .is_ok(); + let mut held = if sent { + rx.recv_timeout(RELEASE_WAIT).ok().flatten() + } else { + None + }; + let out = f(); + // A late answer still has to be given back; one after `rx` is gone the engine takes + // back by itself. + if held.is_none() { + held = rx.try_recv().ok().flatten(); + } + if let Some(held) = held { + let _ = self.commands.send(Command::Reacquire(held)); + } + out + } +} + /// One track at a time. Commands are queued to the engine thread; results arrive as /// [`Event`]s on the callback given to [`Player::new`], called on that thread. pub struct Player { @@ -102,6 +152,7 @@ impl Player { rx, commands: commands.clone(), volume: volume.clone(), + path: None, source: None, output: None, state: State::Stopped, @@ -141,6 +192,12 @@ impl Player { self.send(Command::Seek(to)); } + pub fn handle(&self) -> Handle { + Handle { + commands: self.commands.clone(), + } + } + /// Linear gain, clamped to 0..=1; takes effect at once. pub fn set_volume(&self, volume: f32) { let v = volume.clamp(0.0, 1.0); @@ -170,6 +227,8 @@ struct Engine { rx: Receiver, commands: Sender, volume: Arc, + /// The track last opened; its `source` is gone while a release holds it. + path: Option, source: Option, /// Present while playing or paused mid-track; dropped on stop, seek and end. output: Option, @@ -219,6 +278,7 @@ impl Engine { Command::Open(path) => { self.output = None; self.source = None; + self.path = Some(path.clone()); self.set_state(State::Stopped); let source = Source::open(&path)?; let duration = source.duration; @@ -276,6 +336,45 @@ impl Engine { self.handle(Command::Play)?; } } + Command::Release(path, answer) => { + if self.source.is_none() || self.path.as_ref() != Some(&path) { + let _ = answer.send(None); + return Ok(()); + } + // The state stays: a play or pause meanwhile applies when the track is back. + let held = Held { + position: self.position(), + path, + }; + self.base = held.position; + self.output = None; + self.source = None; + if let Err(mpsc::SendError(Some(held))) = answer.send(Some(held)) { + // Nobody waits any more: take the file back at once. + return self.handle(Command::Reacquire(held)); + } + } + Command::Reacquire(held) => { + // Another track was opened meanwhile. + if self.source.is_some() || self.path.as_ref() != Some(&held.path) { + return Ok(()); + } + let mut source = Source::open(&held.path)?; + let duration = source.duration; + source.seek(held.position)?; + self.source = Some(source); + self.base = held.position; + self.exhausted = false; + self.emit(Event::Opened { + path: held.path, + duration, + }); + self.emit(Event::Position(held.position)); + if self.state == State::Playing { + self.state = State::Paused; + self.handle(Command::Play)?; + } + } Command::OutputError(e) => return Err(Error::Output(e)), Command::Quit => {} } diff --git a/crates/tunal-player/src/source.rs b/crates/tunal-player/src/source.rs index 81964fa..06c673f 100644 --- a/crates/tunal-player/src/source.rs +++ b/crates/tunal-player/src/source.rs @@ -1,4 +1,5 @@ -//! A decoded audio file: interleaved `f32` frames from symphonia, with accurate seeking. +//! A decoded audio file: interleaved `f32` frames from symphonia, with accurate seeking, or +//! from the `ffmpeg` CLI for what symphonia can't decode. use std::fs::File; use std::io::ErrorKind; @@ -15,15 +16,76 @@ use symphonia::core::probe::Hint; use symphonia::core::units::{Time, TimeBase}; use crate::Error; +use crate::ffmpeg::{self, Ffmpeg}; pub(crate) struct Source { + pub rate: u32, + pub channels: usize, + pub duration: Option, + inner: Inner, +} + +enum Inner { + Native(Native), + Ffmpeg(Ffmpeg), +} + +impl Source { + pub fn open(path: &Path) -> Result { + Self::open_with(path, None) + } + + /// Like `open`; a file only ffmpeg decodes comes at `fallback_rate` (its own when `None`). + pub fn open_with(path: &Path, fallback_rate: Option) -> Result { + match Native::open(path) { + Ok(n) => Ok(Source { + rate: n.rate, + channels: n.channels, + duration: n.duration, + inner: Inner::Native(n), + }), + Err(e @ (Error::Unsupported | Error::Decode(_))) => { + match Ffmpeg::open(path, fallback_rate) { + Ok(f) => Ok(Source { + rate: f.rate, + channels: ffmpeg::CHANNELS, + duration: f.duration, + inner: Inner::Ffmpeg(f), + }), + // Neither can read it: symphonia's reason stands. + Err(Error::Unsupported) => Err(e), + Err(other) => Err(other), + } + } + Err(e) => Err(e), + } + } + + /// Next interleaved frames (`channels` samples each), `None` at the end of the stream. + pub fn next(&mut self) -> Result, Error> { + match &mut self.inner { + Inner::Native(n) => n.next(), + Inner::Ffmpeg(f) => f.next(), + } + } + + pub fn seek(&mut self, to: Duration) -> Result<(), Error> { + match &mut self.inner { + Inner::Native(n) => n.seek(to), + Inner::Ffmpeg(f) => f.seek(to), + } + } +} + +/// Decoding with symphonia. +struct Native { format: Box, decoder: Box, track_id: u32, time_base: Option, - pub rate: u32, - pub channels: usize, - pub duration: Option, + rate: u32, + channels: usize, + duration: Option, buf: Option>, /// Samples at the start of `buf` that precede a seek target. offset: usize, @@ -34,8 +96,8 @@ pub(crate) struct Source { ended: bool, } -impl Source { - pub fn open(path: &Path) -> Result { +impl Native { + fn open(path: &Path) -> Result { let file = File::open(path).map_err(|e| Error::Io(e.to_string()))?; let stream = MediaSourceStream::new(Box::new(file), Default::default()); let mut hint = Hint::new(); @@ -60,7 +122,7 @@ impl Source { let decoder = symphonia::default::get_codecs() .make(¶ms, &DecoderOptions::default()) .map_err(Error::from)?; - let mut source = Source { + let mut source = Native { format, decoder, track_id, @@ -86,8 +148,7 @@ impl Source { Ok(source) } - /// Next interleaved frames (`channels` samples each), `None` at the end of the stream. - pub fn next(&mut self) -> Result, Error> { + fn next(&mut self) -> Result, Error> { if self.primed { self.primed = false; } else if !self.decode_next()? { @@ -96,7 +157,7 @@ impl Source { Ok(self.buf.as_ref().map(|b| &b.samples()[self.offset..])) } - pub fn seek(&mut self, to: Duration) -> Result<(), Error> { + fn seek(&mut self, to: Duration) -> Result<(), Error> { self.primed = false; self.ended = false; self.seek_ts = None; diff --git a/crates/tunal-player/src/waveform.rs b/crates/tunal-player/src/waveform.rs index 61332c2..5ad4dfc 100644 --- a/crates/tunal-player/src/waveform.rs +++ b/crates/tunal-player/src/waveform.rs @@ -11,6 +11,8 @@ use crate::source::Source; /// Frames per fine block; blocks are merged into the requested bucket count at the end. const BLOCK: usize = 256; +/// Rate a file only ffmpeg decodes is read at for peaks: plenty for a seek bar. +const PEAK_RATE: u32 = 8000; /// Cached waveforms kept before the cache is emptied. const CACHE_LIMIT: usize = 256; @@ -87,7 +89,7 @@ impl Waveforms { /// Decodes `path` into `buckets` min/max pairs; checks `cancel` between packets. pub fn compute(path: &Path, buckets: usize, cancel: &AtomicBool) -> Result { - let mut source = Source::open(path)?; + let mut source = Source::open_with(path, Some(PEAK_RATE))?; let channels = source.channels; let rate = source.rate; let mut blocks: Vec<(f32, f32)> = Vec::new(); diff --git a/crates/tunal-player/tests/ffmpeg.rs b/crates/tunal-player/tests/ffmpeg.rs new file mode 100644 index 0000000..5b411ef --- /dev/null +++ b/crates/tunal-player/tests/ffmpeg.rs @@ -0,0 +1,131 @@ +//! The ffmpeg fallback on files symphonia can't decode; skipped without ffmpeg. No audio device +//! is needed: opening a track and computing its waveform both decode without output. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::mpsc; +use std::time::Duration; + +use tunal_player::{Event, Player, Waveforms, ffmpeg_available}; + +/// Runs ffmpeg with `args` to make `name` in `dir` from a one-second 440 Hz tone (plus a +/// test picture when `video`). +fn make(dir: &Path, name: &str, video: bool, args: &[&str]) -> PathBuf { + let out = dir.join(name); + let mut cmd = Command::new("ffmpeg"); + cmd.args(["-nostdin", "-v", "error", "-y"]); + if video { + cmd.args(["-f", "lavfi", "-i", "testsrc=duration=1:size=64x48:rate=10"]); + } + cmd.args(["-f", "lavfi", "-i", "sine=frequency=440:duration=1"]) + .args(args) + .arg(&out); + assert!(cmd.status().unwrap().success(), "ffmpeg made {name}"); + out +} + +fn peaks_and_length(path: &Path) -> (f32, f64) { + let (tx, rx) = mpsc::channel(); + Waveforms::new().request(path, 16, move |r| tx.send(r).unwrap()); + let wave = rx.recv_timeout(Duration::from_secs(30)).unwrap().unwrap(); + let top = wave.peaks.iter().map(|p| p.1).fold(0.0, f32::max); + (top, wave.duration.as_secs_f64()) +} + +/// Opens `path` in a player and returns the events up to the first position. +fn open_events(player: &Player, rx: &mpsc::Receiver, path: &Path) -> Vec { + player.open(path); + let mut events = Vec::new(); + loop { + let event = rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let last = matches!(event, Event::Position(_) | Event::Error(_)); + events.push(event); + if last { + return events; + } + } +} + +fn opened_duration(events: &[Event]) -> Option { + events.iter().find_map(|e| match e { + Event::Opened { duration, .. } => *duration, + _ => None, + }) +} + +#[test] +fn opus_and_video_containers_decode_through_ffmpeg() { + if !ffmpeg_available() { + eprintln!("skipped: no ffmpeg"); + return; + } + let dir = tempfile::tempdir().unwrap(); + let files = [ + make(dir.path(), "t.opus", false, &["-c:a", "libopus"]), + make(dir.path(), "-dash t.opus", false, &["-c:a", "libopus"]), + make( + dir.path(), + "v.mkv", + true, + &["-c:v", "mpeg4", "-c:a", "libopus"], + ), + make(dir.path(), "v.avi", true, &["-c:v", "mpeg4", "-c:a", "ac3"]), + ]; + let (tx, rx) = mpsc::channel(); + let player = Player::new(move |e| { + let _ = tx.send(e); + }); + for path in &files { + let name = path.file_name().unwrap().to_string_lossy(); + let (top, secs) = peaks_and_length(path); + // lavfi's sine is at 1/8 of full scale. + assert!(top > 0.05, "{name}: peak {top}"); + assert!((0.9..=1.2).contains(&secs), "{name}: {secs} s of samples"); + let events = open_events(&player, &rx, path); + let duration = opened_duration(&events).unwrap_or_else(|| panic!("{name}: {events:?}")); + assert!( + (0.9..=1.2).contains(&duration.as_secs_f64()), + "{name}: {duration:?}" + ); + } +} + +#[test] +fn a_released_track_comes_back_where_it_was() { + if !ffmpeg_available() { + eprintln!("skipped: no ffmpeg"); + return; + } + let dir = tempfile::tempdir().unwrap(); + let path = make(dir.path(), "t.opus", false, &["-c:a", "libopus"]); + let other = make(dir.path(), "o.opus", false, &["-c:a", "libopus"]); + let (tx, rx) = mpsc::channel(); + let player = Player::new(move |e| { + let _ = tx.send(e); + }); + open_events(&player, &rx, &path); + player.seek(Duration::from_millis(400)); + assert!(matches!( + rx.recv_timeout(Duration::from_secs(10)).unwrap(), + Event::Position(p) if p == Duration::from_millis(400) + )); + let handle = player.handle(); + // Another file: nothing to let go of. + assert_eq!(handle.without(&other, || 1), 1); + // The open track: closed while `f` runs (it may rewrite the file), then reopened. + let copy = dir.path().join("copy.opus"); + handle.without(&path, || std::fs::copy(&path, ©).unwrap()); + let mut events = Vec::new(); + while let Ok(event) = rx.recv_timeout(Duration::from_secs(10)) { + let last = matches!(event, Event::Position(_)); + events.push(event); + if last { + break; + } + } + assert!(opened_duration(&events).is_some(), "{events:?}"); + assert!( + matches!(events.last(), Some(Event::Position(p)) if *p == Duration::from_millis(400)), + "{events:?}" + ); +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 9cdc78e..56c3b00 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -43,3 +43,4 @@ D-038 — 2026-11-18 — Elevation is per job thread: `tunal_elevate::Elevation` D-039 — 2026-11-19 — Native DnD/clipboard on Wayland (`native/`): Slint's foreign `wl_display` wrapped with `wayland-backend` `client_system`, our own queue (wl_seat → own wl_pointer/wl_keyboard for serials, one wl_data_device v3) dispatched on a `tunal-wayland` thread; surface from the raw window handle (`raw-window-handle-06`). Drag in goes through Slint's internal `WindowInner::process_drag_event` (`i-slint-core` pinned `=1.19.0`), so DropZones, glow and drop menu are shared with in-app drags (proposed action Move → menu). Drag out: an in-app drag arms the payload; when our pointer reports motion outside the window with the button held, `start_drag` with the press serial, then a synthetic release ends Slint's in-window drag. Drag out offers Copy only (never removes our files); no drag icon yet. Clipboard: copy/cut also `set_selection` (uri-list, text, `x-special/gnome-copied-files`, internal marker); paste prefers another app's files when the clipboard holds them. Native off (None) on X11 and in screenshots — S030 — S031, S036. D-038 — 2026-11-19 — Native DnD on Wayland (S030) is verified by build plus an Xvfb fallback run only; no window is opened on the user's live niri session; the Wayland attach check and the drag-out test move to S036 (real cross-app checks with the user) — orchestrator, per CLAUDE.md §4 offscreen rule — S030, S036. D-040 — 2026-11-19 — Overnight unattended run (user asleep): S033 and S034 run in parallel (no shared files); S035 runs to its 🧑 visual-review step and stops; S036 does only its checklist step (all other steps need the user); S037 runs before S036 is finished but leaves STATUS.md at "S035 review and S036 checks open" instead of "done". Usage-limit resume by one-shot wake-ups of the orchestrator (D-036) — orchestrator — S033–S037. +D-041 — 2026-11-19 — Player decoding: symphonia (all its pure-Rust codecs and formats) first, then the `ffmpeg` CLI as a fallback for what it can't decode (Opus, WMA, AC-3, the sound of video files…): `ffprobe` gives rate and length, `ffmpeg -f f32le -ac 2` pipes PCM into the same output path, seeking restarts it with `-ss`, the child is killed on stop. Not FFmpeg bindings: the CLI pattern already exists (D-004 video frames), it needs no C libraries at build time, it stays optional at runtime (missing → "unsupported audio format" as before, D-016), and symphonia 0.5 has no Opus. Play is offered for audio and video files; tag edits close the playing file while it is rewritten and resume it at the same position — user — player, tag editor.