Merge branch 'refs/heads/worktree-agent-a4d139ca566fb1c6c'

This commit is contained in:
astar76 2026-11-19 10:01:21 -06:00
commit c27e663444
17 changed files with 989 additions and 179 deletions

View file

@ -94,7 +94,7 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~
| `Xvfb :97 &` then `env -u WAYLAND_DISPLAY DISPLAY=:97 target/debug/tunal <dir> &` and `DISPLAY=:97 target/debug/examples/xdnd_probe x1 y1 x2 y2` (or `in x y <uri>`) | X11 native DnD: fake XTEST drag out of the window onto a probe target, or a probe source dropping into the app; Xvfb only | S031 |
| same, with `SLINT_BACKEND=winit-software` (so `DISPLAY=:97 import -window root <png>` captures it), then `DISPLAY=:97 target/debug/examples/xdnd_probe click x y [count] [gap_ms] [hover_ms]` | real clicks (XTEST) on a window point after resting `hover_ms` there, e.g. the split toggle with a tooltip showing; Xvfb only | split/tooltip fix |
| `TUNAL_APPEARANCE=1 XDG_CONFIG_HOME=<scratch> cargo run -p tunal -- <dir> --screenshot <png> --size 1000x760` | folder appearance dialog for `<dir>` (theme icons looked up at once); `cargo run -p tunal-dirmeta --example roundtrip -- <dir>` sets `Icon` in `<dir>/.directory` and prints the old values | S015 |
| `TUNAL_PLAY=<audio file> XDG_CONFIG_HOME=<scratch> cargo run -p tunal -- <dir> --screenshot <png> [--dark] --size 1200x760` | player bar open on that file, a third in (tags, cover, waveform read at once; no audio output) | S023 |
| `TUNAL_PLAY=<audio file> XDG_CONFIG_HOME=<scratch> cargo run -p tunal -- <dir> --screenshot <png> [--dark] --size 1200x760` (`TUNAL_PLAY_STATE=playing` draws it playing: the wave) | player bar open on that file, a third in (tags, cover, length read at once; no audio output), paused unless asked | S023 |
| `TUNAL_TAGS=editor\|lookup\|mapping\|apply:<file>:<file> TUNAL_TAGS_SYNC=1 TUNAL_MUSICBRAINZ=<mock url> XDG_CONFIG_HOME=<scratch> cargo run -p tunal -- <dir> --screenshot <png> --size 1000x760` | tag editor / lookup / mapping over a folder; `apply` also writes the tags (scratch copies only); mock = a local server for both services | S021 |
| `cargo run -p tunal -- --gallery --page connection\|host-key\|secret --screenshot <png> [--dark] --size 960x640` | the connection editor, the unknown-host-key prompt, the password prompt over a stand-in folder; with a scratch `HOME` (own `.ssh/config`, key) and `XDG_CONFIG_HOME` holding `tunal/connections.toml`, `session.toml` (pane `sftp://…`) and a trusted `known_hosts`, a normal `--screenshot` shows the Network section and an SFTP folder (local sshd on a spare port only) | S029 |
| `cargo build -p tunal && target/debug/tunal --matrix <dir>` (about 1.5 min) | screenshot matrix: shell full/grid/empty/split, row hover/pressed/selected, context menu, drag, rename, properties, open-with, delete, appearance, player, tag editor, settings pages 0–5, gallery pages, light + dark, 720x480 minimum; stand-in folder in `<dir>/fixture`, config in `<dir>/config`. Hooks: `TUNAL_POINTER=x,y[,press\|click\|menu]` (hover/press/select/right-click before the frame), `TUNAL_ACTION=<action id>` (runs a menu action on the selection) | S034 |

23
Cargo.lock generated
View file

@ -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"

View file

@ -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"

View file

@ -0,0 +1,237 @@
//! 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<bool> = 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<Duration>,
child: Option<Child>,
stdout: Option<ChildStdout>,
/// Raw bytes read; the first `partial` of them are the start of an incomplete frame.
bytes: Vec<u8>,
partial: usize,
samples: Vec<f32>,
/// 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<u32>) -> Result<Self, Error> {
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<Option<&[f32]>, 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();
let (samples, _) = self.bytes[..whole].as_chunks::<4>();
self.samples
.extend(samples.iter().map(|b| f32::from_le_bytes(*b)));
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<Duration>), 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::<u32>().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::<f64>()
.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))
}

View file

@ -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<Option<Held>>),
/// 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<Command>,
}
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<T>(&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<Command>,
commands: Sender<Command>,
volume: Arc<AtomicU32>,
/// The track last opened; its `source` is gone while a release holds it.
path: Option<PathBuf>,
source: Option<Source>,
/// Present while playing or paused mid-track; dropped on stop, seek and end.
output: Option<Output>,
@ -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 => {}
}

View file

