Compare commits

...
2 Commits
Author SHA1 Message Date
Ansho Rei a005c3207a fix: ignore the controller while another window is in front
remus reads the controller from the device, whichever window has focus,
so presses meant for a game in front also skipped tracks and paused in
remus. It now follows winit's focus events, through slint's
unstable-winit-030 feature since Slint does not expose window activation
itself, and drops controller presses while the window is not in front.
It assumes focus until told otherwise, so a window manager that never
reports focus keeps the controller working.
2026-11-04 20:51:33 +01:00
Ansho Rei 6997e7cd93 fix: show the picture in the playing track's file on the now-playing screen
Nextcloud Music gives every song of an album the album's cover id, so
tracks with their own art all showed the album cover. The player now
reads the picture embedded in each file it decodes and reports it once
per track, or reports that there is none. The now-playing art, backdrop
and palette use it, and wait for that answer so they do not show the
album cover first and then change. Lists and the queue keep the
server's cover.

Pictures are read where each file's decoder hands on its stream:
further down, a file without a picture still carries the previous
file's tags after a gapless switch.
2026-11-04 20:22:03 +01:00
7 changed files with 323 additions and 41 deletions
+12
View File
@@ -2,6 +2,18 @@
One section per version, newest first.
## v0.8.4 (2026-11-04)
### Bug fixes
- While another app or a game is in front, the controller no longer also controls remus. Music keeps playing in the background, and media keys still work.
## v0.8.3 (2026-11-04)
### Bug fixes
- The now-playing cover, its background and the album art colours use the picture embedded in the playing track's file when it has one. Nextcloud Music gives every song of an album the album's cover, so tracks with their own art all showed the same one. Lists and the queue still show the server's cover.
## v0.8.2 (2026-11-04)
### Bug fixes
Generated
+2 -1
View File
@@ -4385,7 +4385,7 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "remus"
version = "0.8.2"
version = "0.8.4"
dependencies = [
"anyhow",
"directories",
@@ -4907,6 +4907,7 @@ dependencies = [
"const-field-offset",
"i-slint-backend-linuxkms",
"i-slint-backend-selector",
"i-slint-backend-winit",
"i-slint-common",
"i-slint-core",
"i-slint-core-macros",
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "remus"
version = "0.8.2"
version = "0.8.4"
edition = "2024"
license = "MIT"
@@ -18,7 +18,7 @@ md5 = "0.8.1"
reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
slint = "1.18.1"
slint = { version = "1.18.1", features = ["unstable-winit-030"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "sync", "macros", "time"] }
toml = "1.1.8"
zbus = { version = "5.19.0", default-features = false, features = ["tokio"] }
@@ -20,6 +20,8 @@
</supports>
<content_rating type="oars-1.1"/>
<releases>
<release version="0.8.4" date="2026-11-04"/>
<release version="0.8.3" date="2026-11-04"/>
<release version="0.8.2" date="2026-11-04"/>
<release version="0.8.1" date="2026-11-04"/>
<release version="0.8.0" date="2026-11-04"/>
+117 -31
View File
@@ -211,6 +211,10 @@ struct Page {
type CoverKey = (String, u32);
/// Prefix of the cover id for the picture embedded in a song's file, followed
/// by the song id. Read from the stream, never asked of the server.
const EMBEDDED: &str = "remus-embedded:";
struct Covers {
images: LruCache<CoverKey, Image>,
/// Per cover id, whatever size it was decoded at. None for a cover with
@@ -220,6 +224,11 @@ struct Covers {
prints: LruCache<CoverKey, u64>,
pending: HashSet<CoverKey>,
failed: HashSet<CoverKey>,
/// Per song id, the picture embedded in its file as the player read it,
/// None for a file without one. Some servers, such as Nextcloud Music,
/// give every song the album's cover id, so this is the only place a
/// track's own cover can come from.
embedded: LruCache<String, Option<Arc<[u8]>>>,
limit: Arc<Semaphore>,
/// Per server, under `root`, since ids are only unique within a server.
dir: Option<PathBuf>,
@@ -280,12 +289,19 @@ pub struct App {
volume_save_timer: Timer,
/// Keyboard keys or the buttons of the controller used last.
prompts: Prompts,
/// Whether the window has focus. True until the windowing system says
/// otherwise, so a system that never says still gets controller input.
window_active: bool,
/// Decoded hint icons, so a selection move does not parse SVG again.
icons: RefCell<HashMap<(Prompts, Control), Vec<Image>>>,
settings: Settings,
fade: Fade,
/// The now-playing art on screen, `None` when nothing is playing.
art_shown: Option<ShownArt>,
/// The playing track started and the player has not yet said whether its
/// file has a picture: the art and palette wait, so they do not show the
/// album cover and then change again.
art_waiting: bool,
/// Runs while the cover turns away; the new art goes up when it fires.
flip_timer: Timer,
}
@@ -343,6 +359,7 @@ impl App {
prints: LruCache::new(NonZeroUsize::new(400).unwrap()),
pending: HashSet::new(),
failed: HashSet::new(),
embedded: LruCache::new(NonZeroUsize::new(16).unwrap()),
limit: Arc::new(Semaphore::new(6)),
dir: None,
root: dir,
@@ -366,8 +383,10 @@ impl App {
volume_timer: Timer::default(),
volume_save_timer: Timer::default(),
art_shown: None,
art_waiting: false,
flip_timer: Timer::default(),
prompts: Prompts::Keyboard,
window_active: true,
icons: RefCell::default(),
settings: config::load_settings(),
fade: Fade {
@@ -561,6 +580,7 @@ impl App {
self.covers.prints.clear();
self.covers.pending.clear();
self.covers.failed.clear();
self.covers.embedded.clear();
for stack in &mut self.stacks {
stack.clear();
}
@@ -685,10 +705,30 @@ impl App {
/// A button pressed on a controller of this family.
pub fn pad_action(&mut self, a: Action, family: Family) {
// Meant for whatever is in front: a game, Steam, another app.
if !self.window_active {
return;
}
self.set_prompts(Prompts::Pad(family));
self.action(a);
}
/// The window gained or lost focus. Only the controller cares: keys only
/// arrive while it has focus anyway.
pub fn set_window_active(&mut self, active: bool) {
if active != self.window_active {
log::info!(
"window {}",
if active {
"in front, controller on"
} else {
"in the background, controller off"
}
);
self.window_active = active;
}
}
/// A controller connected (its family) or the last one disconnected.
pub fn pad_present(&mut self, family: Option<Family>) {
self.set_prompts(family.map_or(Prompts::Keyboard, Prompts::Pad));
@@ -1235,11 +1275,10 @@ impl App {
if !self.settings.album_art_colours {
return Some(Palette::brand());
}
let Some(id) = self
.current
.and_then(|i| self.queue.get(i))
.and_then(|s| s.cover_art.clone())
else {
if self.art_waiting {
return None;
}
let Some(id) = self.playing_cover_id() else {
return Some(Palette::brand());
};
match self.covers.tones.get(&id) {
@@ -1801,6 +1840,20 @@ impl App {
if self.covers.pending.contains(&key) || self.covers.failed.contains(&key) {
return None;
}
let generation = self.covers.generation;
if let Some(song) = id.strip_prefix(EMBEDDED) {
let bytes = self.covers.embedded.get(song).cloned().flatten()?;
self.covers.pending.insert(key.clone());
self.spawn(
async move { tokio::task::spawn_blocking(move || decode_cover(&bytes, px)).await? },
move |app, r| {
if app.covers.generation == generation {
app.cover_loaded(key, r);
}
},
);
return None;
}
let client = self.client.clone()?;
self.covers.pending.insert(key.clone());
let limit = self.covers.limit.clone();
@@ -1810,7 +1863,6 @@ impl App {
.as_ref()
.map(|d| d.join(format!("{}_{px}", sanitize(id))));
let id = id.to_string();
let generation = self.covers.generation;
self.spawn(
async move {
let _permit = limit.acquire_owned().await?;
@@ -1853,11 +1905,11 @@ impl App {
Err(e) => {
log::debug!("cover {} failed: {e:#}", key.0);
// The playing track's art may be waiting on this to flip.
let playing = self
.current
.and_then(|i| self.queue.get(i))
.and_then(|s| s.cover_art.as_deref())
== Some(key.0.as_str());
let playing = self.playing_cover_id().as_deref() == Some(key.0.as_str());
// A picture in the file that will not decode: the album cover then.
if let Some(song) = key.0.strip_prefix(EMBEDDED) {
self.covers.embedded.put(song.to_string(), None);
}
self.covers.failed.insert(key);
if playing {
self.render_player();
@@ -1897,12 +1949,7 @@ impl App {
{
self.render_page_header();
}
if self
.current
.and_then(|i| self.queue.get(i))
.and_then(|s| s.cover_art.as_deref())
== Some(id)
{
if self.playing_cover_id().as_deref() == Some(id) {
self.render_player();
}
let (qlo, qhi) = self.queue_range;
@@ -2032,6 +2079,8 @@ impl App {
// new play: another queue started there, or the track replayed.
let t = t.filter(|&i| i < self.queue.len());
self.current = t;
// A file already read needs no wait: replayed, or skipped back to.
self.art_waiting = t.is_some_and(|i| !self.covers.embedded.contains(&self.queue[i].id));
self.position = 0.0;
self.scrobbled = false;
if let Some((i, _)) = self.restoring.take()
@@ -2055,6 +2104,29 @@ impl App {
self.sync_queue(true);
self.save_queue();
}
PlayerEvent::Art(i, bytes) => {
if self.current != Some(i) {
return;
}
let Some(song) = self.queue.get(i).map(|s| s.id.clone()) else {
return;
};
log::debug!(
"track {song}: {}",
if bytes.is_some() {
"picture in the file"
} else {
"no picture in the file"
}
);
// A late picture does not undo one already read.
if bytes.is_some() || !self.covers.embedded.contains(&song) {
self.covers.embedded.put(song, bytes.map(Arc::from));
}
self.art_waiting = false;
self.render_player();
return;
}
}
self.sync_inhibit();
self.sync_mpris();
@@ -2247,8 +2319,9 @@ impl App {
/// from the one on screen. While a changed track's cover loads, the old one
/// stays up: the load ends in a render either way, and decides then.
fn update_art(&mut self, s: &Song) {
if self.flip_timer.running() {
// Mid-turn: the midpoint puts up whatever is current then.
if self.flip_timer.running() || self.art_waiting {
// Mid-turn: the midpoint puts up whatever is current then. Waiting
// on the player: its answer ends in a render.
return;
}
let Some(shown) = &self.art_shown else {
@@ -2256,7 +2329,7 @@ impl App {
self.render_art(s);
return;
};
if shown.id == s.cover_art || self.screen != Screen::NowPlaying {
if shown.id == self.cover_id(s) || self.screen != Screen::NowPlaying {
self.render_art(s);
return;
}
@@ -2275,10 +2348,10 @@ impl App {
/// The picture the song's art will show: `Some(None)` for the placeholder,
/// `None` while its cover is still loading.
fn art_print(&mut self, s: &Song) -> Option<Option<u64>> {
let Some(id) = s.cover_art.as_deref() else {
let Some(id) = self.cover_id(s) else {
return Some(None);
};
let key: CoverKey = (id.to_string(), self.now_playing_px());
let key: CoverKey = (id, self.now_playing_px());
if let Some(p) = self.covers.prints.get(&key) {
return Some(Some(*p));
}
@@ -2286,7 +2359,7 @@ impl App {
return Some(None);
}
// Starts the load if it is not under way.
self.cover(id, key.1);
self.cover(&key.0, key.1);
None
}
@@ -2297,7 +2370,7 @@ impl App {
return;
}
let next = self.current.and_then(|i| self.queue.get(i + 1));
if let Some(id) = next.and_then(|s| s.cover_art.clone()) {
if let Some(id) = next.and_then(|s| self.cover_id(s)) {
let px = self.now_playing_px();
self.cover(&id, px);
}
@@ -2306,9 +2379,9 @@ impl App {
/// Puts the song's cover, or its letter placeholder, on screen.
fn render_art(&mut self, s: &Song) {
let px = self.now_playing_px();
let cover = s.cover_art.as_deref().and_then(|id| self.cover(id, px));
let print = s
.cover_art
let id = self.cover_id(s);
let cover = id.as_deref().and_then(|id| self.cover(id, px));
let print = id
.as_ref()
.and_then(|id| self.covers.prints.get(&(id.clone(), px)).copied())
.filter(|_| cover.is_some());
@@ -2317,10 +2390,23 @@ impl App {
self.ui.set_np_tint(tint(name));
self.ui.set_np_has_cover(cover.is_some());
self.ui.set_np_cover(cover.unwrap_or_default());
self.art_shown = Some(ShownArt {
id: s.cover_art.clone(),
print,
});
self.art_shown = Some(ShownArt { id, print });
}
/// The cover id the now-playing art, backdrop and palette use for `s`:
/// the picture in its file once the player has read one, else the
/// server's cover. Lists keep the server's cover.
fn cover_id(&self, s: &Song) -> Option<String> {
match self.covers.embedded.peek(&s.id) {
Some(Some(_)) => Some(format!("{EMBEDDED}{}", s.id)),
_ => s.cover_art.clone(),
}
}
fn playing_cover_id(&self) -> Option<String> {
self.current
.and_then(|i| self.queue.get(i))
.and_then(|s| self.cover_id(s))
}
/// The cover is edge-on: swap in the current track's art and turn it back.
+12
View File
@@ -28,6 +28,18 @@ fn main() -> anyhow::Result<()> {
let ui = AppWindow::new()?;
ui.set_version(env!("CARGO_PKG_VERSION").into());
app::install(&ui, rt.handle().clone());
// The controller is read from the device, whichever window is in front, so
// the app needs to know when another one is, to leave the presses to it.
{
use slint::winit_030::{EventResult, WinitWindowAccessor, winit::event::WindowEvent};
ui.window().on_winit_window_event(|_, event| {
if let WindowEvent::Focused(focused) = *event {
log::debug!("window focused: {focused}");
app::with_app(move |app| app.set_window_active(focused));
}
EventResult::Propagate
});
}
input::spawn_gamepad(|ev| {
let _ = slint::invoke_from_event_loop(move || {
app::with_app(move |app| match ev {
+176 -7
View File
@@ -2,6 +2,7 @@
//! track can be handed to playbin in `about-to-finish`, which keeps playback
//! gapless.
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread::JoinHandle;
@@ -11,13 +12,17 @@ use anyhow::{Context, Result};
use gstreamer as gst;
use gstreamer::prelude::*;
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
pub enum PlayerEvent {
Position(f64),
Duration(f64),
Paused(bool),
/// Index into the queue, None when playback has stopped.
Track(Option<usize>),
/// The picture embedded in a track's file, or None once it is clear the
/// file has none. Sent once per track started, after its `Track`. A
/// picture that turns up late is still sent, after the None.
Art(usize, Option<Vec<u8>>),
}
#[derive(Default)]
@@ -33,14 +38,21 @@ struct Queue {
seek_to: Option<f64>,
}
/// Pictures found in the files being decoded, by URI.
type Pictures = Arc<Mutex<HashMap<String, Vec<u8>>>>;
pub struct Player {
playbin: gst::Element,
queue: Arc<Mutex<Queue>>,
pictures: Pictures,
stop: Arc<AtomicBool>,
bus_thread: Option<JoinHandle<()>>,
}
const TICK: Duration = Duration::from_millis(250);
/// How long after a track starts its tags can still bring a picture. Tags
/// come ahead of the audio, so this is mostly a slow server's margin.
const ART_WAIT: Duration = Duration::from_millis(600);
impl Player {
pub fn spawn(on_event: impl Fn(PlayerEvent) + Send + 'static) -> Result<Player> {
@@ -71,15 +83,19 @@ impl Player {
None
});
let pictures = Pictures::default();
watch_pictures(&playbin, &pictures);
let stop = Arc::new(AtomicBool::new(false));
let bus_thread = std::thread::Builder::new().name("gst-bus".into()).spawn({
let (playbin, queue, stop) = (playbin.clone(), queue.clone(), stop.clone());
move || watch_bus(&playbin, &queue, &stop, &on_event)
let (playbin, queue, pictures, stop) = (playbin.clone(), queue.clone(), pictures.clone(), stop.clone());
move || watch_bus(&playbin, &queue, &pictures, &stop, &on_event)
})?;
Ok(Player {
playbin,
queue,
pictures,
stop,
bus_thread: Some(bus_thread),
})
@@ -147,6 +163,7 @@ impl Player {
/// to Null flushes the bus, so nothing from the old track reports later.
pub fn stop(&self) {
*lock(&self.queue) = Queue::default();
lock(&self.pictures).clear();
let _ = self.playbin.set_state(gst::State::Null);
}
@@ -213,8 +230,53 @@ impl Drop for Player {
}
}
fn lock(q: &Mutex<Queue>) -> MutexGuard<'_, Queue> {
q.lock().unwrap_or_else(|e| e.into_inner())
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// Records the picture in each file playbin decodes, keyed by its URI. Read
/// where each file's decoder hands on its stream, because further down the
/// tags of a file without a picture still carry the previous file's, once
/// playback moves on gaplessly.
fn watch_pictures(playbin: &gst::Element, pictures: &Pictures) {
let Some(bin) = playbin.downcast_ref::<gst::Bin>() else {
return;
};
let pictures = pictures.clone();
bin.connect_deep_element_added(move |_, _, element| {
let decoder = element
.factory()
.is_some_and(|f| matches!(f.name().as_str(), "uridecodebin" | "uridecodebin3"));
// playbin adds the same decoder again for later tracks.
// SAFETY: the key is only ever set to a bool, here.
if !decoder || unsafe { element.data::<bool>("remus-pictures") }.is_some() {
return;
}
unsafe { element.set_data("remus-pictures", true) };
let pictures = pictures.clone();
element.connect_pad_added(move |decoder, pad| {
let decoder = decoder.downgrade();
let pictures = pictures.clone();
pad.add_probe(gst::PadProbeType::EVENT_DOWNSTREAM, move |_, info| {
if let Some(gst::PadProbeData::Event(ev)) = &info.data
&& let gst::EventView::Tag(t) = ev.view()
&& let Some(bytes) = embedded_picture(t.tag())
&& let Some(uri) = decoder.upgrade().and_then(|d| d.property::<Option<String>>("uri"))
{
lock(&pictures).entry(uri).or_insert(bytes);
}
gst::PadProbeReturn::Ok
});
});
});
}
/// The track whose picture is still being looked for.
struct ArtWait {
index: usize,
since: Instant,
/// Already reported as without a picture; one turning up later is still sent.
told_none: bool,
}
fn start(playbin: &gst::Element, url: &str) {
@@ -246,7 +308,13 @@ fn seek_to(playbin: &gst::Element, seconds: f64) {
}
}
fn watch_bus(playbin: &gst::Element, queue: &Mutex<Queue>, stop: &AtomicBool, emit: &dyn Fn(PlayerEvent)) {
fn watch_bus(
playbin: &gst::Element,
queue: &Mutex<Queue>,
pictures: &Pictures,
stop: &AtomicBool,
emit: &dyn Fn(PlayerEvent),
) {
let Some(bus) = playbin.bus() else { return };
let mut last_tick = Instant::now();
let mut duration = 0.0;
@@ -259,8 +327,12 @@ fn watch_bus(playbin: &gst::Element, queue: &Mutex<Queue>, stop: &AtomicBool, em
last_track = Some(t);
emit(PlayerEvent::Track(t));
emit(PlayerEvent::Position(0.0));
true
} else {
false
}
};
let mut art_wait: Option<ArtWait> = None;
while !stop.load(Ordering::Relaxed) {
if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(TICK.as_millis() as u64)) {
use gst::MessageView;
@@ -278,7 +350,24 @@ fn watch_bus(playbin: &gst::Element, queue: &Mutex<Queue>, stop: &AtomicBool, em
(q.current, started)
};
duration = 0.0;
report_track(current, started);
if report_track(current, started) {
art_wait = current.map(|index| ArtWait {
index,
since: Instant::now(),
told_none: false,
});
// Keep only what this track and the next may still need.
let keep: Vec<String> = {
let q = lock(queue);
current
.into_iter()
.flat_map(|i| q.urls.get(i..=i + 1))
.flatten()
.cloned()
.collect()
};
lock(pictures).retain(|uri, _| keep.contains(uri));
}
}
MessageView::StateChanged(s) if s.src() == Some(playbin.upcast_ref()) => match s.current() {
gst::State::Playing => emit(PlayerEvent::Paused(false)),
@@ -303,6 +392,7 @@ fn watch_bus(playbin: &gst::Element, queue: &Mutex<Queue>, stop: &AtomicBool, em
}
let _ = playbin.set_state(gst::State::Ready);
report_track(None, false);
art_wait = None;
}
// A failing source posts several errors. Once the first has moved
// on to the next track, the source is out of playbin and the rest
@@ -336,11 +426,23 @@ fn watch_bus(playbin: &gst::Element, queue: &Mutex<Queue>, stop: &AtomicBool, em
} else {
let _ = playbin.set_state(gst::State::Ready);
report_track(None, false);
art_wait = None;
}
}
_ => {}
}
}
if let Some(w) = &mut art_wait {
let url = lock(queue).urls.get(w.index).cloned();
let picture = url.and_then(|u| lock(pictures).get(&u).cloned());
if picture.is_some() {
emit(PlayerEvent::Art(w.index, picture));
art_wait = None;
} else if !w.told_none && w.since.elapsed() >= ART_WAIT {
w.told_none = true;
emit(PlayerEvent::Art(w.index, None));
}
}
if last_tick.elapsed() >= TICK {
last_tick = Instant::now();
if playbin.current_state() == gst::State::Playing {
@@ -358,6 +460,22 @@ fn watch_bus(playbin: &gst::Element, queue: &Mutex<Queue>, stop: &AtomicBool, em
}
}
/// The front cover among the pictures in `tags`, else the first picture.
fn embedded_picture(tags: &gst::TagListRef) -> Option<Vec<u8>> {
// GST_TAG_IMAGE_TYPE_FRONT_COVER in gst-tag's GstTagImageType.
const FRONT_COVER: i32 = 1;
let is_front = |s: &gst::Sample| {
s.info()
.and_then(|i| i.value("image-type").ok())
.and_then(|v| gst::glib::EnumValue::from_value(v))
.is_some_and(|(_, v)| v.value() == FRONT_COVER)
};
let pictures: Vec<gst::Sample> = tags.iter_tag::<gst::tags::Image>().map(|v| v.get()).collect();
let sample = pictures.iter().find(|s| is_front(s)).or(pictures.first())?;
let map = sample.buffer()?.map_readable().ok()?;
Some(map.as_slice().to_vec())
}
/// Removes the query string from any URL in `text`. Stream URLs carry the
/// Subsonic auth token, and GStreamer's HTTP errors quote the URL.
fn strip_queries(text: &str) -> String {
@@ -425,6 +543,57 @@ mod tests {
format!("file://{}", path.display())
}
/// Puts an ID3v2.3 tag holding `picture` as the front cover before the
/// file at `uri`, as a tagged MP3 would carry it.
fn with_id3_picture(uri: &str, picture: &[u8]) {
let path = uri.strip_prefix("file://").unwrap();
let mut body = vec![0u8]; // Latin-1 text
body.extend_from_slice(b"image/png\0");
body.push(3); // front cover
body.push(0); // empty description
body.extend_from_slice(picture);
let mut frame = b"APIC".to_vec();
frame.extend_from_slice(&(body.len() as u32).to_be_bytes());
frame.extend_from_slice(&[0, 0]);
frame.extend_from_slice(&body);
let n = frame.len() as u32;
let syncsafe = [(n >> 21) & 0x7f, (n >> 14) & 0x7f, (n >> 7) & 0x7f, n & 0x7f].map(|b| b as u8);
let mut tagged = b"ID3\x03\x00\x00".to_vec();
tagged.extend_from_slice(&syncsafe);
tagged.extend_from_slice(&frame);
tagged.extend_from_slice(&std::fs::read(path).unwrap());
std::fs::write(path, tagged).unwrap();
}
#[test]
fn reports_the_picture_in_each_file() {
// SAFETY: set before any thread reads the environment in this test.
unsafe { std::env::set_var("REMUS_AUDIO_SINK", "fakesink") };
let dir = std::env::temp_dir().join(format!("remus-player-art-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let urls = vec![silent_wav(&dir, "a.wav", 1.0), silent_wav(&dir, "b.wav", 1.0)];
let mut png = Vec::new();
image::RgbImage::from_pixel(4, 4, image::Rgb([200, 30, 30]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
with_id3_picture(&urls[0], &png);
let (tx, rx) = mpsc::channel();
let player = Player::spawn(move |ev| {
if let PlayerEvent::Art(i, bytes) = ev {
let _ = tx.send((i, bytes));
}
})
.unwrap();
player.play_list(&urls, 0);
let first = rx.recv_timeout(Duration::from_secs(5));
let second = rx.recv_timeout(Duration::from_secs(5));
drop(player);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(first, Ok((0, Some(png))), "the tagged file's picture");
assert_eq!(second, Ok((1, None)), "the plain file has none");
}
#[test]
fn plays_a_queue_through_to_the_end() {
// SAFETY: set before any thread reads the environment in this test.