diff --git a/Cargo.lock b/Cargo.lock index a730e95..3a8cab9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1007,9 +1007,11 @@ dependencies = [ "axum", "base64 0.23.1", "chrono", + "color_quant", "cosmic-text", "dotenvy", "futures", + "gif", "html-escape", "image", "mime_guess", diff --git a/Cargo.toml b/Cargo.toml index 4e2a4c9..cea8d5b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,8 +11,10 @@ axum = "0.8" base64 = "0.23.1" chrono = { version = "0.4.45", default-features = false, features = ["clock", "std"] } cosmic-text = { version = "0.19.0", default-features = false, features = ["std", "swash"] } +color_quant = "1" dotenvy = "0.15.7" futures = "0.3.34" +gif = "0.14" html-escape = "0.3.0" image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "gif"] } mime_guess = "2.0.5" diff --git a/ROADMAP.md b/ROADMAP.md index bce4632..360e9c6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -105,5 +105,6 @@ Plan (backward compatible with the existing file): - Dashboard controls live in `web/dashboard/static/controls.js` (faders, switches, segments, searchable pickers, colour picker). Every control fires a bubbling `input`; sections go through one save bar. - The server page has only been looked at with faked API answers (`--web-dev` has no Discord cache). Not checked on the live bot yet. - Fixed: role menus published from the dashboard no longer claim roles they didn't make (taking one out used to delete a server's own role); zero ids no longer panic `D!ban`; announcement channels show in the pickers; static files revalidate after an update. -- Music panel: a picture drawn by `commands/music/card.rs` (cover, title, the song's real waveform from `source::peaks`, progress), redrawn every 20 s while people listen, with Discord's buttons under it. Without Attach Files the panel falls back to the text card. Rendering and analysis are tested; the panel itself has not been run against Discord. +- Music panel: an animated GIF drawn by `commands/music/card.rs`, laid out like the website's player: cover and title, moving bars, clock and progress. Each GIF is 30 s and is replaced about every 20 s while people listen; paused gives a still JPEG. Bar heights follow the song's real loudness (`source::peaks`), their shape is drawn, not a real spectrum. Bar colours come from the album cover (greys for a cover with no colour). Without Attach Files the panel falls back to the text card. +- Voice: a failed join now forgets the call, and a song whose position stands still for 45 s tells the channel and leaves. Why the joins failed on 2026-11-06 isn't known; songbird logs nothing at info level for it. - Known gap, unchanged: on a stage channel the bot can't unsuppress itself (twilight's `suppress()` only sets true). diff --git a/src/commands/music/card.rs b/src/commands/music/card.rs index 1c5f3c3..d017fb0 100644 --- a/src/commands/music/card.rs +++ b/src/commands/music/card.rs @@ -1,30 +1,48 @@ -//! The picture on the now-playing panel: cover, title, the song's real waveform and how far along it is. -//! Discord can't run animation in a message, so this is redrawn every so often and the panel's buttons sit under it. +//! The picture on the now-playing panel, laid out like the player on the website: cover and title, moving bars, then +//! the clock and progress. Discord can't run code in a message, so the movement is a GIF: 30 seconds of it, replaced +//! before it runs out. The bars' height follows the song's real loudness; their shape is drawn, not a real spectrum. use crate::{pix, text}; +use color_quant::NeuQuant; use cosmic_text::Align; use image::{DynamicImage, Rgba, RgbaImage}; +use std::collections::HashMap; use std::sync::Arc; -pub const FILE_NAME: &str = "player.jpg"; -/// How many bars the waveform has (the analysis in `source::peaks` makes one level per bar). -pub const BARS: usize = 72; +pub const MOVING_NAME: &str = "player.gif"; +pub const STILL_NAME: &str = "player.jpg"; +/// How finely `source::peaks` measures a song. +pub const LEVELS_PER_SECOND: usize = 5; -const WIDTH: u32 = 1200; -const HEIGHT: u32 = 380; -const PAD: i32 = 32; -const COVER: u32 = 316; -const RIGHT: i32 = PAD + COVER as i32 + 32; -const COLUMN: i32 = WIDTH as i32 - PAD - RIGHT; -const WAVE_TOP: i32 = 180; -const WAVE_HEIGHT: i32 = 124; +const WIDTH: u32 = 800; +const HEIGHT: u32 = 384; +const PAD: i32 = 28; +const COVER: u32 = 112; +const TEXT_X: i32 = PAD + COVER as i32 + 16; +const COLUMN: i32 = WIDTH as i32 - PAD - TEXT_X; +const BARS: usize = 36; +const BAR_TOP: i32 = 156; +const BAR_BOTTOM: i32 = 316; +const CLOCK_Y: i32 = 332; +const TRACK_LEFT: i32 = 104; +const TRACK_RIGHT: i32 = WIDTH as i32 - 104; +/// Everything below this line changes from frame to frame. +const MOVING_TOP: i32 = BAR_TOP - 4; + +const FRAME_SECONDS: f64 = 0.25; +const FRAMES: usize = 120; +/// The picture reaches people a moment after it's drawn, so it starts this far ahead. +const UPLOAD_LEAD: f64 = 1.5; +/// How much of the palette the cover gets; the rest is kept for the interface's own colours. +const COVER_COLOURS: usize = 200; const SURFACE: [u8; 3] = [25, 25, 27]; const SLOT: [u8; 3] = [35, 35, 37]; -const UNPLAYED: [u8; 3] = [58, 58, 62]; +const TRACK: [u8; 3] = [44, 44, 47]; const PRIMARY: [u8; 3] = [237, 237, 237]; const SECONDARY: [u8; 3] = [161, 161, 166]; const MUTED: [u8; 3] = [133, 133, 139]; -const ORCHID: [u8; 3] = [207, 123, 230]; +/// Bars for a cover with no colour in it (or no cover): low, middle and high. +const NEUTRAL_BARS: [[u8; 3]; 3] = [[88, 88, 92], [132, 132, 138], [188, 188, 194]]; pub struct View { pub status: String, @@ -33,9 +51,8 @@ pub struct View { pub position: f64, /// `None` for a live stream. pub duration: Option, - pub accent: u32, - /// 0..1 per bar, or `None` until the analysis is done (or for a live stream): a flat line then. - pub peaks: Option>>, + /// The song's loudness over time, or `None` until it's measured (or for a live stream). + pub levels: Option>>, pub cover: Option>, } @@ -43,21 +60,6 @@ fn rgba(c: [u8; 3]) -> Rgba { Rgba([c[0], c[1], c[2], 255]) } -/// The card colour comes from the cover and can be nearly black or grey: keep its hue at full brightness, -/// and use the logo's orchid when there's no hue to keep. -fn readable(accent: u32) -> [u8; 3] { - let c = [(accent >> 16) as u8, (accent >> 8) as u8, accent as u8].map(f32::from); - let (high, low) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); - if high == 0.0 || (high - low) / high < 0.2 { - return ORCHID; - } - let bright = c.map(|v| v * 255.0 / high); - let light = 0.299 * bright[0] + 0.587 * bright[1] + 0.114 * bright[2]; - // deep blues stay dim even at full brightness, so they get some white as well - let lift = ((140.0 - light) / (255.0 - light)).max(0.0); - bright.map(|v| (v + (255.0 - v) * lift).round() as u8) -} - /// Shorten with an ellipsis until one line fits `width`. fn fit_line(text_: &str, size: f32, look: &text::Look, width: f32) -> String { if text::width_of(text_, size, look) <= width { @@ -74,7 +76,7 @@ fn fit_line(text_: &str, size: f32, look: &text::Look, width: f32) -> String { String::new() } -fn line(img: &mut RgbaImage, text_: &str, x: i32, y: i32, size: f32, bold: bool, colour: [u8; 3], width: i32) { +fn line(img: &mut RgbaImage, text_: &str, (x, y): (i32, i32), size: f32, bold: bool, colour: [u8; 3], width: i32) { let look = text::Look::new(None, bold, colour); let fitted = fit_line(text_, size, &look, width as f32); text::layout(&fitted, size, &look, None, Align::Left).draw(img, x, y); @@ -82,11 +84,11 @@ fn line(img: &mut RgbaImage, text_: &str, x: i32, y: i32, size: f32, bold: bool, fn cover(img: &mut RgbaImage, art: Option<&RgbaImage>) { let Some(art) = art else { - pix::rounded_rect(img, PAD, PAD, COVER as i32, COVER as i32, 12, rgba(SLOT)); + pix::rounded_rect(img, PAD, PAD, COVER as i32, COVER as i32, 8, rgba(SLOT)); return; }; let mut square = pix::cover(art, COVER, COVER); - let (size, r) = (COVER as f32, 12.0); + let (size, r) = (COVER as f32, 8.0); // soft rounded corners: how far a pixel sits past the corner's circle pix::fade_alpha(&mut square, |x, y| { let dx = (r - (x as f32 + 0.5)).max((x as f32 + 0.5) - (size - r)).max(0.0); @@ -96,92 +98,268 @@ fn cover(img: &mut RgbaImage, art: Option<&RgbaImage>) { pix::paste(img, &square, PAD as i64, PAD as i64); } -fn mix(a: [u8; 3], b: [u8; 3], t: f32) -> [u8; 3] { - [0, 1, 2].map(|i| (a[i] as f32 * (1.0 - t) + b[i] as f32 * t).round() as u8) -} - -fn waveform(img: &mut RgbaImage, view: &View, accent: [u8; 3]) { - let step = COLUMN as f32 / BARS as f32; - let bar = (step * 0.64).round() as i32; - // the played part in bars, so the bar under the playhead can be part lit - let played = view.duration.filter(|d| *d > 0.0).map_or(0.0, |d| (view.position / d).clamp(0.0, 1.0)) as f32 * BARS as f32; - let middle = WAVE_TOP + WAVE_HEIGHT / 2; - for i in 0..BARS { - let level = view.peaks.as_ref().and_then(|p| p.get(i)).copied().unwrap_or(0.0); - let height = ((level * WAVE_HEIGHT as f32).round() as i32).max(bar).min(WAVE_HEIGHT); - let lit = (played - i as f32).clamp(0.0, 1.0); - let colour = mix(UNPLAYED, accent, lit); - pix::rounded_rect(img, RIGHT + (i as f32 * step).round() as i32, middle - height / 2, bar, height, bar / 2, rgba(colour)); - } -} - fn clock(seconds: f64) -> String { let s = seconds.max(0.0) as u64; if s >= 3600 { format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60) } else { format!("{}:{:02}", s / 60, s % 60) } } -pub fn render(view: &View) -> Vec { +/// The parts that stay the same for a whole animation. +fn backdrop(view: &View) -> RgbaImage { let mut img = RgbaImage::from_pixel(WIDTH, HEIGHT, rgba(SURFACE)); - let accent = readable(view.accent); cover(&mut img, view.cover.as_deref()); - line(&mut img, &view.status, RIGHT, 32, 24.0, false, MUTED, COLUMN); - line(&mut img, &view.title, RIGHT, 62, 42.0, true, PRIMARY, COLUMN); - line(&mut img, &view.artist, RIGHT, 124, 28.0, false, SECONDARY, COLUMN); - waveform(&mut img, view, accent); - let time_y = WAVE_TOP + WAVE_HEIGHT + 8; - match view.duration { - Some(d) => { - line(&mut img, &clock(view.position), RIGHT, time_y, 24.0, false, SECONDARY, 200); - let end = clock(d); - let look = text::Look::new(None, false, MUTED); - let w = text::width_of(&end, 24.0, &look).ceil() as i32; - line(&mut img, &end, RIGHT + COLUMN - w, time_y, 24.0, false, MUTED, w + 1); + line(&mut img, &view.status, (TEXT_X, 30), 17.0, false, MUTED, COLUMN); + line(&mut img, &view.title, (TEXT_X, 50), 30.0, true, PRIMARY, COLUMN); + line(&mut img, &view.artist, (TEXT_X, 92), 19.0, false, SECONDARY, COLUMN); + img +} + +fn mix(a: [u8; 3], b: [u8; 3], t: f32) -> [u8; 3] { + [0, 1, 2].map(|i| (a[i] as f32 * (1.0 - t) + b[i] as f32 * t).round() as u8) +} + +fn luma(c: [u8; 3]) -> f32 { + 0.299 * c[0] as f32 + 0.587 * c[1] as f32 + 0.114 * c[2] as f32 +} + +/// How colourful a colour is: 0 for grey, 1 for pure. +fn saturation(c: [u8; 3]) -> f32 { + let (high, low) = (*c.iter().max().unwrap_or(&0) as f32, *c.iter().min().unwrap_or(&0) as f32); + if high == 0.0 { 0.0 } else { (high - low) / high } +} + +/// Keep a colour's hue but make sure it reads on the dark card. +fn lifted(c: [u8; 3]) -> [u8; 3] { + let high = (*c.iter().max().unwrap_or(&1)).max(1) as f32; + let bright = c.map(|v| (v as f32 * (235.0 / high).max(1.0)).min(255.0).round() as u8); + mix(bright, [255, 255, 255], ((110.0 - luma(bright)) / 145.0).clamp(0.0, 0.6)) +} + +/// The bars' three colours, taken from the album cover: its real colours where it has a few, shades of the one it +/// has otherwise, and greys for a cover with none. +fn bar_colours(cover: Option<&RgbaImage>) -> [[u8; 3]; 3] { + let Some(cover) = cover else { return NEUTRAL_BARS }; + let small = image::imageops::thumbnail(cover, 48, 48); + let map = NeuQuant::new(10, 16, small.as_raw()).color_map_rgb(); + let apart = |a: [u8; 3], b: [u8; 3]| (0..3).map(|i| (a[i] as i32 - b[i] as i32).pow(2)).sum::() > 40 * 40; + // the palette holds many near copies of a cover's main colour, so keep only the ones that really differ + let mut distinct: Vec<[u8; 3]> = Vec::new(); + for c in map.chunks(3).map(|c| [c[0], c[1], c[2]]).filter(|c| saturation(*c) >= 0.3 && *c.iter().max().unwrap_or(&0) >= 50).map(lifted) { + if distinct.iter().all(|kept| apart(*kept, c)) { + distinct.push(c); } - None => line(&mut img, &clock(view.position), RIGHT, time_y, 24.0, false, SECONDARY, 200), } + distinct.sort_by(|a, b| luma(*a).total_cmp(&luma(*b))); + match distinct.as_slice() { + [] => NEUTRAL_BARS, + [one] => [mix(*one, SURFACE, 0.3), *one, mix(*one, [255, 255, 255], 0.3)], + [low, high] => [*low, mix(*low, *high, 0.5), *high], + many => [many[0], many[many.len() / 2], many[many.len() - 1]], + } +} + +/// The level at `seconds` into the song. Half way up when the song isn't measured, so the bars still move. +fn level_at(view: &View, seconds: f64) -> f32 { + let Some(levels) = &view.levels else { return 0.5 }; + let index = (seconds.max(0.0) * LEVELS_PER_SECOND as f64) as usize; + levels.get(index).copied().unwrap_or(0.0) +} + +fn bar_height(i: usize, t: f32, level: f32) -> i32 { + let x = i as f32 / BARS as f32; + let shape = 0.42 + 0.34 * (x * 9.0 + t * 1.7).sin() * (x * 3.1 - t * 0.9).sin() + 0.2 * (x * 23.0 + t * 3.3).sin(); + let tall = (shape * (0.2 + level * 0.95)).clamp(0.04, 1.0); + (tall * (BAR_BOTTOM - BAR_TOP) as f32).round() as i32 +} + +/// Draw the bars, the clock and the progress for the moment `seconds` into the song. +fn moment(img: &mut RgbaImage, view: &View, bars: &[[u8; 3]; 3], seconds: f64) { + let left = (WIDTH as i32 - 2 * PAD) as f32; + let step = left / BARS as f32; + let bar = (step * 0.76).round() as i32; + let level = level_at(view, seconds); + for i in 0..BARS { + let colour = if i * 10 >= BARS * 7 { bars[2] } else if i * 20 >= BARS * 7 { bars[1] } else { bars[0] }; + let height = bar_height(i, seconds as f32, level); + pix::rounded_rect(img, PAD + (i as f32 * step).round() as i32, BAR_BOTTOM - height, bar, height, 3, rgba(colour)); + } + line(img, &clock(seconds), (PAD, CLOCK_Y), 17.0, false, SECONDARY, 72); + let middle = CLOCK_Y + 10; + pix::rounded_rect(img, TRACK_LEFT, middle, TRACK_RIGHT - TRACK_LEFT, 4, 2, rgba(TRACK)); + if let Some(d) = view.duration.filter(|d| *d > 0.0) { + let done = ((seconds / d).clamp(0.0, 1.0) * (TRACK_RIGHT - TRACK_LEFT) as f64) as i32; + pix::rounded_rect(img, TRACK_LEFT, middle, done, 4, 2, rgba(bars[2])); + let end = clock(d); + let look = text::Look::new(None, false, MUTED); + let w = text::width_of(&end, 17.0, &look).ceil() as i32; + line(img, &end, (WIDTH as i32 - PAD - w, CLOCK_Y), 17.0, false, MUTED, w + 1); + } +} + +/// One picture, for a paused song. +pub fn still(view: &View) -> Vec { + let mut img = backdrop(view); + moment(&mut img, view, &bar_colours(view.cover.as_deref()), view.position); let mut out = std::io::Cursor::new(Vec::new()); let rgb = DynamicImage::ImageRgba8(img).to_rgb8(); let _ = rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 90)); out.into_inner() } +/// One palette for the whole GIF: the cover's colours, then every shade the interface can blend into. +struct Palette { + cover: NeuQuant, + colours: Vec<[u8; 3]>, + known: HashMap<[u8; 3], u8>, +} + +impl Palette { + fn new(backdrop: &RgbaImage, bars: &[[u8; 3]; 3]) -> Self { + // learn from the cover alone: the card around it is mostly one flat colour, which would swallow the palette + let square = image::imageops::crop_imm(backdrop, PAD as u32, PAD as u32, COVER, COVER).to_image(); + let cover = NeuQuant::new(1, COVER_COLOURS, square.as_raw()); + let mut colours: Vec<[u8; 3]> = cover.color_map_rgb().chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); + for shade in [PRIMARY, SECONDARY, MUTED] { + colours.extend((0..=8).map(|i| [0, 1, 2].map(|c| (SURFACE[c] as f32 + (shade[c] as f32 - SURFACE[c] as f32) * i as f32 / 8.0).round() as u8))); + } + colours.extend([SLOT, TRACK]); + colours.extend(bars); + colours.truncate(256); + Self { cover, colours, known: HashMap::new() } + } + + fn index(&mut self, c: [u8; 3]) -> u8 { + let colours = &self.colours; + *self.known.entry(c).or_insert_with(|| { + let distance = |p: &[u8; 3]| (0..3).map(|i| (p[i] as i32 - c[i] as i32).pow(2)).sum::(); + (0..colours.len()).min_by_key(|i| distance(&colours[*i])).unwrap_or(0) as u8 + }) + } + + /// The cover gets the fast lookup: it has far too many different pixels for the exact search. + fn index_cover(&self, c: [u8; 3]) -> u8 { + self.cover.index_of(&[c[0], c[1], c[2], 255]) as u8 + } + + fn flat(&self) -> Vec { + let mut out: Vec = self.colours.iter().flatten().copied().collect(); + out.resize(768, 0); + out + } +} + +/// 30 seconds of the player, played once: the bars move and the clock counts up from where the song is now. +pub fn moving(view: &View) -> Vec { + let base = backdrop(view); + let bars = bar_colours(view.cover.as_deref()); + let mut palette = Palette::new(&base, &bars); + let mut out = Vec::new(); + let flat = palette.flat(); + let Ok(mut encoder) = gif::Encoder::new(&mut out, WIDTH as u16, HEIGHT as u16, &flat) else { return still(view) }; + let top = MOVING_TOP as u32; + let start = view.position + UPLOAD_LEAD; + for n in 0..FRAMES { + let at = start + n as f64 * FRAME_SECONDS; + let at = view.duration.map_or(at, |d| at.min(d)); + let mut img = base.clone(); + moment(&mut img, view, &bars, at); + let delay = (FRAME_SECONDS * 100.0) as u16; + let frame = if n == 0 { + let in_cover = |x: u32, y: u32| (PAD as u32..PAD as u32 + COVER).contains(&x) && (PAD as u32..PAD as u32 + COVER).contains(&y); + let buffer: Vec = img.enumerate_pixels().map(|(x, y, p)| if in_cover(x, y) { palette.index_cover([p[0], p[1], p[2]]) } else { palette.index([p[0], p[1], p[2]]) }).collect(); + gif::Frame { width: WIDTH as u16, height: HEIGHT as u16, buffer: buffer.into(), delay, ..Default::default() } + } else { + // only the moving strip: the rest of the picture stays from the first frame + let buffer: Vec = (top..HEIGHT).flat_map(|y| (0..WIDTH).map(move |x| (x, y))).map(|(x, y)| { let p = img.get_pixel(x, y); palette.index([p[0], p[1], p[2]]) }).collect(); + gif::Frame { top: top as u16, width: WIDTH as u16, height: (HEIGHT - top) as u16, buffer: buffer.into(), delay, ..Default::default() } + }; + if encoder.write_frame(&frame).is_err() { + return still(view); + } + } + drop(encoder); + out +} + #[cfg(test)] mod tests { use super::*; + use image::AnimationDecoder; fn view() -> View { - let peaks: Vec = (0..BARS).map(|i| 0.3 + 0.6 * ((i as f32 * 0.31).sin() * (i as f32 * 0.07).sin()).abs()).collect(); + let levels: Vec = (0..222 * LEVELS_PER_SECOND).map(|i| 0.4 + 0.6 * (i as f32 * 0.09).sin().abs()).collect(); let art = RgbaImage::from_fn(640, 360, |x, y| Rgba([(x / 3) as u8, 60, (y / 2) as u8 + 60, 255])); View { status: "Now playing".into(), title: "A very long song title that cannot possibly fit on one line of this card, こんにちは 🎵".into(), artist: "Marlow Reed · 3:42".into(), - position: 66.0, duration: Some(222.0), accent: 0x101030, peaks: Some(Arc::new(peaks)), cover: Some(Arc::new(art)) } + position: 66.0, duration: Some(222.0), levels: Some(Arc::new(levels)), cover: Some(Arc::new(art)) } } #[test] - fn the_card_is_a_small_picture_of_the_right_size() { - let jpg = render(&view()); + fn the_moving_card_is_30_seconds_and_small_enough_to_upload_often() { + let started = std::time::Instant::now(); + let bytes = moving(&view()); + println!("{} KB in {:?}", bytes.len() / 1024, started.elapsed()); if std::env::var("DEZIO_DUMP").is_ok() { - std::fs::write(std::env::temp_dir().join("dezio_player.jpg"), &jpg).unwrap(); - let bare = View { peaks: None, cover: None, duration: None, status: "Live".into(), title: "Radio".into(), ..view() }; - std::fs::write(std::env::temp_dir().join("dezio_player_live.jpg"), render(&bare)).unwrap(); + std::fs::write(std::env::temp_dir().join("dezio_player.gif"), &bytes).unwrap(); + std::fs::write(std::env::temp_dir().join("dezio_player.jpg"), still(&view())).unwrap(); + let warm = RgbaImage::from_fn(640, 360, |x, y| if y < 180 { Rgba([230, 120 + (x / 8) as u8, 30, 255]) } else { Rgba([150, 30, 40, 255]) }); + std::fs::write(std::env::temp_dir().join("dezio_player_warm.jpg"), still(&View { cover: Some(Arc::new(warm)), ..view() })).unwrap(); } - let img = image::load_from_memory(&jpg).unwrap(); - assert_eq!((img.width(), img.height()), (WIDTH, HEIGHT)); - assert!(jpg.len() < 200_000, "{} bytes", jpg.len()); + let frames = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&bytes)).unwrap().into_frames().collect_frames().unwrap(); + assert_eq!(frames.len(), FRAMES); + assert_eq!(frames[0].buffer().dimensions(), (WIDTH, HEIGHT)); + assert_ne!(frames[0].buffer().as_raw(), frames[40].buffer().as_raw(), "the bars have to move"); + assert!(bytes.len() < 2_000_000, "{} bytes", bytes.len()); } #[test] - fn dark_covers_still_give_a_colour_that_reads() { - let c = readable(0x050510); - assert!(0.299 * c[0] as f32 + 0.587 * c[1] as f32 + 0.114 * c[2] as f32 >= 139.0, "{c:?}"); - assert!(c[2] > c[0], "keeps its blue: {c:?}"); - assert_eq!(readable(0xffffff), ORCHID); - assert_eq!(readable(0x101010), ORCHID); + fn the_clock_stops_at_the_end_of_the_song() { + let v = View { position: 221.0, ..view() }; + assert!(!moving(&v).is_empty()); + } + + #[test] + fn bars_follow_the_songs_loudness() { + let quiet: i32 = (0..BARS).map(|i| bar_height(i, 3.0, 0.05)).sum(); + let loud: i32 = (0..BARS).map(|i| bar_height(i, 3.0, 1.0)).sum(); + assert!(loud > quiet * 2, "{quiet} {loud}"); + } + + #[test] + fn a_measured_song_reads_its_level_and_silence_past_the_end() { + let v = View { levels: Some(Arc::new(vec![0.1, 0.9])), ..view() }; + assert_eq!(level_at(&v, 0.3), 0.9); + assert_eq!(level_at(&v, 50.0), 0.0); + assert_eq!(level_at(&View { levels: None, ..view() }, 1.0), 0.5); + } + + #[test] + fn the_bars_take_their_colours_from_the_cover() { + let red = RgbaImage::from_fn(64, 64, |x, _| Rgba([200 + (x / 2) as u8, 30, 20, 255])); + for c in bar_colours(Some(&red)) { + assert!(c[0] > c[1] && c[0] > c[2], "{c:?}"); + } + let green_and_blue = RgbaImage::from_fn(64, 64, |x, _| if x < 32 { Rgba([20, 170, 60, 255]) } else { Rgba([20, 60, 200, 255]) }); + let bars = bar_colours(Some(&green_and_blue)); + assert!(bars.iter().any(|c| c[1] > c[0] && c[1] > c[2]), "green is in there: {bars:?}"); + assert!(bars.iter().any(|c| c[2] > c[0] && c[2] > c[1]), "and blue: {bars:?}"); + } + + #[test] + fn a_black_and_white_cover_gets_neutral_bars() { + let grey = RgbaImage::from_fn(64, 64, |x, _| Rgba([(x * 4) as u8, (x * 4) as u8, (x * 4) as u8, 255])); + assert_eq!(bar_colours(Some(&grey)), NEUTRAL_BARS); + assert_eq!(bar_colours(None), NEUTRAL_BARS); + } + + #[test] + fn dark_colours_are_lifted_but_keep_their_hue() { + let c = lifted([8, 8, 40]); + assert!(luma(c) >= 80.0 && c[2] > c[0], "{c:?}"); } #[test] fn long_titles_are_cut_to_fit() { let look = text::Look::new(None, true, PRIMARY); - let cut = fit_line(&"long ".repeat(60), 46.0, &look, 400.0); - assert!(cut.ends_with('…') && text::width_of(&cut, 46.0, &look) <= 400.0); + let cut = fit_line(&"long ".repeat(60), 30.0, &look, 400.0); + assert!(cut.ends_with('…') && text::width_of(&cut, 30.0, &look) <= 400.0); } } diff --git a/src/commands/music/mod.rs b/src/commands/music/mod.rs index a1dff3d..985da2e 100644 --- a/src/commands/music/mod.rs +++ b/src/commands/music/mod.rs @@ -43,9 +43,12 @@ const DEFAULT_VOLUME: u32 = 80; const MAX_QUEUE: usize = 500; const IDLE_TIMEOUT: Duration = Duration::from_secs(300); const LOOP_MODES: [&str; 3] = ["off", "track", "queue"]; -/// How often the panel's picture is redrawn while a song plays. Each redraw is an upload and a message edit. +/// How often the panel's picture is replaced while a song plays, sooner than its 30 seconds of animation run out. +/// Each one is an upload and a message edit. const PANEL_TICK: Duration = Duration::from_secs(20); -/// Songs longer than this keep a flat line instead of a waveform: the analysis reads the whole file. +/// A playing song whose position hasn't moved for this long has lost its voice connection. +const STALL_LIMIT: Duration = Duration::from_secs(45); +/// Songs longer than this aren't measured: the analysis reads the whole file. Their bars move at a steady level. const WAVEFORM_LIMIT: u64 = 30 * 60; type Guild = Id; @@ -81,6 +84,8 @@ struct PState { /// Dezio can't upload here, so the panel is text only. plain_panel: bool, drawn_at: Option, + /// Where the song last was, and when it got there. + moved: Option<(f64, Instant)>, } pub struct Player { @@ -114,7 +119,7 @@ fn player_for(guild: Guild) -> Arc { let percent = prefs::guild_pref(guild.get(), "music_volume").and_then(|v| v.as_u64()).unwrap_or(DEFAULT_VOLUME as u64).min(100); Arc::new(Player { guild, - st: Mutex::new(PState { queue: VecDeque::new(), current: None, loop_mode: 0, volume: percent as f32 / 100.0, text_channel: None, panel: None, skip_requested: false, votes: None, alone_since: None, idle_since: None, loading: None, next_id: 1, waveform: None, plain_panel: false, drawn_at: None }), + st: Mutex::new(PState { queue: VecDeque::new(), current: None, loop_mode: 0, volume: percent as f32 / 100.0, text_channel: None, panel: None, skip_requested: false, votes: None, alone_since: None, idle_since: None, loading: None, next_id: 1, waveform: None, plain_panel: false, drawn_at: None, moved: None }), play_lock: AsyncMutex::new(()), connect_lock: AsyncMutex::new(()), }) @@ -287,6 +292,9 @@ async fn connect(state: &Arc, p: &Arc, channel: Id } tracing::warn!("voice connect to {channel} failed (attempt {}): {last}", attempt + 1); } + // Discord's answer can still arrive after we gave up. Forget the call, or the next /play would see a half-made + // connection, believe it, and play into nothing. + let _ = sb.remove(p.guild).await; Err(format!("Couldn't connect to <#{channel}> ({last}). Try again in a moment.")) } @@ -483,6 +491,22 @@ pub async fn on_bot_left(state: Arc, guild: Guild) { teardown(&state, guild, false, None).await; // kicked or disconnected } +/// Keep track of a playing song's position; true once it has stood still for [`STALL_LIMIT`]. +/// `position` is `None` while paused or between songs, which starts the clock over. +fn hasnt_moved(moved: &mut Option<(f64, Instant)>, position: Option, now: Instant) -> bool { + let Some(position) = position else { + *moved = None; + return false; + }; + match *moved { + Some((last, since)) if last == position => now.duration_since(since) >= STALL_LIMIT, + _ => { + *moved = Some((position, now)); + false + } + } +} + /// Leave after 5 minutes alone or with nothing playing. Started once. pub fn start_watch(state: Arc) { static ONCE: std::sync::Once = std::sync::Once::new(); @@ -526,9 +550,19 @@ pub fn start_watch(state: Arc) { teardown(&state, guild, true, Some("👋 Left the voice channel after 5 minutes of inactivity.")).await; continue; } + let stuck = { + let mut st = p.lock(); + let playing_at = st.current.as_ref().filter(|c| !c.paused).map(|c| c.pos.seconds()); + hasnt_moved(&mut st.moved, playing_at, Instant::now()) + }; + if stuck { + tracing::warn!("music in {guild}: no audio has moved for {} s, giving up", STALL_LIMIT.as_secs()); + teardown(&state, guild, true, Some("⚠️ I lost the voice connection, so the music stopped. Use `/play` to start again.")).await; + continue; + } let due = { let st = p.lock(); - listeners && st.panel.is_some() && !st.plain_panel && st.current.as_ref().is_some_and(|c| !c.paused && c.track.duration.is_some()) && st.drawn_at.is_none_or(|t| t.elapsed() >= PANEL_TICK) + listeners && st.panel.is_some() && !st.plain_panel && st.current.as_ref().is_some_and(|c| !c.paused) && st.drawn_at.is_none_or(|t| t.elapsed() >= PANEL_TICK) }; if due { let state = state.clone(); @@ -542,8 +576,8 @@ pub fn start_watch(state: Arc) { // ---- the now-playing panel -------------------------------------------------------------------------------------------------- -/// The panel. With `image` the picture carries the title and progress, so the text only adds what's clickable. -fn panel_card(p: &Player, image: bool) -> Option { +/// The panel. With a picture (`image` is its file name) that carries the title and progress, so the text only adds what's clickable. +fn panel_card(p: &Player, image: Option<&str>) -> Option { let st = p.lock(); let cur = st.current.as_ref()?; let track = &cur.track; @@ -552,8 +586,8 @@ fn panel_card(p: &Player, image: bool) -> Option { let mut meta: Vec = track.uploader.iter().map(|u| escape(u)).collect(); meta.push(track.duration.map_or("🔴 LIVE".to_string(), |d| fmt_time(d as f64))); let position = cur.pos.seconds(); - if image { - card = card.gallery(&[&format!("attachment://{}", card::FILE_NAME)]); + if let Some(name) = image { + card = card.gallery(&[&format!("attachment://{name}")]); } else { card = card.header(&[&format!("-# {}", if cur.paused { "⏸️ Paused".to_string() } else { format!("{PLAYING_EMOJI} Now Playing") }), &format!("### {}\n{}", link(&truncate(&track.title, 90), &track.url), meta.join(" · "))], track.thumbnail.as_deref()); if let Some(d) = track.duration.filter(|_| position >= 1.0) { @@ -561,7 +595,7 @@ fn panel_card(p: &Player, image: bool) -> Option { } } let mut details: Vec = track.requester.iter().map(|r| format!("Requested by <@{r}>")).collect(); - if image { + if image.is_some() { details.insert(0, link(&truncate(&track.title, 60), &track.url)); } details.push(format!("🔊 {}%", (st.volume * 100.0).round() as u32)); @@ -625,12 +659,13 @@ async fn show_panel(state: &Arc, p: &Arc) { }; let picture = panel_picture(p).await; let mut sent = None; - if let (Some(file), Some(card)) = (picture, panel_card(p, true)) { + let name = picture.as_ref().map(|f| f.filename.clone()); + if let (Some(file), Some(card)) = (picture, panel_card(p, name.as_deref())) { sent = post(card, vec![file]).await.inspect_err(|e| tracing::debug!("couldn't post the music panel's picture: {e}")).ok(); p.lock().plain_panel = sent.is_none(); // usually no Attach Files permission here } if sent.is_none() { - let Some(card) = panel_card(p, false) else { return }; + let Some(card) = panel_card(p, None) else { return }; sent = post(card, vec![]).await.inspect_err(|e| tracing::debug!("couldn't post the music panel: {e}")).ok(); } if let Some(m) = sent { @@ -647,17 +682,19 @@ async fn fetch_cover(state: &State, track: &Track) { track.art.lock().unwrap_or_else(|e| e.into_inner()).cover = decoded.map(Arc::new); } -/// Measure the song in the background, then redraw the panel with its waveform. +/// Measure the song's loudness in the background, then redraw the panel so the bars follow it. async fn start_waveform(state: &Arc, p: &Arc, track: &Track) { if let Some(old) = p.lock().waveform.take() { old.abort(); } let done = track.art.lock().unwrap_or_else(|e| e.into_inner()).peaks.is_some(); - let Some(duration) = track.duration.filter(|d| !done && *d > 0 && *d <= WAVEFORM_LIMIT) else { return }; + if done || !track.duration.is_some_and(|d| d > 0 && d <= WAVEFORM_LIMIT) { + return; + } let Some(stream) = track.stream.lock().await.as_ref().map(|s| Stream { url: s.url.clone(), headers: s.headers.clone(), at: s.at }) else { return }; let (state, player, track) = (state.clone(), p.clone(), track.clone()); let task = tokio::spawn(async move { - let Ok(Some(bars)) = tokio::time::timeout(Duration::from_secs(120), source::peaks(&stream, duration as f64, card::BARS)).await else { return }; + let Ok(Some(bars)) = tokio::time::timeout(Duration::from_secs(120), source::peaks(&stream, card::LEVELS_PER_SECOND)).await else { return }; track.art.lock().unwrap_or_else(|e| e.into_inner()).peaks = Some(Arc::new(bars)); refresh_panel(&state, &player).await; }); @@ -671,14 +708,14 @@ async fn panel_picture(p: &Player) -> Option { let cur = st.current.as_ref().filter(|_| !st.plain_panel)?; let track = &cur.track; let art = track.art.lock().unwrap_or_else(|e| e.into_inner()); - let accent = track.accent.lock().unwrap_or_else(|e| e.into_inner()).filter(|a| *a != 0).unwrap_or(BLURPLE); let status = if cur.paused { "Paused" } else if track.duration.is_none() { "Live" } else { "Now playing" }; let mut who: Vec = track.uploader.iter().cloned().collect(); who.push(track.duration.map_or("Live".to_string(), |d| fmt_time(d as f64))); - card::View { status: status.to_string(), title: track.title.clone(), artist: who.join(" · "), position: cur.pos.seconds(), duration: track.duration.map(|d| d as f64), accent, peaks: art.peaks.clone(), cover: art.cover.clone() } + (cur.paused, card::View { status: status.to_string(), title: track.title.clone(), artist: who.join(" · "), position: cur.pos.seconds(), duration: track.duration.map(|d| d as f64), levels: art.peaks.clone(), cover: art.cover.clone() }) }; - let jpg = tokio::task::spawn_blocking(move || card::render(&view)).await.ok()?; - Some(Attachment::from_bytes(card::FILE_NAME.to_string(), jpg, 1)) + let (paused, view) = view; + let (name, bytes) = tokio::task::spawn_blocking(move || if paused { (card::STILL_NAME, card::still(&view)) } else { (card::MOVING_NAME, card::moving(&view)) }).await.ok()?; + Some(Attachment::from_bytes(name.to_string(), bytes, 1)) } async fn refresh_panel(state: &State, p: &Player) { @@ -689,7 +726,7 @@ async fn refresh_panel(state: &State, p: &Player) { }; let Some((c, m)) = panel else { return }; let picture = panel_picture(p).await; - let Some(card) = panel_card(p, picture.is_some()) else { return }; + let Some(card) = panel_card(p, picture.as_ref().map(|f| f.filename.as_str())) else { return }; let files: Vec = picture.into_iter().collect(); let components = [card]; let mut edit = state.http.update_message(c, m).components(Some(&components)).attachments(&files); @@ -1274,6 +1311,21 @@ pub fn commands() -> Vec { mod tests { use super::*; + #[test] + fn a_song_that_stops_moving_counts_as_lost() { + let start = Instant::now(); + let later = |s: u64| start + Duration::from_secs(s); + let mut moved = None; + assert!(!hasnt_moved(&mut moved, Some(5.0), start)); + assert!(!hasnt_moved(&mut moved, Some(5.0), later(44))); + assert!(hasnt_moved(&mut moved, Some(5.0), later(45))); + // moving again, or a pause, starts the clock over + assert!(!hasnt_moved(&mut moved, Some(6.0), later(46))); + assert!(!hasnt_moved(&mut moved, None, later(100))); + assert!(!hasnt_moved(&mut moved, Some(6.0), later(200))); + assert!(!hasnt_moved(&mut moved, Some(6.0), later(230))); + } + #[test] fn links_are_safe_in_markdown() { assert_eq!(link("A [b] c", "https://x.y/z"), "[A (b) c]()"); diff --git a/src/commands/music/source.rs b/src/commands/music/source.rs index d302942..b11dc8f 100644 --- a/src/commands/music/source.rs +++ b/src/commands/music/source.rs @@ -192,18 +192,18 @@ pub fn spawn_pipe(stream: &Stream, start: f64) -> Result<(BufferedPipe, Position Ok((pipe, position)) } -/// Turn summed squares per bar into 0..1 heights, loudest bar = 1. `None` if there was nothing to hear. +/// Turn summed squares per slice into 0..1 loudness, loudest slice = 1. `None` if there was nothing to hear. fn shape(sums: &[(f64, u64)]) -> Option> { let rms: Vec = sums.iter().map(|(sum, n)| if *n > 0 { (sum / *n as f64).sqrt() } else { 0.0 }).collect(); let loudest = rms.iter().cloned().fold(0.0, f64::max); - (loudest > 0.0).then(|| rms.iter().map(|v| (v / loudest).powf(1.5) as f32).collect()) + (loudest > 0.0).then(|| rms.iter().map(|v| (v / loudest) as f32).collect()) } -/// How loud each part of a song is, one level per bar. A second, very low quality ffmpeg reads the whole song once -/// (about 2 MB of audio for 3 minutes), so it stays away from the voice thread and failing costs nothing. -pub async fn peaks(stream: &Stream, duration: f64, bars: usize) -> Option> { +/// How loud a song is over time, `per_second` levels a second. A second, very low quality ffmpeg reads the whole song +/// once (about 2 MB of audio for 3 minutes), so it stays away from the voice thread and failing costs nothing. +pub async fn peaks(stream: &Stream, per_second: usize) -> Option> { use tokio::io::AsyncReadExt; - const RATE: f64 = 2000.0; + const RATE: usize = 2000; let mut cmd = tokio::process::Command::new(crate::commands::media::download::tool("ffmpeg")); cmd.args(["-nostdin", "-loglevel", "error"]); if !stream.headers.is_empty() { @@ -212,8 +212,9 @@ pub async fn peaks(stream: &Stream, duration: f64, bars: usize) -> Option); + let per_slice = RATE / per_second; + let mut sums: Vec<(f64, u64)> = Vec::new(); + let (mut buf, mut index, mut odd) = (vec![0u8; 16 * 1024], 0usize, None::); loop { let n = out.read(&mut buf).await.ok()?; if n == 0 { @@ -227,10 +228,12 @@ pub async fn peaks(stream: &Stream, duration: f64, bars: usize) -> Option 0.0 && bars[1] < 0.5); - assert_eq!(bars[2], 0.0); + fn levels_are_scaled_to_the_loudest_slice() { + let levels = shape(&[(4.0, 1), (1.0, 1), (0.0, 0)]).unwrap(); + assert_eq!(levels, vec![1.0, 0.5, 0.0]); assert!(shape(&[(0.0, 0)]).is_none()); } #[tokio::test] - async fn a_song_gets_a_real_waveform() { + async fn a_song_gets_its_real_loudness() { if std::process::Command::new("ffmpeg").arg("-version").output().is_err() { return; } @@ -260,10 +261,11 @@ mod tests { let filter = "aevalsrc='if(lt(t,1),0,0.5*sin(440*2*PI*t))':d=2:s=44100"; assert!(std::process::Command::new("ffmpeg").args(["-loglevel", "error", "-y", "-f", "lavfi", "-i", filter]).arg(&path).status().unwrap().success()); let stream = Stream { url: path.to_string_lossy().into_owned(), headers: vec![], at: std::time::Instant::now() }; - let bars = peaks(&stream, 2.0, 8).await.unwrap(); + let levels = peaks(&stream, 4).await.unwrap(); let _ = std::fs::remove_file(&path); - assert!(bars[1] < 0.1, "{bars:?}"); - assert!(bars[6] > 0.9, "{bars:?}"); + assert_eq!(levels.len(), 8, "{levels:?}"); + assert!(levels[1] < 0.1, "{levels:?}"); + assert!(levels[6] > 0.9, "{levels:?}"); } /// A reader that hands out `frames` frames of 0.5-valued samples slowly, then ends. diff --git a/web/dashboard/static/app.js b/web/dashboard/static/app.js index c206588..5d62ebb 100644 --- a/web/dashboard/static/app.js +++ b/web/dashboard/static/app.js @@ -1,7 +1,7 @@ // Dezio dashboard: the pages. The controls live in controls.js. "use strict"; -const state = { me: null, page: "me", sections: [], spy: null }; +const state = { me: null, page: "me", sections: [], spy: null, turn: 0 }; // ---------------------------------------------------------------------------- helpers function toast(text, bad) { @@ -375,8 +375,9 @@ function mount(parts) { watchScroll(); } -async function showMe() { +async function showMe(turn) { const s = await api("GET", "/api/user"); + if (turn !== state.turn) return; // they went elsewhere meanwhile; a newer load draws the page const parts = [h("header", { class: "page-head" }, h("h1", {}, "Your settings"), h("p", { class: "sub" }, "These follow you to every server that has Dezio"))]; if (s.lastfm_available) { @@ -433,9 +434,9 @@ async function showMe() { mount(parts); } -async function showGuild(id) { +async function showGuild(id, turn) { const g = await api("GET", `/api/guilds/${id}`); - if (state.page !== id) return; + if (turn !== state.turn) return; const path = `/api/guilds/${id}`; const facts = [`${g.channels.length} channels`, `${g.roles.length} roles`]; if (g.member_count) facts.unshift(`${g.member_count} members`); @@ -557,19 +558,20 @@ function watchScroll() { async function go(page, keepScroll) { if (page !== state.page && dirty().length && !(await ask("Leave without saving?", "Your changes on this page will be lost.", "Leave", "Stay"))) return; const top = scrollY; + const turn = ++state.turn; // sections are added to one shared list, so only the newest load may build the page state.page = page; state.sections = []; refreshSaveBar(); history.replaceState(null, "", page === "me" ? "/dashboard" : `/dashboard#${page}`); renderSide(); - const slow = setTimeout(() => $("main").replaceChildren(skeleton()), 160); + const slow = setTimeout(() => { if (turn === state.turn) $("main").replaceChildren(skeleton()); }, 160); try { - if (page === "me") await showMe(); else await showGuild(page); + if (page === "me") await showMe(turn); else await showGuild(page, turn); } catch (e) { - $("main").replaceChildren(h("p", { class: "error" }, e.message)); + if (turn === state.turn) $("main").replaceChildren(h("p", { class: "error" }, e.message)); } clearTimeout(slow); - scrollTo(0, keepScroll ? top : 0); + if (turn === state.turn) scrollTo(0, keepScroll ? top : 0); } const ERRORS = { diff --git a/web/site/assets/site.css b/web/site/assets/site.css index 76f870c..dc835ef 100644 --- a/web/site/assets/site.css +++ b/web/site/assets/site.css @@ -15,7 +15,7 @@ a { color: var(--text); } .top nav a:not(.btn):hover { color: var(--text); } /* hero: the copy on the left, the player on the right */ -.hero { display: flex; align-items: center; min-height: calc(100vh - 57px); padding: 48px 0 64px; } +.hero { display: flex; align-items: center; min-height: calc(100vh - 57px); padding: 48px 0 64px; overflow-x: clip; } .hero-grid { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 64px; align-items: center; } .hero-copy > * { animation: rise var(--enter) var(--ease) backwards; } .hero-copy > :nth-child(2) { animation-delay: 48ms; } @@ -28,7 +28,85 @@ a { color: var(--text); } @keyframes rise { from { opacity: 0; transform: translateY(8px); } } /* the player: Dezio's now-playing panel, working */ -.deck { display: grid; gap: 16px; margin: 0; padding: 20px; border: 1px solid var(--line); border-radius: 20px; background: var(--card); box-shadow: 0 32px 64px rgba(0, 0, 0, .4); animation: rise var(--enter) var(--ease) 192ms backwards; } +.carousel { min-width: 0; perspective: 1200px; animation: rise var(--enter) var(--ease) 192ms backwards; } +.slides { display: grid; } +.slide { --x: 0px; grid-area: 1 / 1; min-width: 0; visibility: hidden; opacity: 0; transform: translateX(var(--x)); transition: opacity var(--enter) var(--ease), transform var(--enter) var(--ease), visibility var(--enter); } +.slide.on { visibility: visible; opacity: 1; transform: none; } +.deck { --rx: 0deg; --ry: 0deg; position: relative; display: grid; align-content: start; gap: 16px; height: 100%; margin: 0; padding: 20px; border: 1px solid var(--line); border-radius: 20px; background: var(--card); box-shadow: 0 32px 64px rgba(0, 0, 0, .4); + transform: rotateX(var(--rx)) rotateY(var(--ry)); transition: transform 420ms var(--ease), border-color var(--menu) var(--ease); } +.deck.tilting { border-color: var(--line-2); transition: transform 80ms linear, border-color var(--menu) var(--ease); } +.deck::after { content: ""; position: absolute; inset: 0; border-radius: inherit; opacity: 0; pointer-events: none; background: radial-gradient(320px circle at var(--gx, 50%) var(--gy, 50%), rgba(255, 255, 255, .07), transparent 70%); transition: opacity var(--menu) var(--ease); } +.deck.tilting::after { opacity: 1; } + +.car-nav { display: flex; align-items: center; gap: 8px; margin-top: 16px; } +.car-dots { flex: 1; display: grid; grid-template-columns: repeat(10, minmax(0, 1fr)); gap: 4px; } +.car-dot { position: relative; height: 24px; padding: 0; border: 0; background: none; cursor: pointer; } +.car-dot::before { content: ""; position: absolute; left: 0; right: 0; top: 10px; height: 4px; border-radius: 2px; background: var(--raised-2); transition: background-color var(--fast) var(--ease); } +.car-dot:hover::before { background: var(--text-3); } +.car-dot i { position: absolute; left: 0; right: 0; top: 10px; height: 4px; border-radius: 2px; background: var(--accent); transform: scaleX(0); transform-origin: left; } +.car-dot.on i { transform: scaleX(1); } +.car-dot.timing i { animation: fill 10s linear; } +.carousel.held .car-dot.timing i { animation-play-state: paused; } +@keyframes fill { from { transform: scaleX(0); } to { transform: scaleX(1); } } +.car-label { margin: 8px 0 0; color: var(--text-3); font-size: 13px; line-height: 20px; text-align: center; } + +.slide-head { display: flex; align-items: center; gap: 12px; } +.slide-head .ic { width: 18px; height: 18px; flex: none; color: var(--text-3); } +.slide-head > div { flex: 1; min-width: 0; display: grid; } +.slide-head small { color: var(--text-3); font-size: 13px; line-height: 20px; } +.slide-head strong { overflow: hidden; font-size: 20px; font-weight: 500; line-height: 28px; text-overflow: ellipsis; white-space: nowrap; } + +.handheld { padding: 12px; border-radius: 12px; background: var(--ink); } +.handheld canvas { display: block; width: 100%; border-radius: 4px; image-rendering: pixelated; } +.ranks { display: grid; gap: 12px; margin: 0; padding: 0; list-style: none; font-size: 14px; line-height: 20px; } +.ranks li { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 16px; } +.ranks b { color: var(--text-3); font: 400 12px/20px var(--mono); } +.ranks i { grid-column: 1 / -1; height: 4px; border-radius: 2px; background: var(--raised-2); transform-origin: left; } +.ranks li:first-child i { background: var(--accent); } +.ranks .r100 { transform: scaleX(1); } .ranks .r70 { transform: scaleX(.7); } .ranks .r48 { transform: scaleX(.48); } .ranks .r35 { transform: scaleX(.35); } .ranks .r24 { transform: scaleX(.24); } +.chess { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 16px; align-items: start; } +.board { display: grid; grid-template-columns: repeat(8, 1fr); overflow: hidden; border-radius: 6px; } +.board span { display: grid; place-items: center; aspect-ratio: 1; background: #3a3a3e; color: #fff; font-size: clamp(14px, 2vw, 24px); line-height: 1; } +.board span.lt { background: #77777d; } +.board span.last { background: var(--violet); } +.board span.b { color: #111; } +.chess-side { min-width: 104px; color: var(--text-3); font-size: 13px; line-height: 20px; } +.chess-side p { margin: 0 0 8px; } +.chess-side b { display: block; color: var(--text); font-weight: 500; } +.moves { font-family: var(--mono); font-size: 12px; } +.table { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; padding: 20px; border-radius: 12px; background: var(--ink); } +.table small { display: block; margin-bottom: 8px; color: var(--text-3); font-size: 13px; } +.hand { display: flex; } +.card { display: grid; align-content: space-between; width: 72px; height: 100px; padding: 8px; border-radius: 8px; background: #f4f2ee; color: #1b1b1d; font: 500 20px/1 var(--font); box-shadow: 0 4px 12px rgba(0, 0, 0, .4); } +.card + .card { margin-left: -24px; transform: rotate(5deg); } +.card i { justify-self: end; font-style: normal; font-size: 24px; } +.card.red { color: #c7302f; } +.card.down { background: var(--cobalt); box-shadow: inset 0 0 0 4px #f4f2ee, 0 4px 12px rgba(0, 0, 0, .4); } +.job { display: grid; gap: 8px; padding: 16px; border-radius: 12px; background: var(--ink); } +.job p:first-child { display: flex; justify-content: space-between; margin: 0; font-size: 14px; } +.job b { color: var(--text-2); font: 400 12px/22px var(--mono); } +.job .bar i { background: var(--accent); transform: scaleX(0); transition: transform 200ms linear; } +.sources { display: flex; flex-wrap: wrap; gap: 8px; margin: 0; padding: 0; list-style: none; color: var(--text-2); font-size: 13px; } +.sources li { padding: 2px 8px; border: 1px solid var(--line); border-radius: 6px; } +.log { margin: 0; padding: 0; list-style: none; font-size: 14px; line-height: 20px; } +.log li { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0 16px; padding: 10px 0; border-bottom: 1px solid var(--line); } +.log li:last-child { border-bottom: 0; } +.log b { font-weight: 500; } +.log span { grid-row: 2; color: var(--text-3); font-size: 13px; } +.log time { color: var(--text-3); font: 400 12px/20px var(--mono); } +.quote { display: grid; grid-template-columns: 2fr 3fr; align-items: center; min-height: 200px; overflow: hidden; border-radius: 12px; background: #000; color: #fff; text-align: center; } +.quote-face { align-self: stretch; background: linear-gradient(to right, #8b8b8f, #000); } +.quote p { margin: 0 16px 8px; font-size: 18px; line-height: 26px; } +.quote small { color: #8a8a8a; font-size: 13px; } +.chat { display: grid; gap: 12px; } +.bubble { display: grid; gap: 2px; margin: 0; padding: 12px 16px; border-radius: 12px; background: var(--raised); color: var(--text-2); font-size: 15px; } +.bubble b { color: var(--text); font-size: 13px; font-weight: 500; } +.bubble.me { background: var(--ink); box-shadow: inset 3px 0 0 var(--violet); } +.weather { display: flex; align-items: baseline; gap: 16px; } +.temp { margin: 0; font-size: 56px; font-weight: 400; line-height: 64px; letter-spacing: -.03em; } +.days { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; margin: 0; padding: 0; list-style: none; color: var(--text-3); font-size: 13px; text-align: center; } +.days li { padding: 12px 0; border-radius: 8px; background: var(--ink); } +.days b { display: block; margin-top: 4px; color: var(--text); font: 400 16px/24px var(--font); } .deck-top { display: flex; align-items: center; gap: 16px; } .cover { width: 96px; height: 96px; flex: none; border-radius: 8px; } .deck-title { display: grid; min-width: 0; } @@ -103,5 +181,9 @@ footer a { color: var(--text-2); } .item code { grid-column: 2; justify-self: start; } .vu { height: 64px; } .cover { width: 72px; height: 72px; } + .card { width: 60px; height: 84px; } + .table { padding: 12px; } + .chess { grid-template-columns: minmax(0, 1fr); } + .chess-side { display: none; } .deck-title strong { font-size: 18px; line-height: 24px; } } diff --git a/web/site/assets/site.js b/web/site/assets/site.js index fa9be97..dd7e796 100644 --- a/web/site/assets/site.js +++ b/web/site/assets/site.js @@ -79,7 +79,7 @@ if (deck) { const frame = (now) => { const beat = 60000 / TRACKS[index].bpm; const dt = now - last; - if (dt > 110) { + if (dt > 110 && deck.closest(".slide").classList.contains("on")) { last = now; phase += dt / 1000; const kick = Math.exp(-((now % beat) / beat) * 5); @@ -110,3 +110,129 @@ if (deck) { paintTrack(); paintTime(); } + +// The hero's cards: one at a time, Back and Next, and on to the next one every 10 seconds unless the pointer is on them. +const carousel = document.getElementById("carousel"); +if (carousel) { + const slides = [...carousel.querySelectorAll(".slide")]; + const label = document.getElementById("car-label"); + const dots = slides.map((slide, i) => { + const dot = document.createElement("button"); + dot.type = "button"; + dot.className = "car-dot"; + dot.setAttribute("aria-label", `Show ${slide.dataset.label}`); + dot.append(document.createElement("i")); + dot.addEventListener("click", () => show(i, i < at ? -1 : 1)); + document.getElementById("car-dots").append(dot); + return dot; + }); + let at = 0; + const paintDots = () => dots.forEach((dot, i) => { + dot.classList.toggle("on", i === at); + dot.classList.remove("timing"); + if (i === at && !calm) { void dot.offsetWidth; dot.classList.add("timing"); } // restarts the 10 seconds + if (i === at) dot.setAttribute("aria-current", "true"); else dot.removeAttribute("aria-current"); + }); + const show = (index, direction) => { + const next = (index + slides.length) % slides.length; + if (next === at) return paintDots(); + const [from, to] = [slides[at], slides[next]]; + to.style.transition = "none"; + to.style.setProperty("--x", `${direction * 32}px`); + void to.offsetWidth; + to.style.transition = ""; + from.style.setProperty("--x", `${direction * -32}px`); + from.classList.remove("on"); + from.inert = true; + to.classList.add("on"); + to.inert = false; + at = next; + label.textContent = to.dataset.label; + paintDots(); + }; + document.getElementById("car-next").addEventListener("click", () => show(at + 1, 1)); + document.getElementById("car-back").addEventListener("click", () => show(at - 1, -1)); + carousel.addEventListener("keydown", (event) => { + if (event.key === "ArrowRight") show(at + 1, 1); + if (event.key === "ArrowLeft") show(at - 1, -1); + }); + // The timer is the progress bar's own animation, so holding the pointer on the cards pauses both together. + carousel.addEventListener("animationend", (event) => { if (event.animationName === "fill") show(at + 1, 1); }); + const hold = (value) => () => carousel.classList.toggle("held", value); + carousel.addEventListener("pointerenter", hold(true)); + carousel.addEventListener("pointerleave", hold(false)); + carousel.addEventListener("focusin", hold(true)); + carousel.addEventListener("focusout", hold(false)); + new IntersectionObserver(([entry]) => carousel.classList.toggle("held", !entry.isIntersecting)).observe(carousel); + paintDots(); + + // Each card leans toward the pointer. Only for a real mouse, so scrolling on a phone doesn't wobble it. + if (!calm && matchMedia("(hover: hover) and (pointer: fine)").matches) { + for (const card of carousel.querySelectorAll(".deck")) { + card.addEventListener("pointermove", (event) => { + const box = card.getBoundingClientRect(); + const x = (event.clientX - box.left) / box.width, y = (event.clientY - box.top) / box.height; + card.classList.add("tilting"); + card.style.setProperty("--ry", `${(x - .5) * 16}deg`); + card.style.setProperty("--rx", `${(.5 - y) * 16}deg`); + card.style.setProperty("--gx", `${x * 100}%`); + card.style.setProperty("--gy", `${y * 100}%`); + }); + card.addEventListener("pointerleave", () => { + card.classList.remove("tilting"); + card.style.setProperty("--rx", "0deg"); + card.style.setProperty("--ry", "0deg"); + }); + } + } + + // Chess: the Ruy Lopez after 3... a6, drawn from its position string. + const board = document.getElementById("board"); + const GLYPHS = { k: "\u265A", q: "\u265B", r: "\u265C", b: "\u265D", n: "\u265E", p: "\u265F" }; + [..."r1bqkbnr/1ppp1ppp/p1n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R".replaceAll("/", "")].flatMap((c) => (/\d/.test(c) ? Array(Number(c)).fill("") : [c])).forEach((piece, i) => { + const square = document.createElement("span"); + const [row, col] = [Math.floor(i / 8), i % 8]; + square.className = (row + col) % 2 ? "" : "lt"; + if (i === 16) square.classList.add("last"); // a6, the last move + if (piece) { + square.textContent = GLYPHS[piece.toLowerCase()] + "\uFE0E"; + if (piece === piece.toLowerCase()) square.classList.add("b"); + } + board.append(square); + }); + + // Downloads: the progress bar fills while its card is showing. + const downloads = slides.find((s) => s.dataset.label === "Downloads"); + let job = 0; + setInterval(() => { + if (!downloads.classList.contains("on") || calm) { job = calm ? 72 : 0; } else job = Math.min(100, job + 4); + document.getElementById("job-pct").textContent = `${job}%`; + document.getElementById("job-bar").style.transform = `scaleX(${job / 100})`; + }, 200); + + // Game Boy: a little scene of our own in the handheld's four greens. + const canvas = document.getElementById("pixels"); + const pen = canvas.getContext("2d"); + const SHADES = ["#e0f0c0", "#90b868", "#487048", "#183020"]; + const box = (shade, x, y, w, h) => { pen.fillStyle = SHADES[shade]; pen.fillRect(Math.round(x), Math.round(y), w, h); }; + const gameboy = slides.find((s) => s.dataset.label === "Game Boy"); + const scene = (time) => { + const t = calm ? 40 : time / 16; + box(0, 0, 0, 160, 96); + for (let i = 0; i < 4; i++) { const x = 170 - ((t * .25 + i * 57) % 190); box(1, x, 12 + i * 7 % 18, 18, 4); box(1, x + 4, 8 + i * 7 % 18, 10, 4); } + for (let i = 0; i < 5; i++) { const x = 170 - ((t * .5 + i * 41) % 200); box(1, x, 60 - i * 3 % 12, 24, 24); box(1, x + 6, 54 - i * 3 % 12, 12, 8); } + box(3, 0, 80, 160, 16); + for (let x = -((t * 1) % 16); x < 160; x += 16) box(2, x, 84, 8, 4); + const pipe = 170 - (t * 1 % 220); + box(2, pipe, 64, 12, 16); box(3, pipe - 2, 62, 16, 4); + const coin = 170 - ((t * 1 + 90) % 220); + if (coin > 40) box(2, coin, 38 + Math.sin(t / 8) * 2, 6, 6); + // the runner hops over whatever is coming + const gap = pipe - 36; + const hop = gap > -12 && gap < 26 ? Math.sin(((26 - gap) / 38) * Math.PI) * 30 : 0; + box(3, 36, 66 - hop, 10, 12); box(0, 42, 69 - hop, 2, 2); box(3, 34 + (Math.floor(t / 6) % 2) * 6, 78 - hop, 4, 2); + }; + const run = (time) => { if (gameboy.classList.contains("on")) scene(time); requestAnimationFrame(run); }; + scene(0); + if (!calm) requestAnimationFrame(run); +} diff --git a/web/site/index.html b/web/site/index.html index a5ac737..42746af 100644 --- a/web/site/index.html +++ b/web/site/index.html @@ -25,6 +25,12 @@ + + + + + + @@ -57,36 +63,131 @@

/help lists every command, and D! works too

-
-
- -
- Now playing - Slow Drive Home - Marlow Reed · 3:42 -
+
+
+
+
ChessYour move, @nightowl
/chess
+
+

@nightowl white

@mira black

1. e4 e5
2. Nf3 Nc6
3. Bb5 a6

+
+
+
+
+
CasinoBlackjack against Dezio
/blackjack
+
+
Dealer
7♠
+
You, 21
A♥K♣
+
+

Also coin flip, slots and roulette, with balances kept per person

+
+
+
+
+
DownloadsSized to fit Discord
/download
+
+

Converting to H.2640%

+
+

tiktok.com · clip.mp4 · 7.4 MB

+
+
  • TikTok
  • Instagram
  • YouTube
  • X
  • Reddit
+
+
+
+
+
Moderation and loggingEvery action, credited
/logging
+
    +
  • Message deleted#general, by @mira
  • +
  • Member timed out@spamcat for 10 minutes, by @mira
  • +
  • Role addedDJ to @nightowl, by @rowan
  • +
  • Messages purged42 in #memes, by @rowan
  • +
+
+
+
+
+
QuotesRight-click, Create Quote
Quote
+

I said I'd be on in five minutes. That was in March.

- Mira · @mira
+

Presets, any Google Font, colours and your own default style

+
+
+
+
+
AI chatMention Dezio to talk
@Dezio
+
+

nightowl@Dezio what should I name my cat

+

DezioSir Reginald Whiskers. He can drop the title once he's earned it.

+
+

Admins can give it a personality or keep it to one channel

+
+
+
+
+
WeatherDenver, Colorado
/weather
+

12°C

Partly cloudy · feels like 10°C

+
  • Sat14°
  • Sun9°
  • Mon6°
  • Tue11°
  • Wed15°
+
+
+ +
+ +
+ +
+

Music

+