@ -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<Duration>,
inner: Inner,
}
enum Inner {
Native(Native),
Ffmpeg(Ffmpeg),
}
impl Source {
pub fn open(path: &Path) -> Result<Self, Error> {
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<u32>) -> Result<Self, Error> {
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<Option<&[f32]>, 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<dyn FormatReader>,
decoder: Box<dyn Decoder>,
track_id: u32,
time_base: Option<TimeBase>,
pub rate: u32,
pub channels: usize,
pub duration: Option<Duration>,
rate: u32,
channels: usize,
duration: Option<Duration>,
buf: Option<SampleBuffer<f32>>,
/// 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<Self, Error> {
impl Native {
fn open(path: &Path) -> Result<Self, Error> {
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(&params, &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<Option<&[f32]>, Error> {
fn next(&mut self) -> Result<Option<&[f32]>, 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;

View file

@ -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<Waveform, Error> {
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();

View file

@ -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<Event>, path: &Path) -> Vec<Event> {
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<Duration> {
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, &copy).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:?}"
);
}

View file

@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};
use lofty::config::WriteOptions;
use lofty::file::{AudioFile, TaggedFile, TaggedFileExt};
use lofty::picture::{MimeType, Picture, PictureType};
use lofty::probe::Probe;
use lofty::tag::{Accessor, ItemKey, Tag, TagType};
use crate::model::{Cover, CoverEdit, Edit, TagEdit, TagSet, TrackTags};
@ -100,8 +101,15 @@ fn read_tag(tag: &Tag) -> TrackTags {
}
}
/// Opens a file by its content (MP3, FLAC, Ogg Vorbis/Opus/Speex, MP4/M4A, WAV, AIFF, APE,
/// WavPack, Musepack, AAC); the extension only decides when the content can't.
fn open(path: &Path) -> Result<TaggedFile, Error> {
lofty::read_from_path(path).map_err(tag_err)
Probe::open(path)
.map_err(tag_err)?
.guess_file_type()
.map_err(Error::Io)?
.read()
.map_err(tag_err)
}
/// Reads the tags of one file. A file without a tag gives empty tags.

View file

@ -0,0 +1,103 @@
//! Tags round-trip on every format the editor offers, on files made with ffmpeg in a temp dir;
//! skipped without ffmpeg (the fixed fixtures in tags.rs cover the common five).
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use tunal_tags::{Edit, TagEdit, duration_ms, read, write};
fn ffmpeg() -> bool {
Command::new("ffmpeg")
.arg("-version")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|s| s.success())
}
/// A one-second tone in `name`, encoded with `args`, or `None` when this ffmpeg lacks the
/// encoder.
fn make(dir: &Path, name: &str, args: &[&str]) -> Option<PathBuf> {
let out = dir.join(name);
let ok = Command::new("ffmpeg")
.args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"])
.arg("sine=frequency=440:duration=1")
.args(args)
.arg(&out)
.status()
.is_ok_and(|s| s.success());
ok.then_some(out)
}
fn edit() -> TagEdit {
let s = |v: &str| Edit::Set(v.to_owned());
TagEdit {
title: s("Wave"),
artist: s("Tester"),
album: s("Formats"),
track_no: Edit::Set(7),
date: s("2024"),
..TagEdit::default()
}
}
#[test]
fn tags_round_trip_on_every_offered_format() {
if !ffmpeg() {
eprintln!("skipped: no ffmpeg");
return;
}
let dir = tempfile::tempdir().unwrap();
let formats: [(&str, &[&str]); 11] = [
("t.mp3", &["-c:a", "libmp3lame"]),
("t.flac", &["-c:a", "flac"]),
("t.ogg", &["-c:a", "libvorbis"]),
("t.opus", &["-c:a", "libopus"]),
("t.spx", &["-c:a", "libspeex", "-ar", "16000"]),
("t.m4a", &["-c:a", "aac"]),
("alac.m4a", &["-c:a", "alac"]),
("t.wav", &["-c:a", "pcm_s16le"]),
("t.aiff", &["-c:a", "pcm_s16be"]),
("t.wv", &["-c:a", "wavpack"]),
// Opus content under another format's name: lofty goes by the content.
("opus-named.ogg", &["-c:a", "libopus", "-f", "ogg"]),
];
let mut tried = 0;
for (name, args) in formats {
let Some(path) = make(dir.path(), name, args) else {
eprintln!("{name}: encoder missing, skipped");
continue;
};
tried += 1;
let before = duration_ms(&path).unwrap_or_else(|| panic!("{name}: no duration"));
write(&path, &edit()).unwrap_or_else(|e| panic!("{name}: {e}"));
let t = read(&path).unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!(t.title.as_deref(), Some("Wave"), "{name}");
assert_eq!(t.artist.as_deref(), Some("Tester"), "{name}");
assert_eq!(t.album.as_deref(), Some("Formats"), "{name}");
assert_eq!(t.track_no, Some(7), "{name}");
// A second edit touches only its field.
let retitle = TagEdit {
title: Edit::Set("Wave 2".into()),
..TagEdit::default()
};
write(&path, &retitle).unwrap_or_else(|e| panic!("{name}: {e}"));
let t = read(&path).unwrap();
assert_eq!(t.title.as_deref(), Some("Wave 2"), "{name}");
assert_eq!(t.artist.as_deref(), Some("Tester"), "{name}");
// The audio is still all there.
let after = duration_ms(&path).unwrap_or_else(|| panic!("{name}: no duration after"));
assert!(
before.abs_diff(after) <= 50,
"{name}: {before} → {after} ms"
);
let decoded = Command::new("ffmpeg")
.args(["-nostdin", "-v", "error", "-i"])
.arg(&path)
.args(["-f", "null", "-"])
.status()
.unwrap();
assert!(decoded.success(), "{name}: still decodes");
}
assert!(tried >= 5, "only {tried} formats could be made");
}

View file

@ -15,7 +15,7 @@ use crate::folder::appearance::Appearance;
use crate::jobs_bridge::Bridge;
use crate::menus::{Context as MenuContext, Menus};
use crate::open::Opener;
use crate::player_bridge::PlayerUi;
use crate::player_bridge::{self, PlayerUi};
use crate::properties::Properties;
use crate::shell::Shell;
use crate::shell::pane::Pane;
@ -228,7 +228,8 @@ impl Action {
Self::Open | Self::OpenWith => files && ctx.selected > 0,
Self::Properties | Self::SortBy | Self::ViewMode => true,
Self::Appearance => files && ctx.selected <= 1,
Self::EditTags | Self::Play => files && ctx.audio,
Self::EditTags => files && ctx.taggable,
Self::Play => files && ctx.playable,
}
}
}
@ -242,8 +243,10 @@ pub struct Context {
pub can_trash: bool,
/// The clipboard holds something to paste.
pub paste: bool,
/// Every selected entry is a local audio file.
pub audio: bool,
/// Every selected entry is a local audio file whose tags can be written.
pub taggable: bool,
/// Every selected entry is a local audio or video file (video plays its sound).
pub playable: bool,
}
#[derive(Default)]
@ -359,10 +362,10 @@ impl Actions {
.map(|l| l.capabilities())
.unwrap_or_default();
let selected = pane.model.selected_uris();
let files = !selected.is_empty() && !pane.model.selection_is_dir();
Context {
audio: !selected.is_empty()
&& !pane.model.selection_is_dir()
&& selected.iter().all(tags_bridge::is_audio),
taggable: files && selected.iter().all(tags_bridge::can_tag),
playable: files && selected.iter().all(player_bridge::can_play),
selected: selected.len(),
in_trash: pane.dir().is_some_and(|d| d.scheme() == tunal_core::TRASH),
writable: caps.write,
@ -593,12 +596,12 @@ impl Actions {
return;
}
Action::Play => {
// The folder's audio files queue up after the first one chosen.
// The folder's playable files queue up after the first one chosen.
let queue: Vec<_> = pane
.model
.shown_files()
.iter()
.filter(|u| tags_bridge::is_audio(u))
.filter(|u| player_bridge::can_play(u))
.filter_map(|u| u.to_path())
.collect();
if let Some(first) = uris.first().and_then(|u| u.to_path()) {

View file

@ -1,27 +1,43 @@
//! The quick player: the bar under the panes plays one audio file at a time, with its tags,
//! cover and waveform, and goes on through the folder's audio files when the setting says so.
//! Playback, tags and the waveform run off the UI thread; their results come back to the UI
//! The quick player: the bar under the panes plays one audio file (or a video's sound) at a
//! time, with its tags and cover, and goes on through the folder's playable files when the
//! setting says so. Playback and tags run off the UI thread; their results come back to the UI
//! thread, where the bar's state lives (a thread-local, so only plain data crosses threads).
use std::cell::{Cell, OnceCell, RefCell};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::time::Duration;
use slint::{ComponentHandle, Image, ModelRc, Rgba8Pixel, SharedPixelBuffer, VecModel};
use tunal_player::{Event, Player, State, WaveTicket, Waveform, Waveforms};
use slint::{ComponentHandle, Image, Rgba8Pixel, SharedPixelBuffer};
use tunal_core::{Kind, Uri, mime};
use tunal_player::{Event, Handle, Player, State, WaveTicket, Waveform, Waveforms};
use crate::config;
use crate::jobs_bridge::Bridge;
use crate::tags_bridge::TAGGABLE;
use crate::{MainWindow, PlayerData};
/// Peaks read per track; the bar draws fewer, one per bar.
const BUCKETS: usize = 600;
/// Peaks read when a waveform is only wanted for the track's length.
const BUCKETS: usize = 1;
/// What ←/→ on the seek bar skip.
const STEP: Duration = Duration::from_secs(5);
/// The cover is scaled down to this (the bar shows it at 48 px, twice that for HiDPI).
const COVER: u32 = 96;
/// Audio or video by MIME type, yet nothing to play: playlists and MIDI (no synthesizer).
const NOT_MEDIA: [&str; 8] = [
"audio/x-mpegurl",
"audio/mpegurl",
"audio/scpls",
"audio/x-scpls",
"audio/x-pn-realaudio",
"video/x-ms-asf",
"audio/mid",
"audio/midi",
];
/// Extensions the MIME table calls video that are mostly source files (TypeScript, Go modules).
const NOT_MEDIA_EXT: [&str; 2] = ["ts", "mod"];
thread_local! {
static PLAYER: RefCell<Weak<PlayerUi>> = const { RefCell::new(Weak::new()) };
@ -34,11 +50,45 @@ fn with(f: impl FnOnce(&PlayerUi)) {
}
}
/// A local audio or video file (a video plays its sound). Formats neither decoder knows get
/// an error toast when played.
pub fn can_play(uri: &Uri) -> bool {
let (Some(path), Some(name)) = (uri.to_path(), uri.file_name()) else {
return false;
};
let ext = path.extension().and_then(OsStr::to_str).unwrap_or_default();
let is = |list: &[&str]| list.iter().any(|e| ext.eq_ignore_ascii_case(e));
if is(&TAGGABLE) {
return true;
}
let mime = mime::mime_type(name, &Kind::File);
(mime.starts_with("audio/") || mime.starts_with("video/"))
&& !NOT_MEDIA.contains(&mime)
&& !is(&NOT_MEDIA_EXT)
}
/// The engine's handle once something was played, so another thread can close the playing
/// file while it rewrites it (`Handle::without`).
pub fn handle() -> Option<Handle> {
let player = PLAYER.with(|w| w.borrow().upgrade())?;
player.player.get().map(Player::handle)
}
/// Tags of `paths` were written: the bar reads the title, artist and cover again when it
/// shows one of them.
pub fn tags_changed(paths: &[PathBuf]) {
with(|p| {
let current = p.track.borrow().as_ref().map(|t| t.path.clone());
if let Some(path) = current.filter(|c| paths.contains(c)) {
p.read_info_later(path);
}
});
}
struct Track {
path: PathBuf,
duration: Duration,
position: Duration,
waveform: Option<Arc<Waveform>>,
ticket: Option<WaveTicket>,
}
@ -55,8 +105,9 @@ pub struct PlayerUi {
bridge: Rc<Bridge>,
/// Started at the first play: it owns a thread and the audio device.
player: OnceCell<Player>,
/// Decodes a whole track for its length when the file doesn't tell it.
waves: Waveforms,
/// The folder's audio files when playing started, for "next track".
/// The folder's playable files when playing started, for "next track".
queue: RefCell<Vec<PathBuf>>,
track: RefCell<Option<Track>>,
playing: Cell<bool>,
@ -83,14 +134,15 @@ impl PlayerUi {
me
}
/// Plays `first`; `queue` is the folder's audio files in the order shown.
/// Plays `first`; `queue` is the folder's playable files in the order shown.
pub fn play(&self, first: PathBuf, queue: Vec<PathBuf>) {
*self.queue.borrow_mut() = queue;
self.open(first, true);
}
/// Screenshots (`TUNAL_PLAY` in main.rs): shows `path` a third of the way through, with
/// its tags and waveform read in place and no audio output.
/// its tags and length read in place and no audio output. `TUNAL_PLAY_STATE=playing`
/// draws it playing (the wave), otherwise paused (flat).
pub fn debug_open(&self, path: PathBuf) {
self.show_track(&path);
if let Some(ui) = self.ui.upgrade() {
@ -106,8 +158,10 @@ impl PlayerUi {
track.position = waveform.duration / 3;
}
self.waveform_ready(&path, Ok(waveform));
self.show_position();
}
let playing = std::env::var("TUNAL_PLAY_STATE").is_ok_and(|s| s == "playing");
self.playing.set(playing);
self.show_position();
}
fn player(&self) -> &Player {
@ -129,7 +183,7 @@ impl PlayerUi {
}
}
/// The bar with the file name until the tags come, an empty waveform until it comes.
/// The bar with the file name until the tags come.
fn show_track(&self, path: &Path) {
if let Some(old) = self.track.borrow_mut().take()
&& let Some(ticket) = old.ticket
@ -140,7 +194,6 @@ impl PlayerUi {
path: path.to_path_buf(),
duration: Duration::ZERO,
position: Duration::ZERO,
waveform: None,
ticket: None,
});
self.playing.set(false);
@ -153,10 +206,10 @@ impl PlayerUi {
cover: Image::default(),
has_cover: false,
time: time_text(Duration::ZERO, Duration::ZERO).into(),
time_template: time_template(Duration::ZERO).into(),
volume: self.volume.get(),
muted: self.muted.get(),
});
ui.set_player_peaks(ModelRc::default());
ui.set_player_position(0.0);
}
}
@ -168,14 +221,21 @@ impl PlayerUi {
if play {
player.play();
}
// Tags and cover.
self.read_info_later(path);
}
/// Tags and cover, read on a thread.
fn read_info_later(&self, path: PathBuf) {
let ui = self.ui.clone();
let p = path.clone();
std::thread::spawn(move || {
let info = read_info(&p);
let _ = ui.upgrade_in_event_loop(move |ui| with(|me| me.show_info(&ui, &p, info)));
let info = read_info(&path);
let _ = ui.upgrade_in_event_loop(move |ui| with(|me| me.show_info(&ui, &path, info)));
});
// The waveform (at once from the cache when this track was shown before).
}
/// The file has no length in its header: decode it all for one (at once from the cache
/// when this track was shown before).
fn measure(&self, path: PathBuf) {
let ui = self.ui.clone();
let p = path.clone();
let ticket = self.waves.request(path, BUCKETS, move |result| {
@ -195,9 +255,7 @@ impl PlayerUi {
return;
}
let mut data = ui.get_player();
if let Some(title) = info.title {
data.title = title.into();
}
data.title = info.title.unwrap_or_else(|| name_of(path)).into();
data.artist = info.artist.unwrap_or_default().into();
data.has_cover = info.cover.is_some();
data.cover = info.cover.map(Image::from_rgba8).unwrap_or_default();
@ -208,29 +266,14 @@ impl PlayerUi {
if !self.is_current(path) {
return;
}
// No waveform (an odd file): the bar keeps its plain track.
if let Ok(waveform) = result {
if let Some(track) = self.track.borrow_mut().as_mut() {
if track.duration.is_zero() {
track.duration = waveform.duration;
}
track.waveform = Some(waveform);
}
self.show_bars();
// No waveform (an odd file): the length stays unknown.
if let Ok(waveform) = result
&& let Some(track) = self.track.borrow_mut().as_mut()
&& track.duration.is_zero()
{
track.duration = waveform.duration;
}
}
/// Downsamples the waveform to the bars the seek bar has room for.
fn show_bars(&self) {
let Some(ui) = self.ui.upgrade() else {
return;
};
let track = self.track.borrow();
let Some(waveform) = track.as_ref().and_then(|t| t.waveform.as_ref()) else {
return;
};
let n = usize::try_from(ui.get_player_bar_count()).unwrap_or(0);
ui.set_player_peaks(ModelRc::new(VecModel::from(bars(waveform, n))));
self.show_position();
}
fn show_position(&self) {
@ -249,6 +292,7 @@ impl PlayerUi {
ui.set_player_position(fraction as f32);
let mut data = ui.get_player();
data.time = time_text(track.position, track.duration).into();
data.time_template = time_template(track.duration).into();
data.playing = self.playing.get();
ui.set_player(data);
}
@ -256,11 +300,20 @@ impl PlayerUi {
fn event(&self, event: Event) {
match event {
Event::Opened { path, duration } => {
if let Some(track) = self.track.borrow_mut().as_mut()
&& track.path == path
&& let Some(duration) = duration
{
track.duration = duration;
let unknown = {
let mut track = self.track.borrow_mut();
match track.as_mut().filter(|t| t.path == path) {
Some(track) => {
if let Some(duration) = duration {
track.duration = duration;
}
track.duration.is_zero() && track.ticket.is_none()
}
None => false,
}
};
if unknown {
self.measure(path);
}
}
Event::State(state) => self.playing.set(state == State::Playing),
@ -289,7 +342,7 @@ impl PlayerUi {
self.show_position();
}
/// The audio file after the current one, when the setting asks for it.
/// The playable file after the current one, when the setting asks for it.
fn next(&self) -> Option<PathBuf> {
if !config::load::<config::Settings>("settings").player_next {
return None;
@ -405,12 +458,6 @@ impl PlayerUi {
me.set_volume(me.volume.get(), !me.muted.get());
}
});
let me = self.me.clone();
ui.on_player_bars_changed(move || {
if let Some(me) = me.upgrade() {
me.show_bars();
}
});
}
}
@ -435,45 +482,40 @@ fn cover(data: &[u8]) -> Option<SharedPixelBuffer<Rgba8Pixel>> {
))
}
/// `n` bar heights 0..1: the loudest peak under each bar, the loudest bar at full height.
fn bars(waveform: &Waveform, n: usize) -> Vec<f32> {
let peaks = &waveform.peaks;
if peaks.is_empty() || n == 0 {
return Vec::new();
}
let amplitude: Vec<f32> = (0..n)
.map(|i| {
let a = i * peaks.len() / n;
let b = ((i + 1) * peaks.len() / n).clamp(a + 1, peaks.len());
peaks[a..b]
.iter()
.map(|(lo, hi)| (hi - lo) / 2.0)
.fold(0.0, f32::max)
})
.collect();
let top = amplitude.iter().copied().fold(0.0, f32::max);
if top <= 0.0 {
return vec![0.0; n];
}
amplitude.into_iter().map(|a| a / top).collect()
}
fn name_of(path: &Path) -> String {
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
}
fn clock(d: Duration, hours: bool) -> String {
let s = d.as_secs();
if hours {
format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
} else {
format!("{}:{:02}", s / 60, s % 60)
}
}
/// "1:23 / 4:56"; hours when the track has them.
fn time_text(position: Duration, duration: Duration) -> String {
let long = duration.as_secs() >= 3600;
let fmt = |d: Duration| {
let s = d.as_secs();
if long {
format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
} else {
format!("{}:{:02}", s / 60, s % 60)
}
let hours = duration.as_secs() >= 3600;
format!("{} / {}", clock(position, hours), clock(duration, hours))
}
/// The widest `time_text` of a track this long, at least "00:00 / 00:00": its digits as 0s
/// (the widest digit in most fonts) and the position as long as the length.
fn time_template(duration: Duration) -> String {
let widest = |s: String| -> String {
s.chars()
.map(|c| if c.is_ascii_digit() { '0' } else { c })
.collect()
};
format!("{} / {}", fmt(position), fmt(duration))
let one = widest(clock(duration, duration.as_secs() >= 3600));
let one = if one.len() < 5 {
"00:00".to_owned()
} else {
one
};
format!("{one} / {one}")
}

View file

@ -22,10 +22,12 @@ use crate::dnd::parse_uri_list;
use crate::jobs_bridge::Bridge;
use crate::{MainWindow, MapRow, ReleaseRow, TagEditorData, TagField, TagLookupData};
/// Extensions lofty reads and writes.
const AUDIO: [&str; 14] = [
"mp3", "flac", "ogg", "oga", "opus", "m4a", "m4b", "mp4", "aac", "wav", "wv", "ape", "mpc",
"aif",
/// Extensions of the formats lofty reads and writes: MPEG audio (ID3v2/APE), FLAC, Ogg
/// Vorbis/Opus/Speex (Vorbis comments), MP4/M4A (atoms), WAV, AIFF, APE, WavPack, Musepack,
/// AAC. Opened, a file goes by its content, so a misnamed one still works.
pub const TAGGABLE: [&str; 25] = [
"mp3", "mp2", "mp1", "flac", "ogg", "oga", "opus", "spx", "m4a", "m4b", "m4p", "m4r", "mp4",
"aac", "wav", "wave", "aif", "aiff", "aifc", "ape", "wv", "mpc", "mp+", "mpp", "3gp",
];
/// Releases the search lists, and how many get a cover (each costs a request).
@ -35,12 +37,12 @@ const COVERED_RELEASES: usize = 6;
const SHOWN_COVER: u32 = 256;
const MAX_COVER_BYTES: u64 = 16 * 1024 * 1024;
/// An audio file we can edit: local, with a known extension.
pub fn is_audio(uri: &Uri) -> bool {
/// An audio file we can edit: local, in a format lofty writes.
pub fn can_tag(uri: &Uri) -> bool {
uri.to_path().is_some_and(|p| {
p.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| AUDIO.iter().any(|a| e.eq_ignore_ascii_case(a)))
.is_some_and(|e| TAGGABLE.iter().any(|a| e.eq_ignore_ascii_case(a)))
})
}
@ -992,10 +994,21 @@ fn write_all(
) {
let sync = std::env::var_os("TUNAL_TAGS_SYNC").is_some();
let weak = ui.clone();
// The playing track is closed while its file is rewritten, then plays on.
let player = crate::player_bridge::handle();
let paths: Vec<PathBuf> = jobs.iter().map(|(p, _)| p.clone()).collect();
let done = move |ui: &MainWindow, failures: Vec<String>| {
crate::player_bridge::tags_changed(&paths);
done(ui, failures);
};
let run = move || {
let mut failures = Vec::new();
for (i, (path, edit)) in jobs.iter().enumerate() {
if let Err(e) = tunal_tags::write(path, edit) {
let written = match &player {
Some(player) => player.without(path, || tunal_tags::write(path, edit)),
None => tunal_tags::write(path, edit),
};
if let Err(e) = written {
failures.push(format!("{}: {e}", name_of(path)));
}
if !sync {

View file

@ -170,11 +170,9 @@ export component MainWindow inherits Window {
// Tags were written to the files; the argument is the message for a toast.
callback tags-written(string);
// The quick player (player_bridge.rs): `player-peaks` has `player-bar-count` bars.
// The quick player (player_bridge.rs).
in property <PlayerData> player;
in property <[float]> player-peaks;
in property <float> player-position;
out property <int> player-bar-count: player-bar.bar-count;
callback player-toggle();
callback player-close();
// Fraction of the track.
@ -183,7 +181,6 @@ export component MainWindow inherits Window {
callback player-step(int);
callback player-volume(float);
callback player-mute();
callback player-bars-changed();
// Properties (properties.rs) and Open with (open.rs).
in property <PropertiesInfo> properties;
@ -655,9 +652,8 @@ export component MainWindow inherits Window {
}
}
player-bar := PlayerBar {
PlayerBar {
data: root.player;
peaks: root.player-peaks;
position: root.player-position;
toggle => {
root.player-toggle();
@ -677,9 +673,6 @@ export component MainWindow inherits Window {
mute => {
root.player-mute();
}
changed bar-count => {
root.player-bars-changed();
}
}
StatusBar {

View file

@ -1,5 +1,6 @@
import { Theme } from "../theme.slint";
import { Motion } from "../motion.slint";
import { Shapes } from "../shapes.slint";
import { Icons } from "../components/icon.slint";
import { IconButton } from "../components/icon-button.slint";
import { StateLayer } from "../components/state-layer.slint";
@ -15,6 +16,8 @@ export struct PlayerData {
has-cover: bool,
// "1:23 / 4:56"
time: string,
// The widest `time` of this track ("00:00 / 00:00"): the label keeps its width.
time-template: string,
// 0..1
volume: float,
muted: bool,
@ -46,27 +49,47 @@ component PlayButton inherits StateLayer {
}
}
// The waveform seek bar: one bar per peak, the played part tinted. A line follows the
// pointer; press and drag scrub, release seeks; ←/→ step. Nothing here animates: the tint
// moves only when the position does (while playing or scrubbing).
// The wavy seek bar: the played part is a sine line that travels while the track plays and
// flattens when it pauses; a gap, the handle at the playhead, another gap, then the flat rest
// of the track with a stop dot at its end. Press or drag anywhere: the handle follows the
// pointer and release seeks; ←/→ step. Paused (or under reduced motion) nothing moves, so
// nothing repaints.
component SeekBar {
// Bar heights 0..1, `bar-count` of them (none while the waveform is being read).
in property <[float]> peaks;
// 0..1
in property <float> position;
in property <bool> playing;
callback seek(float);
callback step(int);
property <length> bar-width: 3px;
property <length> pitch: 5px;
out property <int> bar-count: max(1, floor(root.width / root.pitch));
property <float> shown: touch.pressed ? clamp(touch.mouse-x / root.width, 0, 1) : root.position;
property <length> stroke: Theme.seek-stroke;
property <length> gap: Theme.space-1;
// The wave swells when playback starts and flattens when it stops.
property <length> amplitude: root.playing ? Theme.seek-amplitude : 0;
animate amplitude {
duration: Motion.time(Motion.medium2);
easing: Motion.standard;
}
// One wavelength per period while there is a wave to move.
property <float> phase: root.amplitude > 0 && !Motion.reduced ? Math.mod(animation-tick() / Motion.wave-period, 1) : 0;
// The handle's centre runs from half a handle in to half a handle before the end.
property <length> travel: max(1px, root.width - Theme.seek-handle-width);
property <float> shown: touch.pressed ? clamp((touch.mouse-x - Theme.seek-handle-width / 2) / root.travel, 0, 1) : root.position;
property <length> head: Theme.seek-handle-width / 2 + root.shown * root.travel;
property <length> wave-end: max(0, root.head - Theme.seek-handle-width / 2 - root.gap);
property <length> rest-start: root.head + Theme.seek-handle-width / 2 + root.gap;
property <length> band: 2 * root.amplitude + root.stroke;
property <length> band-top: (root.height - root.band) / 2;
min-width: 120px;
min-width: 64px;
accessible-role: slider;
accessible-label: "Position";
accessible-value: round(root.position * 100) + "%";
// The band's centre line `x` along the wave (`Shapes.wave`'s curve), from the bar's top.
pure function centre(x: length) -> length {
root.band-top + root.amplitude * (1 - Math.sin((x / Theme.seek-wave-length - root.phase) * 360deg)) + root.stroke / 2
}
keys := FocusScope {
key-pressed(event) => {
if event.text == Key.LeftArrow {
@ -81,35 +104,67 @@ component SeekBar {
}
}
// Before the waveform comes: a plain track.
if root.peaks.length == 0: Rectangle {
// The played part, inset by half a stroke at each end for the round caps.
if root.wave-end > root.stroke: Path {
x: root.stroke / 2;
y: root.band-top;
width: root.wave-end - root.stroke;
height: root.band;
viewbox-width: max(1, self.width / 1px);
viewbox-height: root.band / 1px;
commands: Shapes.wave(self.width / 1px, Theme.seek-wave-length / 1px, root.amplitude / 1px, root.stroke / 1px, root.phase);
fill: Theme.primary;
}
if root.wave-end > 0: Rectangle {
x: 0;
y: root.centre(0) - root.stroke / 2;
width: min(root.stroke, root.wave-end);
height: root.stroke;
border-radius: Theme.corner-full(self.height);
background: Theme.primary;
}
if root.wave-end > root.stroke: Rectangle {
x: root.wave-end - root.stroke;
y: root.centre(root.wave-end - root.stroke) - root.stroke / 2;
width: root.stroke;
height: root.stroke;
border-radius: Theme.corner-full(self.height);
background: Theme.primary;
}
// The rest of the track, and the stop dot at its end.
if root.rest-start < root.width: Rectangle {
x: root.rest-start;
y: (root.height - self.height) / 2;
height: Theme.wave-stroke;
border-radius: self.height / 2;
width: root.width - self.x;
height: root.stroke;
border-radius: Theme.corner-full(self.height);
background: Theme.outline-variant;
Rectangle {
x: 0;
width: parent.width * root.shown;
border-radius: parent.border-radius;
background: Theme.primary;
}
}
for peak[i] in root.peaks: Rectangle {
x: i * root.pitch;
width: root.bar-width;
height: max(root.bar-width, peak * root.height);
if root.rest-start < root.width - 2 * root.stroke: Rectangle {
x: root.width - self.width;
y: (root.height - self.height) / 2;
border-radius: self.width / 2;
background: (i + 0.5) / root.peaks.length < root.shown ? Theme.primary : Theme.outline-variant;
width: root.stroke;
height: root.stroke;
border-radius: Theme.corner-full(self.height);
background: Theme.primary;
}
if touch.has-hover || touch.pressed: Rectangle {
x: clamp(touch.mouse-x, 0, root.width) - self.width / 2;
width: Theme.focus-ring-width;
border-radius: self.width / 2;
background: Theme.on-surface;
// The handle: taller on hover and focus, thinner while held.
Rectangle {
x: root.head - self.width / 2;
y: (root.height - self.height) / 2;
width: touch.pressed ? Theme.seek-handle-width / 2 : Theme.seek-handle-width;
height: touch.has-hover || touch.pressed || keys.has-focus ? Theme.seek-handle-height + Theme.space-1 : Theme.seek-handle-height;
border-radius: Theme.corner-full(self.width);
background: Theme.primary;
animate width, height {
duration: Motion.time(Motion.short3);
easing: Motion.standard;
}
}
// Keyboard focus: a ring round the bar.
@ -128,7 +183,7 @@ component SeekBar {
keys.focus();
}
if event.kind == PointerEventKind.up && event.button == PointerEventButton.left {
root.seek(clamp(self.mouse-x / root.width, 0, 1));
root.seek(root.shown);
}
}
}
@ -191,11 +246,11 @@ component VolumeBar {
// The quick player under the panes. It slides up from the status bar when a track opens
// and back down when closed: occasional, so it moves (height, emphasized decelerate).
// Narrow, the seek bar shrinks first; then the parts go in order: the volume slider (the
// mute button stays), half the title width, the cover and artist line, the mute button.
export component PlayerBar inherits Rectangle {
in property <PlayerData> data;
in property <[float]> peaks;
in property <float> position;
out property <int> bar-count: seek.bar-count;
callback toggle();
callback close();
callback seek(float);
@ -205,6 +260,27 @@ export component PlayerBar inherits Rectangle {
property <length> card-height: 64px;
property <length> full: root.card-height + Theme.space-2;
property <length> card-width: root.width - 2 * Theme.space-3;
property <length> gap: Theme.space-3;
property <length> cover-size: 48px;
property <length> button: 40px;
property <length> play-size: 48px;
property <length> volume-width: 72px;
property <length> info-wide: 180px;
property <length> info-narrow: 120px;
property <length> info-title: 96px;
// The time label's width: its widest text, so the digits never push the row.
property <length> time-width: time-probe.preferred-width;
// Padding, play button, time, close button and their gaps: always there.
property <length> base: Theme.space-2 + Theme.space-3 + root.play-size + root.time-width + root.button + 3 * root.gap;
property <length> with-mute: root.base + root.button + root.gap;
property <length> with-cover: root.with-mute + root.cover-size + root.gap;
// 0 everything, 1 no volume slider, 2 narrower title, 3 no cover or artist, 4 no mute.
property <int> tier: root.card-width >= root.with-cover + root.info-wide + root.volume-width + 2 * root.gap + 160px ? 0
: root.card-width >= root.with-cover + root.info-wide + root.gap + 160px ? 1
: root.card-width >= root.with-cover + root.info-narrow + root.gap + 120px ? 2
: root.card-width >= root.with-mute + root.info-title + root.gap + 80px ? 3
: 4;
height: root.data.open ? root.full : 0;
clip: true;
@ -216,22 +292,29 @@ export component PlayerBar inherits Rectangle {
// Anchored to the bottom: it rises out from behind the status bar.
Rectangle {
x: Theme.space-3;
width: root.width - 2 * Theme.space-3;
width: root.card-width;
height: root.card-height;
y: root.height - root.full + Theme.space-2;
border-radius: Theme.corner-full(self.height);
background: Theme.surface-container-high;
time-probe := Text {
visible: false;
text: root.data.time-template;
font-size: Theme.label-medium.size;
font-weight: Theme.label-medium.weight;
}
HorizontalLayout {
padding-left: Theme.space-2;
padding-right: Theme.space-3;
spacing: Theme.space-3;
spacing: root.gap;
alignment: stretch;
VerticalLayout {
if root.tier < 3: VerticalLayout {
alignment: center;
Shape {
size: 48px;
size: root.cover-size;
shape: ShapeKind.cookie9;
fill: Theme.tertiary-container;
glyph: Icons.music-note;
@ -241,9 +324,11 @@ export component PlayerBar inherits Rectangle {
}
}
// The tier-3 title-only column gets the cover's padding back on its left.
VerticalLayout {
alignment: center;
width: 180px;
padding-left: root.tier < 3 ? 0 : Theme.space-2;
width: root.tier < 2 ? root.info-wide : root.tier == 2 ? root.info-narrow : root.info-title;
Text {
text: root.data.title;
color: Theme.on-surface;
@ -251,7 +336,7 @@ export component PlayerBar inherits Rectangle {
font-weight: Theme.label-large.weight;
overflow: elide;
}
Text {
if root.tier < 3: Text {
text: root.data.artist;
color: Theme.on-surface-variant;
font-size: Theme.body-small.size;
@ -271,10 +356,10 @@ export component PlayerBar inherits Rectangle {
}
}
seek := SeekBar {
SeekBar {
horizontal-stretch: 1;
peaks: root.peaks;
position: root.position;
playing: root.data.playing;
seek(f) => {
root.seek(f);
}
@ -284,14 +369,16 @@ export component PlayerBar inherits Rectangle {
}
Text {
width: root.time-width;
text: root.data.time;
color: Theme.on-surface-variant;
font-size: Theme.label-medium.size;
font-weight: Theme.label-medium.weight;
horizontal-alignment: right;
vertical-alignment: center;
}
VerticalLayout {
if root.tier < 4: VerticalLayout {
alignment: center;
IconButton {
icon: root.data.muted ? Icons.volume-off : Icons.volume-up;
@ -302,7 +389,7 @@ export component PlayerBar inherits Rectangle {
}
}
VolumeBar {
if root.tier == 0: VolumeBar {
value: root.data.volume;
muted: root.data.muted;
changed-value(v) => {

View file

@ -66,6 +66,13 @@ export global Theme {
out property <length> wave-stroke: 3px;
out property <length> wave-amplitude: 2px;
out property <length> wave-length: 20px;
// The player's wavy seek bar: stroke, wave height above its centre, one wavelength, and
// the handle at the playhead (a pill).
out property <length> seek-stroke: 4px;
out property <length> seek-amplitude: 3px;
out property <length> seek-wave-length: 32px;
out property <length> seek-handle-width: 4px;
out property <length> seek-handle-height: 20px;
// Fully rounded ends for a shape of the given height.
public pure function corner-full(height: length) -> length {
height / 2

View file

@ -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.