diff --git a/ROADMAP.md b/ROADMAP.md index 6ecd77a..c6d9ffb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -105,6 +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: 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). Typed searches go to YouTube Music for the real artist, album, year and square art, falling back to plain YouTube; links keep their own details. 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. +- 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 at about 6 fps (0.55 s to make on the Celeron) and is replaced about every 20 s while people listen, its clock started ahead by the measured upload time; a new panel posts a still JPEG first, and paused stays still. 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). Typed searches go to YouTube Music for the real artist, album, year and square art, falling back to plain YouTube; links keep their own details. 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. Joins failed on 2026-11-06 because the Chromebook's network gives an IPv6 address with no IPv6 route; /etc/gai.conf now prefers IPv4 (backup /root/gai.conf.bak-2026-11-06). A running bot only picks that up after a restart. - 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 d017fb0..1e45dbf 100644 --- a/src/commands/music/card.rs +++ b/src/commands/music/card.rs @@ -28,10 +28,9 @@ 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; +/// Six frames a second for 30 seconds. GIF delays are in hundredths of a second. +const FRAME_DELAY: u16 = 16; +const FRAMES: usize = 188; /// How much of the palette the cover gets; the rest is kept for the interface's own colours. const COVER_COLOURS: usize = 200; @@ -171,23 +170,25 @@ fn bar_height(i: usize, t: f32, level: f32) -> i32 { (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)); +/// Where bar `i` starts, and how wide every bar is. +fn bar_slot(i: usize) -> (i32, i32) { + let step = (WIDTH as i32 - 2 * PAD) as f32 / BARS as f32; + (PAD + (i as f32 * step).round() as i32, (step * 0.76).round() as i32) +} + +/// Which of the three colours bar `i` gets: low, middle or high. +fn bar_band(i: usize) -> usize { + if i * 10 >= BARS * 7 { 2 } else if i * 20 >= BARS * 7 { 1 } else { 0 } +} + +fn progress_width(view: &View, seconds: f64) -> i32 { + view.duration.filter(|d| *d > 0.0).map_or(0, |d| ((seconds / d).clamp(0.0, 1.0) * (TRACK_RIGHT - TRACK_LEFT) as f64) as i32) +} + +/// The parts of the moving strip that don't move: the empty progress track and the song's length. +fn strip_backdrop(img: &mut RgbaImage, view: &View) { + pix::rounded_rect(img, TRACK_LEFT, CLOCK_Y + 10, 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; @@ -195,6 +196,19 @@ fn moment(img: &mut RgbaImage, view: &View, bars: &[[u8; 3]; 3], seconds: f64) { } } +/// 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 level = level_at(view, seconds); + for i in 0..BARS { + let (x, width) = bar_slot(i); + let height = bar_height(i, seconds as f32, level); + pix::rounded_rect(img, x, BAR_BOTTOM - height, width, height, 3, rgba(bars[bar_band(i)])); + } + line(img, &clock(seconds), (PAD, CLOCK_Y), 17.0, false, SECONDARY, 72); + strip_backdrop(img, view); + pix::rounded_rect(img, TRACK_LEFT, CLOCK_Y + 10, progress_width(view, seconds), 4, 2, rgba(bars[2])); +} + /// One picture, for a paused song. pub fn still(view: &View) -> Vec { let mut img = backdrop(view); @@ -247,31 +261,79 @@ impl Palette { } } -/// 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 { +/// The moving part of the picture as palette indexes: redrawing only this, with no text shaping per frame, is what +/// keeps a GIF quick on the Celeron the bot runs on. +struct Strip { + pixels: Vec, +} + +impl Strip { + const WIDTH: usize = WIDTH as usize; + + fn fill(&mut self, x: i32, y: i32, width: i32, height: i32, colour: u8) { + let (x, width) = (x.max(0) as usize, width.max(0) as usize); + for row in y.max(MOVING_TOP)..(y + height).min(HEIGHT as i32) { + let start = (row - MOVING_TOP) as usize * Self::WIDTH + x; + self.pixels[start..(start + width).min((row - MOVING_TOP + 1) as usize * Self::WIDTH)].fill(colour); + } + } +} + +/// 30 seconds of the player, played once: the bars move and the clock counts up. `lead` is how many seconds the picture +/// takes to reach people, so its clock is right when it arrives. +pub fn moving(view: &View, lead: f64) -> 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 mut out = Vec::new(); 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() } - }; + let bar_ink = bars.map(|c| palette.index(c)); + let start = view.position + lead; + let at = |n: usize| { + let t = start + n as f64 * FRAME_DELAY as f64 / 100.0; + view.duration.map_or(t, |d| t.min(d)) + }; + + // the first frame is the whole picture + let mut first = base.clone(); + moment(&mut first, view, &bars, at(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 = first.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(); + if encoder.write_frame(&gif::Frame { width: WIDTH as u16, height: HEIGHT as u16, buffer: buffer.into(), delay: FRAME_DELAY, ..Default::default() }).is_err() { + return still(view); + } + + // the rest only repaint the strip under the title + let mut empty = RgbaImage::from_pixel(WIDTH, HEIGHT, rgba(SURFACE)); + strip_backdrop(&mut empty, view); + let empty = image::imageops::crop_imm(&empty, 0, MOVING_TOP as u32, WIDTH, HEIGHT - MOVING_TOP as u32).to_image(); + let fixed: Vec = empty.pixels().map(|p| palette.index([p[0], p[1], p[2]])).collect(); + let (clock_x, clock_y, clock_w, clock_h) = (PAD as usize, (CLOCK_Y - MOVING_TOP) as usize, 72usize, 26usize); + let (mut shown, mut digits) = (String::new(), vec![0u8; clock_w * clock_h]); + for n in 1..FRAMES { + let seconds = at(n); + let mut strip = Strip { pixels: fixed.clone() }; + let level = level_at(view, seconds); + for i in 0..BARS { + let (x, width) = bar_slot(i); + let height = bar_height(i, seconds as f32, level); + strip.fill(x, BAR_BOTTOM - height, width, height, bar_ink[bar_band(i)]); + } + strip.fill(TRACK_LEFT, CLOCK_Y + 10, progress_width(view, seconds), 4, bar_ink[2]); + // the clock only changes once a second, so its text is drawn once a second + let time = clock(seconds); + if time != shown { + let mut sprite = RgbaImage::from_pixel(clock_w as u32, clock_h as u32, rgba(SURFACE)); + line(&mut sprite, &time, (0, 0), 17.0, false, SECONDARY, clock_w as i32); + digits = sprite.pixels().map(|p| palette.index([p[0], p[1], p[2]])).collect(); + shown = time; + } + for row in 0..clock_h { + let target = (clock_y + row) * Strip::WIDTH + clock_x; + strip.pixels[target..target + clock_w].copy_from_slice(&digits[row * clock_w..(row + 1) * clock_w]); + } + let frame = gif::Frame { top: MOVING_TOP as u16, width: WIDTH as u16, height: (HEIGHT as i32 - MOVING_TOP) as u16, buffer: strip.pixels.into(), delay: FRAME_DELAY, ..Default::default() }; if encoder.write_frame(&frame).is_err() { return still(view); } @@ -295,7 +357,7 @@ mod tests { #[test] fn the_moving_card_is_30_seconds_and_small_enough_to_upload_often() { let started = std::time::Instant::now(); - let bytes = moving(&view()); + let bytes = moving(&view(), 2.0); 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.gif"), &bytes).unwrap(); @@ -310,10 +372,34 @@ mod tests { assert!(bytes.len() < 2_000_000, "{} bytes", bytes.len()); } + #[test] + fn the_first_frame_starts_where_the_song_will_be_when_it_arrives() { + assert_eq!(clock(66.0 + 7.0), "1:13"); + let early = moving(&view(), 0.0); + let late = moving(&view(), 7.0); + let first = |gif: &[u8]| image::codecs::gif::GifDecoder::new(std::io::Cursor::new(gif)).unwrap().into_frames().next().unwrap().unwrap().into_buffer(); + assert_ne!(first(&early).as_raw(), first(&late).as_raw()); + } + + #[test] + fn the_strip_and_the_still_card_put_the_clock_in_the_same_place() { + // a frame's fixed strip plus its moving parts, compared with the whole picture drawn the slow way + let v = view(); + let bars = bar_colours(v.cover.as_deref()); + let mut whole = backdrop(&v); + moment(&mut whole, &v, &bars, v.position); + assert_eq!(whole.get_pixel(TRACK_LEFT as u32 + 1, CLOCK_Y as u32 + 11)[0], bars[2][0]); + let gif = moving(&v, 0.0); + let frames = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(&gif)).unwrap().into_frames().collect_frames().unwrap(); + let later = frames[1].buffer(); + assert_eq!(later.get_pixel(TRACK_LEFT as u32 + 1, CLOCK_Y as u32 + 11).0[..3], bars[2][..]); + assert_eq!(later.get_pixel(10, MOVING_TOP as u32 + 1).0[..3], SURFACE[..]); + } + #[test] fn the_clock_stops_at_the_end_of_the_song() { let v = View { position: 221.0, ..view() }; - assert!(!moving(&v).is_empty()); + assert!(!moving(&v, 2.0).is_empty()); } #[test] diff --git a/src/commands/music/mod.rs b/src/commands/music/mod.rs index 743fa38..e95e890 100644 --- a/src/commands/music/mod.rs +++ b/src/commands/music/mod.rs @@ -44,8 +44,10 @@ 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 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); +/// Each one is an upload and a message edit. The watch loop runs every 10 s, so this means every 20. +const PANEL_TICK: Duration = Duration::from_secs(18); +/// How long a new picture takes to reach people, until a real one has been measured. +const FIRST_LEAD: f64 = 3.0; /// 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. @@ -84,6 +86,8 @@ struct PState { /// Dezio can't upload here, so the panel is text only. plain_panel: bool, drawn_at: Option, + /// How many seconds the last picture took to draw and upload, so the next one's clock can start that far ahead. + lead: f64, /// Where the song last was, and when it got there. moved: Option<(f64, Instant)>, } @@ -119,7 +123,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, moved: 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, lead: FIRST_LEAD, moved: None }), play_lock: AsyncMutex::new(()), connect_lock: AsyncMutex::new(()), }) @@ -657,7 +661,8 @@ async fn show_panel(state: &Arc, p: &Arc) { let sent = state.http.create_message(channel).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).attachments(&files).allowed_mentions(Some(&AllowedMentions::default())).await?; Ok::<_, anyhow::Error>(sent.model().await?) }; - let picture = panel_picture(p).await; + // a still picture right away; the moving one takes a few seconds to make and replaces it + let picture = panel_picture(p, false).await; let mut sent = None; let name = picture.as_ref().map(|f| f.filename.clone()); if let (Some(file), Some(card)) = (picture, panel_card(p, name.as_deref())) { @@ -670,6 +675,8 @@ async fn show_panel(state: &Arc, p: &Arc) { } if let Some(m) = sent { p.lock().panel = Some((m.channel_id, m.id)); + let (state, player) = (state.clone(), p.clone()); + tokio::spawn(async move { refresh_panel(&state, &player).await }); } } @@ -701,8 +708,9 @@ async fn start_waveform(state: &Arc, p: &Arc, track: &Track) { p.lock().waveform = Some(task); } -/// Draw the panel's picture as it stands now, unless this channel gets the text panel. -async fn panel_picture(p: &Player) -> Option { +/// Draw the panel's picture as it stands now, unless this channel gets the text panel. `animate`: the moving one, +/// if the song is playing. +async fn panel_picture(p: &Player, animate: bool) -> Option { let view = { let st = p.lock(); let cur = st.current.as_ref().filter(|_| !st.plain_panel)?; @@ -712,10 +720,10 @@ async fn panel_picture(p: &Player) -> Option { let mut who: Vec = track.uploader.iter().cloned().collect(); who.extend(track.album.iter().map(|a| track.year.map_or(a.clone(), |y| format!("{a} ({y})")))); who.push(track.duration.map_or("Live".to_string(), |d| fmt_time(d as f64))); - (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() }) + (animate && !cur.paused, st.lead, 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 (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()?; + let (moving, lead, view) = view; + let (name, bytes) = tokio::task::spawn_blocking(move || if moving { (card::MOVING_NAME, card::moving(&view, lead)) } else { (card::STILL_NAME, card::still(&view)) }).await.ok()?; Some(Attachment::from_bytes(name.to_string(), bytes, 1)) } @@ -726,7 +734,8 @@ async fn refresh_panel(state: &State, p: &Player) { st.panel }; let Some((c, m)) = panel else { return }; - let picture = panel_picture(p).await; + let started = Instant::now(); + let picture = panel_picture(p, true).await; 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]; @@ -734,7 +743,10 @@ async fn refresh_panel(state: &State, p: &Player) { if !files.is_empty() { edit = edit.keep_attachment_ids(&[]); // twilight keeps old files by default, which would stack one per redraw } - let Err(e) = edit.await else { return }; + let Err(e) = edit.await else { + p.lock().lead = started.elapsed().as_secs_f64().min(15.0) + 0.5; // the half second is Discord showing it + return; + }; // Only a deleted panel is forgotten: a slow upload mustn't stop the updates, and a newer panel stays. if matches!(e.kind(), ErrorType::Response { status, .. } if status.get() == 404) { let mut st = p.lock();