diff --git a/ROADMAP.md b/ROADMAP.md index 34bcf4b..bce4632 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -105,4 +105,5 @@ 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. - 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 new file mode 100644 index 0000000..1c5f3c3 --- /dev/null +++ b/src/commands/music/card.rs @@ -0,0 +1,187 @@ +//! 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. +use crate::{pix, text}; +use cosmic_text::Align; +use image::{DynamicImage, Rgba, RgbaImage}; +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; + +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 SURFACE: [u8; 3] = [25, 25, 27]; +const SLOT: [u8; 3] = [35, 35, 37]; +const UNPLAYED: [u8; 3] = [58, 58, 62]; +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]; + +pub struct View { + pub status: String, + pub title: String, + pub artist: String, + 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>>, + pub cover: Option>, +} + +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 { + return text_.to_string(); + } + let mut chars: Vec = text_.chars().collect(); + while !chars.is_empty() { + chars.pop(); + let cut = chars.iter().collect::().trim_end().to_string() + "…"; + if text::width_of(&cut, size, look) <= width { + return cut; + } + } + String::new() +} + +fn line(img: &mut RgbaImage, text_: &str, x: i32, y: 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); +} + +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)); + return; + }; + let mut square = pix::cover(art, COVER, COVER); + let (size, r) = (COVER as f32, 12.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); + let dy = (r - (y as f32 + 0.5)).max((y as f32 + 0.5) - (size - r)).max(0.0); + r + 0.5 - (dx * dx + dy * dy).sqrt() + }); + 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 { + 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); + } + None => line(&mut img, &clock(view.position), RIGHT, time_y, 24.0, false, SECONDARY, 200), + } + 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() +} + +#[cfg(test)] +mod tests { + use super::*; + + 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 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)) } + } + + #[test] + fn the_card_is_a_small_picture_of_the_right_size() { + let jpg = render(&view()); + 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(); + } + let img = image::load_from_memory(&jpg).unwrap(); + assert_eq!((img.width(), img.height()), (WIDTH, HEIGHT)); + assert!(jpg.len() < 200_000, "{} bytes", jpg.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); + } + + #[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); + } +} diff --git a/src/commands/music/mod.rs b/src/commands/music/mod.rs index 7f8a3de..a1dff3d 100644 --- a/src/commands/music/mod.rs +++ b/src/commands/music/mod.rs @@ -8,11 +8,12 @@ //! * yt-dlp runs as separate processes, so looking up the next song never steals CPU time from the voice thread. //! * Audio is encoded at the voice channel's bitrate (at most 96 kbps), which keeps the upload light on a slow line. //! * The now-playing panel's buttons carry `music::`: they keep working after a restart. +mod card; pub(crate) mod source; pub mod ytdl; use self::source::Position; -use self::ytdl::{fmt_time, parse_time, progress_bar, Found, Track}; +use self::ytdl::{fmt_time, parse_time, progress_bar, Found, Stream, Track}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::state::State; @@ -29,9 +30,11 @@ use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; use tokio::sync::Mutex as AsyncMutex; use twilight_model::application::interaction::{Interaction, InteractionData}; +use twilight_http::error::ErrorType; use twilight_model::channel::message::component::{ButtonStyle, Component}; use twilight_model::channel::message::{AllowedMentions, MessageFlags}; use twilight_model::guild::Permissions; +use twilight_model::http::attachment::Attachment; use twilight_model::id::marker::{ChannelMarker, GuildMarker, MessageMarker, UserMarker}; use twilight_model::id::Id; @@ -40,6 +43,10 @@ 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. +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. +const WAVEFORM_LIMIT: u64 = 30 * 60; type Guild = Id; @@ -69,6 +76,11 @@ struct PState { idle_since: Option, loading: Option>, next_id: u64, + /// The waveform analysis for the current song. + waveform: Option>, + /// Dezio can't upload here, so the panel is text only. + plain_panel: bool, + drawn_at: Option, } pub struct Player { @@ -102,7 +114,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 }), + 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 }), play_lock: AsyncMutex::new(()), connect_lock: AsyncMutex::new(()), }) @@ -444,6 +456,9 @@ async fn teardown(state: &Arc, guild: Guild, disconnect: bool, notice: Op let (loading, current, channel) = { let mut st = p.lock(); st.queue.clear(); + if let Some(w) = st.waveform.take() { + w.abort(); + } (st.loading.take(), st.current.take(), st.text_channel) }; if let Some(l) = loading { @@ -509,6 +524,15 @@ pub fn start_watch(state: Arc) { } if expired { teardown(&state, guild, true, Some("👋 Left the voice channel after 5 minutes of inactivity.")).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) + }; + if due { + let state = state.clone(); + tokio::spawn(async move { refresh_panel(&state, &p).await }); } } } @@ -518,7 +542,8 @@ pub fn start_watch(state: Arc) { // ---- the now-playing panel -------------------------------------------------------------------------------------------------- -fn panel_card(p: &Player) -> Option { +/// 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 { let st = p.lock(); let cur = st.current.as_ref()?; let track = &cur.track; @@ -526,12 +551,19 @@ fn panel_card(p: &Player) -> Option { let mut card = Card::new(Some(if cur.paused { GOLD } else { accent.unwrap_or(GREEN) })); 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))); - 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()); let position = cur.pos.seconds(); - if let Some(d) = track.duration.filter(|_| position >= 1.0) { - card = card.text(&format!("`{}` {} `{}`", fmt_time(position), progress_bar(position, d as f64), fmt_time(d as f64))); + if image { + card = card.gallery(&[&format!("attachment://{}", card::FILE_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) { + card = card.text(&format!("`{}` {} `{}`", fmt_time(position), progress_bar(position, d as f64), fmt_time(d as f64))); + } } let mut details: Vec = track.requester.iter().map(|r| format!("Requested by <@{r}>")).collect(); + if image { + details.insert(0, link(&truncate(&track.title, 60), &track.url)); + } details.push(format!("🔊 {}%", (st.volume * 100.0).round() as u32)); if st.loop_mode != 0 { details.push(format!("🔁 Loop {}", LOOP_MODES[st.loop_mode])); @@ -585,22 +617,92 @@ async fn show_panel(state: &Arc, p: &Arc) { }; let (Some(track), Some(channel)) = (track, channel) else { return }; tint(state, &track, GREEN).await; - let Some(card) = panel_card(p) else { return }; - match state.http.create_message(channel).flags(MessageFlags::IS_COMPONENTS_V2).components(&[card]).allowed_mentions(Some(&AllowedMentions::default())).await { - Ok(r) => { - if let Ok(m) = r.model().await { - p.lock().panel = Some((m.channel_id, m.id)); - } - } - Err(e) => tracing::debug!("couldn't post the music panel: {e}"), + fetch_cover(state, &track).await; + start_waveform(state, p, &track).await; + let post = |card: Component, files: Vec| async move { + 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; + let mut sent = None; + if let (Some(file), Some(card)) = (picture, panel_card(p, true)) { + 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 }; + sent = post(card, vec![]).await.inspect_err(|e| tracing::debug!("couldn't post the music panel: {e}")).ok(); + } + if let Some(m) = sent { + p.lock().panel = Some((m.channel_id, m.id)); } } +/// Keep the cover so every redraw doesn't fetch it again. +async fn fetch_cover(state: &State, track: &Track) { + let known = track.art.lock().unwrap_or_else(|e| e.into_inner()).cover.is_some(); + let Some(url) = track.thumbnail.as_deref().filter(|_| !known) else { return }; + let Some(bytes) = crate::commands::media::fetch_limited(state, url, 4 * 1024 * 1024).await else { return }; + let decoded = tokio::task::spawn_blocking(move || crate::pix::decode(&bytes).map(|i| crate::pix::thumbnail(&i, 640))).await.ok().flatten(); + 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. +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 }; + 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 }; + track.art.lock().unwrap_or_else(|e| e.into_inner()).peaks = Some(Arc::new(bars)); + refresh_panel(&state, &player).await; + }); + 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 { + let view = { + let st = p.lock(); + 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() } + }; + let jpg = tokio::task::spawn_blocking(move || card::render(&view)).await.ok()?; + Some(Attachment::from_bytes(card::FILE_NAME.to_string(), jpg, 1)) +} + async fn refresh_panel(state: &State, p: &Player) { - let panel = p.lock().panel; - let (Some((c, m)), Some(card)) = (panel, panel_card(p)) else { return }; - if state.http.update_message(c, m).components(Some(&[card])).await.is_err() { - p.lock().panel = None; + let panel = { + let mut st = p.lock(); + st.drawn_at = Some(Instant::now()); + st.panel + }; + 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 files: Vec = picture.into_iter().collect(); + let components = [card]; + let mut edit = state.http.update_message(c, m).components(Some(&components)).attachments(&files); + 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 }; + // 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(); + if st.panel == Some((c, m)) { + st.panel = None; + } } } @@ -702,9 +804,8 @@ pub async fn on_component(state: &Arc, i: &Interaction) { } _ => return, } - if let Some(card) = panel_card(&p) { - interact::update(state, i, card).await; - } + interact::ack(state, i).await; // the picture has to be uploaded, which an interaction reply can't wait for + refresh_panel(state, &p).await; } async fn stop_all(state: &State, p: &Arc) { diff --git a/src/commands/music/source.rs b/src/commands/music/source.rs index 2b6f50a..d302942 100644 --- a/src/commands/music/source.rs +++ b/src/commands/music/source.rs @@ -192,10 +192,80 @@ 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. +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()) +} + +/// 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> { + use tokio::io::AsyncReadExt; + const RATE: f64 = 2000.0; + let mut cmd = tokio::process::Command::new(crate::commands::media::download::tool("ffmpeg")); + cmd.args(["-nostdin", "-loglevel", "error"]); + if !stream.headers.is_empty() { + cmd.arg("-headers").arg(stream.headers.iter().map(|(k, v)| format!("{k}: {v}\r\n")).collect::()); + } + cmd.arg("-i").arg(&stream.url).args(["-vn", "-ac", "1", "-ar", "2000", "-f", "s16le", "pipe:1"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true); + let mut child = cmd.spawn().ok()?; + let mut out = child.stdout.take()?; + let mut sums = vec![(0f64, 0u64); bars]; + let (mut buf, mut index, mut odd) = (vec![0u8; 16 * 1024], 0u64, None::); + loop { + let n = out.read(&mut buf).await.ok()?; + if n == 0 { + break; + } + let mut bytes = buf[..n].iter().copied(); + loop { + let Some(low) = odd.take().or_else(|| bytes.next()) else { break }; + let Some(high) = bytes.next() else { + odd = Some(low); // the sample continues in the next read + break; + }; + let sample = i16::from_le_bytes([low, high]) as f64; + let bar = ((index as f64 / (RATE * duration)) * bars as f64) as usize; + let slot = &mut sums[bar.min(bars - 1)]; + slot.0 += sample * sample; + slot.1 += 1; + index += 1; + } + } + shape(&sums) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn waveforms_are_scaled_to_the_loudest_bar() { + let bars = shape(&[(4.0, 1), (1.0, 1), (0.0, 0)]).unwrap(); + assert_eq!(bars[0], 1.0); + assert!(bars[1] > 0.0 && bars[1] < 0.5); + assert_eq!(bars[2], 0.0); + assert!(shape(&[(0.0, 0)]).is_none()); + } + + #[tokio::test] + async fn a_song_gets_a_real_waveform() { + if std::process::Command::new("ffmpeg").arg("-version").output().is_err() { + return; + } + // silence, then a tone: the second half of the bars must be the loud ones + let path = std::env::temp_dir().join(format!("dezio-peaks-{}.wav", std::process::id())); + 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 _ = std::fs::remove_file(&path); + assert!(bars[1] < 0.1, "{bars:?}"); + assert!(bars[6] > 0.9, "{bars:?}"); + } + /// A reader that hands out `frames` frames of 0.5-valued samples slowly, then ends. struct Slow { frames: usize, diff --git a/src/commands/music/ytdl.rs b/src/commands/music/ytdl.rs index 8a6d79f..50b5f84 100644 --- a/src/commands/music/ytdl.rs +++ b/src/commands/music/ytdl.rs @@ -34,6 +34,14 @@ pub struct Track { pub requester: Option, pub stream: Arc>>, pub accent: Arc>>, + /// The panel picture's cover and waveform, kept so a seek or a loop doesn't fetch them again. + pub art: Arc>, +} + +#[derive(Default)] +pub struct Art { + pub cover: Option>, + pub peaks: Option>>, } fn s(v: &Value, k: &str) -> Option { @@ -51,7 +59,7 @@ fn title_from_url(url: &str) -> String { impl Track { fn blank(url: String, title: String, requester: Option) -> Self { - Self { url, title, duration: None, thumbnail: None, uploader: None, requester, stream: Default::default(), accent: Default::default() } + Self { url, title, duration: None, thumbnail: None, uploader: None, requester, stream: Default::default(), accent: Default::default(), art: Default::default() } } /// From a full extraction (has the stream URL). diff --git a/src/commands/rolemenus.rs b/src/commands/rolemenus.rs index 031f0c8..01cccc2 100644 --- a/src/commands/rolemenus.rs +++ b/src/commands/rolemenus.rs @@ -685,7 +685,12 @@ async fn publish_draft(state: &State, d: &mut Draft, channel: Id, let card = public_card(&d.menu, !files.is_empty()); let mut posted: Option<(Id, Id)> = None; if let Some((c, m)) = d.edit { - if http.update_message(c, m).flags(MessageFlags::IS_COMPONENTS_V2).components(Some(&[card.clone()])).attachments(&files).await.is_ok() { + let components = [card.clone()]; + let mut edit = http.update_message(c, m).flags(MessageFlags::IS_COMPONENTS_V2).components(Some(&components)).attachments(&files); + if !files.is_empty() { + edit = edit.keep_attachment_ids(&[]); // replace the old picture instead of adding one + } + if edit.await.is_ok() { posted = Some((c, m)); } }