Nacre/src/media.rs

146 lines
4.6 KiB
Rust

//! Media playing in tabs: the state pages report (title, artist, art, position), which tab the
//! media button and Discord follow, and the visualizer levels (cava for real system audio when it
//! is installed, else Web Audio levels from the page, else a simulation).
use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use serde::Deserialize;
use crate::util;
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[serde(default)]
pub struct MediaState {
pub title: String,
pub artist: String,
pub album: String,
pub art: String,
pub position: f64,
pub duration: f64,
pub paused: bool,
pub muted: bool,
#[serde(rename = "loop")]
pub looping: bool,
pub has_next: bool,
pub has_prev: bool,
pub creator_url: String,
/// A YouTube ad is showing: keep the previous Discord activity.
pub ad: bool,
pub is_video: bool,
/// The page has a shuffle button of its own, and whether it is on.
pub has_shuffle: bool,
pub shuffle: bool,
}
impl MediaState {
/// Position now, extrapolated from when the state arrived.
pub fn position_at(&self, received_ms: u64) -> f64 {
if self.paused {
return self.position;
}
let elapsed = util::now_ms().saturating_sub(received_ms) as f64 / 1000.0;
let pos = self.position + elapsed;
if self.duration > 0.0 { pos.min(self.duration) } else { pos }
}
}
/// Number of visualizer bars.
pub const BANDS: usize = 28;
/// Real system-audio levels through `cava`.
pub struct Cava {
child: Option<Child>,
pub levels: Arc<Mutex<Vec<f32>>>,
}
impl Default for Cava {
fn default() -> Self {
Self::new()
}
}
impl Cava {
pub fn new() -> Cava {
Cava { child: None, levels: Arc::new(Mutex::new(Vec::new())) }
}
pub fn available() -> bool {
util::which("cava").is_some()
}
pub fn running(&self) -> bool {
self.child.is_some()
}
pub fn start(&mut self, config_dir: &std::path::Path) {
if self.child.is_some() || !Self::available() {
return;
}
let conf = config_dir.join("cava.conf");
let text = format!(
"[general]\nbars = {BANDS}\nframerate = 60\n[output]\nmethod = raw\nraw_target = /dev/stdout\ndata_format = ascii\nascii_max_range = 1000\nchannels = mono\n[smoothing]\nnoise_reduction = 50\n"
);
if std::fs::write(&conf, text).is_err() {
return;
}
let Ok(mut child) = Command::new("cava").arg("-p").arg(&conf).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn() else { return };
let stdout = child.stdout.take();
let levels = self.levels.clone();
if let Some(stdout) = stdout {
let _ = std::thread::Builder::new().name("nacre-cava".into()).spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
let values: Vec<f32> = line.split(';').filter(|v| !v.is_empty()).filter_map(|v| v.trim().parse::<f32>().ok()).map(|v| v / 1000.0).collect();
if values.len() >= BANDS
&& let Ok(mut l) = levels.lock()
{
*l = values;
}
}
});
}
self.child = Some(child);
}
pub fn stop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
if let Ok(mut l) = self.levels.lock() {
l.clear();
}
}
pub fn levels(&self) -> Option<Vec<f32>> {
self.levels.lock().ok().map(|l| l.clone()).filter(|l| l.len() >= BANDS)
}
}
impl Drop for Cava {
fn drop(&mut self) {
self.stop();
}
}
/// Bars that move like music when no real levels are available.
pub fn simulated_levels(time: f64) -> Vec<f32> {
(0..BANDS)
.map(|i| {
let f = i as f64 / BANDS as f64;
let beat = ((time * 2.1).sin() * 0.5 + 0.5).powf(3.0);
let wave = ((time * (3.0 + f * 7.0) + i as f64 * 1.7).sin() * 0.5 + 0.5) * (1.0 - f * 0.55);
((wave * 0.65 + beat * 0.35 * (1.0 - f)) as f32).clamp(0.02, 1.0)
})
.collect()
}
/// Smoothly move displayed bars toward the target levels.
pub fn ease_levels(shown: &mut Vec<f32>, target: &[f32], dt: f32) {
shown.resize(target.len(), 0.0);
for (s, t) in shown.iter_mut().zip(target) {
let rate = if *t > *s { 18.0 } else { 6.0 };
*s += (*t - *s) * (1.0 - (-rate * dt).exp());
}
}