Files
furumi-tui/integrations/opendeck/src/artwork.rs
T

269 lines
8.3 KiB
Rust

//! Demand-driven cover state. A request is scoped to a playback generation,
//! including A → B → A, and can never revive an image from an older request.
use std::time::{Duration, Instant};
use base64::Engine as _;
use furumi_control_protocol::Snapshot;
use image::RgbImage;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(35);
pub const KEY_PIXELS: u32 = 96;
// A 6 mm gap corresponds to 41 pixels on a 14 mm, 96-pixel key.
pub const GAP_PX: u32 = 41;
pub const KEY_STRIDE: u32 = KEY_PIXELS + GAP_PX;
pub const PHYSICAL_MOSAIC_SIZE: u32 = KEY_PIXELS * 2 + GAP_PX;
// Trim slightly less art than the physical 6 mm spacers: about 5 mm per axis.
pub const ART_GAP_PX: u32 = 34;
pub const ART_STRIDE: u32 = KEY_PIXELS + ART_GAP_PX;
pub const MOSAIC_SIZE: u32 = KEY_PIXELS * 2 + ART_GAP_PX;
/// Both cover sizes share the lifetime of a single artwork response.
pub struct PreparedArt {
small: RgbImage,
square: RgbImage,
}
pub struct CoverReply<T> {
pub request_id: String,
pub artwork_id: String,
pub image: T,
}
impl CoverReply<String> {
/// Decode and resize on the image worker while the keys continue to accept input.
pub fn prepare(self) -> CoverReply<Option<PreparedArt>> {
let image = decode_png(&self.image).map(PreparedArt::new);
CoverReply {
request_id: self.request_id,
artwork_id: self.artwork_id,
image,
}
}
}
fn decode_png(encoded: &str) -> Option<RgbImage> {
let bytes = base64::engine::general_purpose::STANDARD
.decode(encoded)
.ok()?;
let mut reader =
image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(2048);
limits.max_image_height = Some(2048);
limits.max_alloc = Some(32 * 1024 * 1024);
reader.limits(limits);
reader.decode().ok().map(|image| image.into_rgb8())
}
impl PreparedArt {
pub fn new(image: RgbImage) -> Self {
let side = image.width().min(image.height());
let square = image::imageops::crop_imm(
&image,
(image.width() - side) / 2,
(image.height() - side) / 2,
side,
side,
);
Self {
small: image::imageops::resize(
&*square,
KEY_PIXELS,
KEY_PIXELS,
image::imageops::FilterType::Lanczos3,
),
square: image::imageops::resize(
&*square,
MOSAIC_SIZE,
MOSAIC_SIZE,
image::imageops::FilterType::Lanczos3,
),
}
}
pub fn small(&self) -> &RgbImage {
&self.small
}
pub fn square(&self) -> &RgbImage {
&self.square
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Identity {
track_key: String,
artwork_id: Option<String>,
}
#[derive(Debug)]
struct Pending {
request_id: String,
artwork_id: String,
generation: u64,
started: Instant,
}
#[derive(Default)]
pub struct Artwork {
identity: Option<Identity>,
generation: u64,
pending: Option<Pending>,
terminal: bool,
image: Option<PreparedArt>,
}
impl Artwork {
pub fn observe(&mut self, snapshot: Option<&Snapshot>) {
let identity = snapshot
.and_then(|s| s.track.as_ref())
.map(|track| Identity {
track_key: track.key.clone(),
artwork_id: track.artwork_id.clone(),
});
if identity != self.identity {
self.identity = identity;
self.generation = self.generation.wrapping_add(1);
self.pending = None;
self.terminal = false;
self.image = None;
}
}
pub fn needed(&self, visible: bool) -> Option<String> {
if !visible || self.terminal || self.pending.is_some() {
return None;
}
self.identity.as_ref()?.artwork_id.clone()
}
pub fn begin(&mut self, request_id: String, artwork_id: String, now: Instant) {
self.pending = Some(Pending {
request_id,
artwork_id,
generation: self.generation,
started: now,
});
}
pub fn matches(&self, id: &str, artwork_id: &str) -> bool {
self.pending.as_ref().is_some_and(|p| {
p.request_id == id && p.artwork_id == artwork_id && p.generation == self.generation
})
}
pub fn complete(&mut self, id: &str, artwork_id: &str, image: Option<PreparedArt>) {
if !self.matches(id, artwork_id) {
return;
}
self.pending = None;
self.terminal = true;
self.image = image;
}
pub fn reject(&mut self, id: &str) {
if self.pending.as_ref().is_some_and(|p| p.request_id == id) {
self.pending = None;
self.terminal = true;
self.image = None;
}
}
pub fn expire(&mut self, now: Instant) {
if self
.pending
.as_ref()
.is_some_and(|p| now.saturating_duration_since(p.started) >= REQUEST_TIMEOUT)
{
self.pending = None;
self.terminal = true;
self.image = None;
}
}
pub fn loading(&self) -> Option<Instant> {
self.pending.as_ref().map(|p| p.started)
}
#[cfg(test)]
pub fn image(&self) -> Option<&RgbImage> {
self.image.as_ref().map(PreparedArt::small)
}
pub fn prepared(&self) -> Option<&PreparedArt> {
self.image.as_ref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::preview::fixture;
#[test]
fn no_request_without_visible_cover_and_missing_is_terminal_for_this_generation() {
let mut s = fixture();
s.track.as_mut().unwrap().artwork_id = Some("art-A".into());
let mut art = Artwork::default();
art.observe(Some(&s));
assert_eq!(art.needed(false), None);
assert_eq!(art.needed(true), Some("art-A".into()));
art.begin("request-A".into(), "art-A".into(), Instant::now());
assert!(art.loading().is_some());
art.complete("request-A", "art-A", None);
assert!(art.image().is_none());
assert!(art.loading().is_none());
assert_eq!(art.needed(true), None);
art.observe(Some(&s));
assert_eq!(art.needed(true), None);
}
#[test]
fn returning_to_same_artwork_rejects_the_first_a_response_by_request_id() {
let now = Instant::now();
let mut s = fixture();
s.track.as_mut().unwrap().artwork_id = Some("same-cover".into());
let mut art = Artwork::default();
art.observe(Some(&s));
art.begin("A-first".into(), "same-cover".into(), now);
let original_key = s.track.as_ref().unwrap().key.clone();
s.track.as_mut().unwrap().key = "B".into();
art.observe(Some(&s));
s.track.as_mut().unwrap().key = original_key;
art.observe(Some(&s));
art.begin("A-new".into(), "same-cover".into(), now);
let image = RgbImage::new(96, 96);
art.complete(
"A-first",
"same-cover",
Some(PreparedArt::new(image.clone())),
);
assert!(art.image().is_none());
assert!(art.loading().is_some());
art.complete("A-new", "same-cover", Some(PreparedArt::new(image.clone())));
assert_eq!(art.image(), Some(&image));
}
#[test]
fn timeout_and_reject_clear_loading_without_retry_or_late_image() {
let now = Instant::now();
let mut s = fixture();
s.track.as_mut().unwrap().artwork_id = Some("art".into());
let mut art = Artwork::default();
art.observe(Some(&s));
art.begin("timeout".into(), "art".into(), now);
art.expire(now + REQUEST_TIMEOUT);
art.complete(
"timeout",
"art",
Some(PreparedArt::new(RgbImage::new(96, 96))),
);
assert!(art.image().is_none());
assert_eq!(art.needed(true), None);
s.track.as_mut().unwrap().key = "next".into();
art.observe(Some(&s));
art.begin("rejected".into(), "art".into(), now);
art.reject("other");
assert!(art.loading().is_some());
art.reject("rejected");
assert!(art.loading().is_none());
assert_eq!(art.needed(true), None);
}
}