/convert: pick type, format and quality; /image is now /media (effects only)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
parent
f27373b693
commit
d272840807
6 changed files with 737 additions and 150 deletions
10
src/cmd.rs
10
src/cmd.rs
|
|
@ -81,6 +81,9 @@ impl Opt {
|
|||
pub type Handler = fn(Arc<Ctx>) -> BoxFuture<'static, Result<()>>;
|
||||
|
||||
/// Suggestions for an option being typed: (state, option name, text so far, who, where) -> (label, value) pairs.
|
||||
/// Like [`Suggest`], but also gets the other options already filled in (so one choice can depend on another).
|
||||
pub type SuggestWith = fn(Arc<State>, String, String, HashMap<String, String>) -> BoxFuture<'static, Vec<(String, String)>>;
|
||||
|
||||
pub type Suggest = fn(Arc<State>, String, String, Option<Id<GuildMarker>>, Id<UserMarker>) -> BoxFuture<'static, Vec<(String, String)>>;
|
||||
|
||||
pub struct Command {
|
||||
|
|
@ -108,12 +111,13 @@ pub struct Command {
|
|||
pub perm: Option<Permissions>,
|
||||
pub handler: Handler,
|
||||
pub suggest: Option<Suggest>,
|
||||
pub suggest_with: Option<SuggestWith>,
|
||||
}
|
||||
|
||||
impl Command {
|
||||
pub fn new(name: &'static str, category: &'static str, description: &'static str, handler: Handler) -> Self {
|
||||
Self { name, aliases: &[], description, category, usage: "", options: vec![], slash: true, slash_name: None,
|
||||
guild_only: false, hidden: false, owner_only: false, cooldown: None, message_menu: false, user_menu: false, perm: None, handler, suggest: None }
|
||||
guild_only: false, hidden: false, owner_only: false, cooldown: None, message_menu: false, user_menu: false, perm: None, handler, suggest: None, suggest_with: None }
|
||||
}
|
||||
pub fn aliases(mut self, a: &'static [&'static str]) -> Self {
|
||||
self.aliases = a;
|
||||
|
|
@ -137,6 +141,10 @@ impl Command {
|
|||
self.slash = true;
|
||||
self
|
||||
}
|
||||
pub fn suggest_with(mut self, f: SuggestWith) -> Self {
|
||||
self.suggest_with = Some(f);
|
||||
self
|
||||
}
|
||||
pub fn suggest(mut self, f: Suggest) -> Self {
|
||||
self.suggest = Some(f);
|
||||
self
|
||||
|
|
|
|||
168
src/commands/media/convert.rs
Normal file
168
src/commands/media/convert.rs
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
//! `/convert` · `D!convert` — turn any picture, clip or sound into any image, video or audio format.
|
||||
//!
|
||||
//! The slash command asks for a **type** (image / video / audio), then a **format** that depends on it (as you type
|
||||
//! the list shows only the formats of that type), then an optional **quality**: *adaptive* (the best that fits
|
||||
//! Discord's upload limit), a height in pixels like `1080p` / `720p` / `900p` for pictures and video (smaller sources
|
||||
//! are upscaled with Lanczos and a little sharpening), or a bitrate like `192k` for audio.
|
||||
//! Text version: `D!convert mp3 128k` (reply to a file, attach one, or add a link / @user).
|
||||
use super::ffmpeg::{self, find_format, formats_for, parse_quality, Converted, MediaType, Quality, HEIGHTS, KBPS};
|
||||
use super::images::pick;
|
||||
use super::{fetch_limited, upload_limit};
|
||||
use crate::bail_user;
|
||||
use crate::cmd::{Command, Ctx, Opt, OptKind};
|
||||
use crate::state::State;
|
||||
use crate::ui::{escape, file_display, truncate, Card};
|
||||
use anyhow::Result;
|
||||
use futures::FutureExt;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
const MAX_MEDIA_BYTES: usize = 40 * 1024 * 1024;
|
||||
|
||||
fn height_label(h: u32) -> &'static str {
|
||||
match h {
|
||||
2160 => "4K",
|
||||
1440 => "2K",
|
||||
1080 => "Full HD",
|
||||
900 => "HD+",
|
||||
720 => "HD",
|
||||
576 => "PAL",
|
||||
480 => "SD",
|
||||
360 => "low",
|
||||
240 => "small",
|
||||
144 => "tiny",
|
||||
_ => "icon-sized",
|
||||
}
|
||||
}
|
||||
|
||||
fn kbps_label(k: u32) -> &'static str {
|
||||
match k {
|
||||
320 => "maximum",
|
||||
256 | 224 => "very high",
|
||||
192 => "high",
|
||||
160 | 128 => "standard",
|
||||
112 | 96 => "good for speech",
|
||||
_ => "small file",
|
||||
}
|
||||
}
|
||||
|
||||
fn media_type_of(siblings: &HashMap<String, String>) -> Option<MediaType> {
|
||||
siblings.get("type").and_then(|t| MediaType::parse(t)).or_else(|| siblings.get("format").and_then(|f| find_format(f, None)).map(|f| f.ty))
|
||||
}
|
||||
|
||||
/// What the dropdowns show: formats of the chosen type, and qualities that fit the type (and the format).
|
||||
async fn suggest(_: Arc<State>, option: String, typed: String, siblings: HashMap<String, String>) -> Vec<(String, String)> {
|
||||
let typed = typed.trim().to_lowercase();
|
||||
let ty = media_type_of(&siblings);
|
||||
match option.as_str() {
|
||||
"format" => {
|
||||
let list: Vec<&ffmpeg::Format> = match ty {
|
||||
Some(t) => formats_for(t),
|
||||
None => ffmpeg::FORMATS.iter().collect(),
|
||||
};
|
||||
list.into_iter()
|
||||
.filter(|f| typed.is_empty() || f.name.contains(&typed) || f.label.to_lowercase().contains(&typed))
|
||||
.map(|f| (if ty.is_some() { f.label.to_string() } else { format!("{} · {}", f.ty.name(), f.label) }, f.name.to_string()))
|
||||
.take(25)
|
||||
.collect()
|
||||
}
|
||||
"quality" => {
|
||||
let lossless = siblings.get("format").and_then(|f| find_format(f, ty)).is_some_and(|f| f.lossless);
|
||||
let mut out = vec![("Adaptive — best that fits Discord".to_string(), "adaptive".to_string())];
|
||||
if lossless && ty == Some(MediaType::Audio) {
|
||||
out = vec![("Lossless — no bitrate to pick".to_string(), "adaptive".to_string())];
|
||||
} else if ty == Some(MediaType::Audio) {
|
||||
out.extend(KBPS.iter().map(|k| (format!("{k} kbps — {}", kbps_label(*k)), format!("{k}k"))));
|
||||
} else {
|
||||
out.extend(HEIGHTS.iter().map(|h| (format!("{h}p — {}", height_label(*h)), format!("{h}p"))));
|
||||
}
|
||||
out.into_iter().filter(|(l, v)| typed.is_empty() || l.to_lowercase().contains(&typed) || v.contains(&typed)).take(25).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_list(ty: MediaType) -> String {
|
||||
formats_for(ty).iter().map(|f| f.name).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// Sizes in a sentence.
|
||||
fn mb(bytes: usize) -> String {
|
||||
if bytes >= 1024 * 1024 { format!("{:.1} MB", bytes as f64 / 1048576.0) } else { format!("{} KB", bytes.div_ceil(1024)) }
|
||||
}
|
||||
|
||||
async fn convert_cmd(ctx: Arc<Ctx>) -> Result<()> {
|
||||
let a = &ctx.args;
|
||||
let mut ty = a.str("type").and_then(MediaType::parse);
|
||||
let mut format = a.str("format").unwrap_or("").to_string();
|
||||
let mut quality_text = a.str("quality").unwrap_or("").to_string();
|
||||
let mut rest = a.str("rest").unwrap_or("").to_string();
|
||||
if !ctx.is_slash() {
|
||||
// `D!convert [type] <format> [quality] [link | @user]`
|
||||
let mut take = |rest: &mut String| -> Option<String> {
|
||||
let t = rest.trim_start().to_string();
|
||||
let (word, tail) = t.split_once(char::is_whitespace).unwrap_or((t.as_str(), ""));
|
||||
if word.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let w = word.to_string();
|
||||
*rest = tail.to_string();
|
||||
Some(w)
|
||||
};
|
||||
if let Some(t) = MediaType::parse(&format) {
|
||||
ty = Some(t);
|
||||
format = take(&mut rest).unwrap_or_default();
|
||||
}
|
||||
let peek = rest.trim_start().split_whitespace().next().unwrap_or("").to_string();
|
||||
if parse_quality(&peek).is_some() {
|
||||
quality_text = take(&mut rest).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
if format.is_empty() {
|
||||
bail_user!("Convert to what? Pick a type and a format — audio: {} · video: {} · image: {}.", format_list(MediaType::Audio), format_list(MediaType::Video), format_list(MediaType::Image));
|
||||
}
|
||||
let Some(fmt) = find_format(&format, ty) else {
|
||||
match ty {
|
||||
Some(t) => bail_user!("`{}` isn't an {} format. Try: {}.", escape(&truncate(&format, 30)), t.name(), format_list(t)),
|
||||
None => bail_user!("I don't know the format `{}`. Audio: {} · video: {} · image: {}.", escape(&truncate(&format, 30)), format_list(MediaType::Audio), format_list(MediaType::Video), format_list(MediaType::Image)),
|
||||
}
|
||||
};
|
||||
let quality = if quality_text.is_empty() {
|
||||
Quality::Adaptive
|
||||
} else {
|
||||
match parse_quality(&quality_text) {
|
||||
Some(q) => q,
|
||||
None => bail_user!("`{}` isn't a quality. Use `adaptive`, a height like `720p` (pictures and video) or a bitrate like `128k` (audio).", escape(&truncate(&quality_text, 20))),
|
||||
}
|
||||
};
|
||||
let (url, _) = pick(&ctx, &rest).await?;
|
||||
let limit = upload_limit(&ctx);
|
||||
ctx.defer().await?;
|
||||
let Some(data) = fetch_limited(&ctx.state, &url, MAX_MEDIA_BYTES).await else {
|
||||
bail_user!("I couldn't download that ({} MB max).", MAX_MEDIA_BYTES / 1024 / 1024);
|
||||
};
|
||||
let started = std::time::Instant::now();
|
||||
let Converted { bytes, ext, note } = match ffmpeg::convert_to(&data, fmt, quality, limit).await {
|
||||
Ok(c) => c,
|
||||
Err(e) => bail_user!("I couldn't convert that to **{}**: {}", fmt.name.to_uppercase(), escape(&truncate(&e, 200))),
|
||||
};
|
||||
let name = format!("converted.{ext}");
|
||||
let summary = format!("✅ Converted to **{}** · {} · {} · {:.1}s", fmt.name.to_uppercase(), note, mb(bytes.len()), started.elapsed().as_secs_f32());
|
||||
let shows = matches!(ext, "png" | "jpg" | "webp" | "gif" | "mp4" | "webm" | "mov");
|
||||
let card = if shows { Card::new(None).text(&summary).gallery(&[&format!("attachment://{name}")]) } else { Card::new(None).text(&summary).push(file_display(&name)) };
|
||||
ctx.reply_file(card.build(), &name, bytes).await
|
||||
}
|
||||
|
||||
pub fn commands() -> Vec<Command> {
|
||||
vec![Command::new("convert", "fun", "Convert any picture, video or audio to another format (pick a type, a format and a quality)", |c| convert_cmd(c).boxed())
|
||||
.aliases(&["conv"])
|
||||
.usage("[type] <format> [quality] [link | @user] (reply to or attach a file)")
|
||||
.opt(Opt::req("type", "What kind of file to make", OptKind::String).choices(&["image", "video", "audio"]).slash_only())
|
||||
.opt(Opt::req("format", "The format to make (the list depends on the type)", OptKind::String).autocomplete())
|
||||
.opt(Opt::opt("quality", "Adaptive, a height (1080p, 720p…) or an audio bitrate (320k, 128k…)", OptKind::String).autocomplete().slash_only())
|
||||
.opt(Opt::opt("rest", "Quality, then a link or @user (or attach / reply)", OptKind::String).prefix_only())
|
||||
.opt(Opt::opt("media", "The picture, GIF, video or audio to convert", OptKind::Attachment).slash_only())
|
||||
.opt(Opt::opt("user", "…or use someone's avatar", OptKind::User).slash_only())
|
||||
.opt(Opt::opt("url", "…or a link", OptKind::String).slash_only())
|
||||
.suggest_with(|_state, option, typed, siblings| suggest(_state, option, typed, siblings).boxed())]
|
||||
}
|
||||
|
|
@ -1,11 +1,9 @@
|
|||
//! Running ffmpeg, and the "convert anything to GIF / MP4 / WebM / PNG / JPG / WebP / MP3" job.
|
||||
//! Running ffmpeg, and the `/convert` job: any picture, clip or sound into any image, video or audio format.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::process::Command;
|
||||
|
||||
pub const TARGETS: [&str; 7] = ["gif", "mp4", "webm", "png", "jpg", "webp", "mp3"];
|
||||
|
||||
/// A scratch folder that deletes itself.
|
||||
pub struct Scratch(PathBuf);
|
||||
|
||||
|
|
@ -42,9 +40,6 @@ pub async fn run(args: &[String], limit: Duration) -> Result<(), String> {
|
|||
}
|
||||
}
|
||||
|
||||
fn s(v: &str) -> String {
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// What the input is, as far as converting is concerned.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
|
|
@ -66,32 +61,436 @@ pub fn kind_of(bytes: &[u8]) -> Kind {
|
|||
}
|
||||
}
|
||||
|
||||
/// Convert `input` bytes to `target`. Returns the file bytes. Tries smaller settings until it fits `limit`.
|
||||
pub async fn convert(input: &[u8], target: &str, limit: usize) -> Result<Vec<u8>, String> {
|
||||
// ---- /convert: type → format → quality --------------------------------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum MediaType {
|
||||
Image,
|
||||
Video,
|
||||
Audio,
|
||||
}
|
||||
|
||||
impl MediaType {
|
||||
pub fn parse(text: &str) -> Option<Self> {
|
||||
match text.trim().to_lowercase().as_str() {
|
||||
"image" | "picture" | "photo" | "img" => Some(Self::Image),
|
||||
"video" | "vid" | "clip" => Some(Self::Video),
|
||||
"audio" | "sound" | "music" => Some(Self::Audio),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Image => "image",
|
||||
Self::Video => "video",
|
||||
Self::Audio => "audio",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Format {
|
||||
pub name: &'static str,
|
||||
pub ext: &'static str,
|
||||
pub ty: MediaType,
|
||||
pub label: &'static str,
|
||||
/// quality (kbit/s) doesn't apply
|
||||
pub lossless: bool,
|
||||
}
|
||||
|
||||
const fn f(name: &'static str, ext: &'static str, ty: MediaType, label: &'static str, lossless: bool) -> Format {
|
||||
Format { name, ext, ty, label, lossless }
|
||||
}
|
||||
|
||||
use MediaType::{Audio, Image, Video};
|
||||
|
||||
pub const FORMATS: [Format; 38] = [
|
||||
f("png", "png", Image, "PNG — lossless", true),
|
||||
f("jpg", "jpg", Image, "JPG — small photos", false),
|
||||
f("webp", "webp", Image, "WebP — small, can animate", false),
|
||||
f("gif", "gif", Image, "GIF — animated pictures", false),
|
||||
f("avif", "avif", Image, "AVIF — very small", false),
|
||||
f("jxl", "jxl", Image, "JPEG XL", false),
|
||||
f("bmp", "bmp", Image, "BMP — raw bitmap", true),
|
||||
f("tiff", "tiff", Image, "TIFF — lossless", true),
|
||||
f("ico", "ico", Image, "ICO — icon (up to 256 px)", true),
|
||||
f("mp4", "mp4", Video, "MP4 — H.264, plays everywhere", false),
|
||||
f("webm", "webm", Video, "WebM — VP9", false),
|
||||
f("mkv", "mkv", Video, "MKV — H.264", false),
|
||||
f("mov", "mov", Video, "MOV — QuickTime", false),
|
||||
f("avi", "avi", Video, "AVI — old school", false),
|
||||
f("hevc", "mp4", Video, "HEVC / H.265 (in MP4)", false),
|
||||
f("av1", "mp4", Video, "AV1 (in MP4) — slow", false),
|
||||
f("wmv", "wmv", Video, "WMV — Windows Media", false),
|
||||
f("flv", "flv", Video, "FLV — Flash video", false),
|
||||
f("ogv", "ogv", Video, "OGV — Theora", false),
|
||||
f("mpeg", "mpg", Video, "MPEG-2", false),
|
||||
f("gif", "gif", Video, "GIF — animated, no sound", false),
|
||||
f("mp3", "mp3", Audio, "MP3", false),
|
||||
f("opus", "opus", Audio, "Opus — best quality per kbps", false),
|
||||
f("m4a", "m4a", Audio, "M4A — AAC", false),
|
||||
f("aac", "aac", Audio, "AAC (raw)", false),
|
||||
f("ogg", "ogg", Audio, "OGG — Vorbis", false),
|
||||
f("flac", "flac", Audio, "FLAC — lossless", true),
|
||||
f("alac", "m4a", Audio, "ALAC — Apple lossless (M4A)", true),
|
||||
f("wav", "wav", Audio, "WAV — uncompressed", true),
|
||||
f("aiff", "aiff", Audio, "AIFF — uncompressed", true),
|
||||
f("wma", "wma", Audio, "WMA — Windows Media", false),
|
||||
f("ac3", "ac3", Audio, "AC3 — Dolby Digital", false),
|
||||
f("mp2", "mp2", Audio, "MP2", false),
|
||||
f("amr", "amr", Audio, "AMR — phone voice", false),
|
||||
f("spx", "spx", Audio, "Speex — voice", false),
|
||||
f("mka", "mka", Audio, "MKA — Matroska audio (Opus)", false),
|
||||
f("webm", "weba", Audio, "WebM audio (Opus)", false),
|
||||
f("3ga", "3ga", Audio, "3GA — 3GP audio (AAC)", false),
|
||||
];
|
||||
|
||||
/// Heights offered for pictures and videos, and bitrates for audio.
|
||||
pub const HEIGHTS: [u32; 11] = [2160, 1440, 1080, 900, 720, 576, 480, 360, 240, 144, 96];
|
||||
pub const KBPS: [u32; 12] = [320, 256, 224, 192, 160, 128, 112, 96, 80, 64, 48, 32];
|
||||
|
||||
pub fn formats_for(ty: MediaType) -> Vec<&'static Format> {
|
||||
FORMATS.iter().filter(|f| f.ty == ty).collect()
|
||||
}
|
||||
|
||||
/// A format by name; `ty` picks between the video and audio WebM (and GIF between picture and clip).
|
||||
pub fn find_format(name: &str, ty: Option<MediaType>) -> Option<&'static Format> {
|
||||
let n = name.trim().trim_start_matches('.').to_lowercase();
|
||||
let n = match n.as_str() {
|
||||
"jpeg" | "jpe" => "jpg",
|
||||
"tif" => "tiff",
|
||||
"matroska" => "mkv",
|
||||
"mpg" | "mpeg2" => "mpeg",
|
||||
"h265" | "x265" => "hevc",
|
||||
"m4w" | "mp4a" | "aac-m4a" => "m4a",
|
||||
"vorbis" | "oga" => "ogg",
|
||||
"wave" => "wav",
|
||||
"aif" | "aifc" => "aiff",
|
||||
"weba" => "webm",
|
||||
"x264" | "h264" | "m4v" => "mp4",
|
||||
"jpegxl" => "jxl",
|
||||
other => other,
|
||||
}
|
||||
.to_string();
|
||||
let matching: Vec<&Format> = FORMATS.iter().filter(|f| f.name == n).collect();
|
||||
matching.iter().copied().find(|f| Some(f.ty) == ty).or_else(|| if ty.is_none() { matching.first().copied() } else { None })
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
pub enum Quality {
|
||||
/// pick the best that fits Discord's upload limit
|
||||
Adaptive,
|
||||
/// output height in pixels (pictures and video); smaller sources are upscaled
|
||||
Height(u32),
|
||||
/// kbit/s (audio)
|
||||
Kbps(u32),
|
||||
}
|
||||
|
||||
pub fn parse_quality(text: &str) -> Option<Quality> {
|
||||
let t = text.trim().to_lowercase().replace(' ', "");
|
||||
if matches!(t.as_str(), "adaptive" | "auto" | "best" | "original" | "default") {
|
||||
return Some(Quality::Adaptive);
|
||||
}
|
||||
if let Some(n) = t.strip_suffix('p').and_then(|n| n.parse::<u32>().ok()) {
|
||||
return (48..=4320).contains(&n).then_some(Quality::Height(n));
|
||||
}
|
||||
let k = t.strip_suffix("kbps").or_else(|| t.strip_suffix("kbit")).or_else(|| t.strip_suffix('k'))?;
|
||||
k.parse::<u32>().ok().filter(|n| (6..=640).contains(n)).map(Quality::Kbps)
|
||||
}
|
||||
|
||||
pub struct Converted {
|
||||
pub bytes: Vec<u8>,
|
||||
pub ext: &'static str,
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
struct Info {
|
||||
duration: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
video: bool,
|
||||
audio: bool,
|
||||
still: bool,
|
||||
}
|
||||
|
||||
async fn inspect(path: &Path, bytes: &[u8]) -> Info {
|
||||
let out = Command::new("ffprobe")
|
||||
.args(["-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height", "-of", "default=nw=1"])
|
||||
.arg(path)
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.await
|
||||
.ok();
|
||||
let text = out.map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default();
|
||||
let num = |key: &str| text.lines().find_map(|l| l.strip_prefix(key)?.parse::<f64>().ok()).unwrap_or(0.0);
|
||||
Info {
|
||||
duration: num("duration="),
|
||||
width: num("width=") as u32,
|
||||
height: num("height=") as u32,
|
||||
video: text.contains("codec_type=video"),
|
||||
audio: text.contains("codec_type=audio"),
|
||||
still: kind_of(bytes) == Kind::Still,
|
||||
}
|
||||
}
|
||||
|
||||
fn v(parts: &[&str]) -> Vec<String> {
|
||||
parts.iter().map(|p| p.to_string()).collect()
|
||||
}
|
||||
|
||||
/// The scale filter for a wanted height; upscaling uses Lanczos plus a touch of sharpening so it doesn't look soft.
|
||||
fn scale_to(height: Option<u32>, source_height: u32, even: bool) -> String {
|
||||
match height {
|
||||
Some(h) => {
|
||||
let h = if even { h - h % 2 } else { h };
|
||||
let mut f = format!("scale=-2:{h}:flags=lanczos+accurate_rnd+full_chroma_int");
|
||||
if source_height > 0 && h > source_height {
|
||||
f.push_str(",unsharp=5:5:0.6:5:5:0.0");
|
||||
}
|
||||
f
|
||||
}
|
||||
None if even => "scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string(),
|
||||
None => "null".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// One thing to try: ffmpeg's output options and what to tell the person.
|
||||
struct Attempt {
|
||||
args: Vec<String>,
|
||||
note: String,
|
||||
}
|
||||
|
||||
fn kbps_text(k: u32) -> String {
|
||||
format!("{k} kbps")
|
||||
}
|
||||
|
||||
/// Default bitrate when the person says "adaptive": good quality for the codec.
|
||||
fn default_kbps(fmt: &str) -> u32 {
|
||||
match fmt {
|
||||
"opus" | "mka" | "webm" => 128,
|
||||
"amr" => 12,
|
||||
"spx" => 32,
|
||||
"ogg" => 160,
|
||||
_ => 192,
|
||||
}
|
||||
}
|
||||
|
||||
fn audio_attempts(fmt: &Format, q: Quality, info: &Info, limit: usize) -> Vec<Attempt> {
|
||||
let encoder: &[&str] = match (fmt.name, fmt.ext) {
|
||||
("mp3", _) => &["-c:a", "libmp3lame"],
|
||||
("opus", _) | ("webm", _) | ("mka", _) => &["-c:a", "libopus", "-vbr", "on"],
|
||||
("m4a", _) | ("aac", _) | ("3ga", _) => &["-c:a", "aac"],
|
||||
("ogg", _) => &["-c:a", "libvorbis"],
|
||||
("wma", _) => &["-c:a", "wmav2"],
|
||||
("ac3", _) => &["-c:a", "ac3"],
|
||||
("mp2", _) => &["-c:a", "mp2"],
|
||||
("amr", _) => &["-c:a", "libopencore_amrnb", "-ar", "8000", "-ac", "1"],
|
||||
("spx", _) => &["-c:a", "libspeex", "-ar", "32000", "-ac", "1"],
|
||||
("flac", _) => &["-c:a", "flac", "-compression_level", "8"],
|
||||
("alac", _) => &["-c:a", "alac"],
|
||||
("wav", _) => &["-c:a", "pcm_s16le"],
|
||||
("aiff", _) => &["-c:a", "pcm_s16be"],
|
||||
_ => &["-c:a", "libmp3lame"],
|
||||
};
|
||||
let mut base = v(&["-vn", "-map", "0:a:0", "-map_metadata", "0", "-t", "3600"]);
|
||||
base.extend(encoder.iter().map(|s| s.to_string()));
|
||||
if fmt.lossless || fmt.name == "amr" {
|
||||
let note = format!("{} · lossless", fmt.name.to_uppercase());
|
||||
return vec![Attempt { args: base, note: if fmt.name == "amr" { "AMR · 12 kbps".to_string() } else { note } }];
|
||||
}
|
||||
let ceiling = match fmt.name {
|
||||
"ac3" => 640,
|
||||
"opus" | "webm" | "mka" => 510,
|
||||
"spx" => 44,
|
||||
_ => 320,
|
||||
};
|
||||
let seconds = if info.duration > 0.0 { info.duration.min(3600.0) } else { 240.0 };
|
||||
let max_fit = ((limit as f64 * 0.93 * 8.0 / 1000.0 / seconds).floor() as u32).max(1);
|
||||
let (wanted, adaptive) = match q {
|
||||
Quality::Kbps(k) => (k.min(ceiling), false),
|
||||
_ => (default_kbps(fmt.name).min(ceiling), true),
|
||||
};
|
||||
let ladder: Vec<u32> = if adaptive {
|
||||
// as close to the default as fits: the default, then every step down
|
||||
let mut all = vec![wanted];
|
||||
all.extend(KBPS.iter().copied().filter(|k| *k < wanted));
|
||||
let fitting: Vec<u32> = all.iter().copied().filter(|k| *k <= max_fit).collect();
|
||||
if fitting.is_empty() { all.last().copied().into_iter().collect() } else { fitting }
|
||||
} else {
|
||||
vec![wanted]
|
||||
};
|
||||
ladder
|
||||
.into_iter()
|
||||
.map(|k| {
|
||||
let mut args = base.clone();
|
||||
args.extend([s("-b:a"), format!("{k}k")]);
|
||||
let word = if adaptive { " (adaptive)" } else { "" };
|
||||
Attempt { args, note: format!("{} · {}{word}", fmt.name.to_uppercase(), kbps_text(k)) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn s(v: &str) -> String {
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
fn video_attempts(fmt: &Format, q: Quality, info: &Info) -> Vec<Attempt> {
|
||||
let height = match q {
|
||||
Quality::Height(h) => Some(h),
|
||||
_ => None,
|
||||
};
|
||||
// AV1 is slow to encode: a shorter clip keeps it from timing out
|
||||
let cap_secs: f64 = if info.still { 3.0 } else if fmt.name == "av1" { 60.0 } else { 180.0 };
|
||||
let cap = format!("{cap_secs}");
|
||||
let cut = if !info.still && info.duration > cap_secs { format!(" · first {} s", cap_secs as u32) } else { String::new() };
|
||||
// (settings label, crf-like value, adaptive height cap)
|
||||
let steps: Vec<(u32, Option<u32>)> = if height.is_some() { vec![(0, None), (1, None), (2, None)] } else { vec![(0, None), (1, Some(1080)), (2, Some(720)), (3, Some(480))] };
|
||||
let mut out = Vec::new();
|
||||
for (step, cap_h) in steps {
|
||||
let h = height.or(cap_h.filter(|c| info.height == 0 || *c < info.height));
|
||||
let (codec, extra): (&str, Vec<String>) = match fmt.name {
|
||||
"mp4" | "mkv" | "mov" => ("libx264", v(&["-preset", "veryfast", "-crf", &[23, 27, 31, 34][step as usize].to_string(), "-pix_fmt", "yuv420p"])),
|
||||
"hevc" => ("libx265", v(&["-preset", "veryfast", "-crf", &[26, 30, 34, 37][step as usize].to_string(), "-pix_fmt", "yuv420p", "-tag:v", "hvc1"])),
|
||||
"av1" => ("libaom-av1", v(&["-cpu-used", "8", "-row-mt", "1", "-b:v", "0", "-crf", &[38, 44, 50, 55][step as usize].to_string(), "-pix_fmt", "yuv420p"])),
|
||||
"webm" => ("libvpx-vp9", v(&["-crf", &[33, 38, 42, 46][step as usize].to_string(), "-b:v", "0", "-row-mt", "1", "-deadline", "realtime", "-cpu-used", "6", "-pix_fmt", "yuv420p"])),
|
||||
"avi" | "mpeg" => (if fmt.name == "avi" { "mpeg4" } else { "mpeg2video" }, v(&["-q:v", &[4, 8, 14, 20][step as usize].to_string(), "-pix_fmt", "yuv420p"])),
|
||||
"wmv" => ("wmv2", v(&["-q:v", &[4, 8, 14, 20][step as usize].to_string(), "-pix_fmt", "yuv420p"])),
|
||||
"flv" => ("flv", v(&["-q:v", &[4, 8, 14, 20][step as usize].to_string(), "-pix_fmt", "yuv420p"])),
|
||||
"ogv" => ("libtheora", v(&["-q:v", &[7, 5, 3, 2][step as usize].to_string(), "-pix_fmt", "yuv420p"])),
|
||||
_ => ("libx264", v(&["-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p"])),
|
||||
};
|
||||
let (acodec, aargs): (&str, Vec<String>) = match fmt.name {
|
||||
"webm" | "av1" => ("libopus", v(&["-b:a", "96k"])),
|
||||
"avi" | "flv" => ("libmp3lame", v(&["-b:a", "128k", "-ar", "44100"])),
|
||||
"wmv" => ("wmav2", v(&["-b:a", "128k"])),
|
||||
"ogv" => ("libvorbis", v(&["-q:a", "4"])),
|
||||
"mpeg" => ("mp2", v(&["-b:a", "192k", "-ar", "44100"])),
|
||||
_ => ("aac", v(&["-b:a", "128k"])),
|
||||
};
|
||||
let mut args = v(&["-t", &cap, "-map", "0:v:0", "-map", "0:a:0?", "-vf", &scale_to(h, info.height, true), "-c:v", codec]);
|
||||
args.extend(extra);
|
||||
args.extend([s("-c:a"), s(acodec)]);
|
||||
args.extend(aargs);
|
||||
if matches!(fmt.name, "mp4" | "mov" | "hevc" | "av1") {
|
||||
args.extend(v(&["-movflags", "+faststart"]));
|
||||
}
|
||||
let shown = h.or(Some(info.height).filter(|x| *x > 0)).map(|h| format!(" · {h}p")).unwrap_or_default();
|
||||
let how = match q {
|
||||
Quality::Height(_) => "",
|
||||
_ => " (adaptive)",
|
||||
};
|
||||
out.push(Attempt { args, note: format!("{}{shown}{how}{cut}", fmt.name.to_uppercase()) });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn gif_attempts(q: Quality, info: &Info) -> Vec<Attempt> {
|
||||
if info.still {
|
||||
let vf = format!("{},split[a][b];[a]palettegen[p];[b][p]paletteuse", scale_to(match q { Quality::Height(h) => Some(h), _ => None }, info.height, false).replace("null", "scale='min(1024,iw)':-2:flags=lanczos"));
|
||||
return vec![Attempt { args: vec![s("-frames:v"), s("1"), s("-vf"), vf, s("-loop"), s("0")], note: "GIF".into() }];
|
||||
}
|
||||
let heights: Vec<u32> = match q {
|
||||
Quality::Height(h) => vec![h, h * 3 / 4, h / 2, h / 3],
|
||||
_ => vec![360, 270, 200, 144],
|
||||
};
|
||||
[15, 12, 10, 8]
|
||||
.iter()
|
||||
.zip(heights)
|
||||
.map(|(fps, h)| {
|
||||
let vf = format!("fps={fps},{},split[a][b];[a]palettegen=max_colors=128:stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=4", scale_to(Some(h.max(48)), info.height, false));
|
||||
Attempt { args: vec![s("-t"), s("20"), s("-an"), s("-vf"), vf, s("-loop"), s("0")], note: format!("GIF · {h}p · {fps} fps") }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn image_attempts(fmt: &Format, q: Quality, info: &Info) -> Vec<Attempt> {
|
||||
let wanted = match q {
|
||||
Quality::Height(h) => Some(h),
|
||||
_ => None,
|
||||
};
|
||||
// adaptive = the original size first, smaller only if the file is too big
|
||||
let sizes: Vec<Option<u32>> = if wanted.is_some() { vec![wanted, wanted.map(|h| h * 3 / 4), wanted.map(|h| h / 2)] } else { vec![None, Some(2160), Some(1440), Some(1080), Some(720)] };
|
||||
let sizes: Vec<Option<u32>> = sizes.into_iter().filter(|h| h.is_none() || info.height == 0 || wanted.is_some() || h.unwrap_or(0) < info.height).collect();
|
||||
let moving = !info.still;
|
||||
let mut out = Vec::new();
|
||||
for (i, h) in sizes.iter().enumerate() {
|
||||
let vf = scale_to(*h, info.height, fmt.name == "avif" || fmt.name == "jxl");
|
||||
let vf = if fmt.name == "ico" {
|
||||
"scale='min(256,iw)':'min(256,ih)':force_original_aspect_ratio=decrease:flags=lanczos".to_string()
|
||||
} else {
|
||||
vf
|
||||
};
|
||||
let size_note = h.or(Some(info.height).filter(|x| *x > 0)).map(|h| format!(" · {h}p")).unwrap_or_default();
|
||||
let how = if wanted.is_some() { "" } else { " (adaptive)" };
|
||||
let mut args: Vec<String> = match fmt.name {
|
||||
"png" => v(&["-frames:v", "1"]),
|
||||
"jpg" => v(&["-frames:v", "1", "-q:v", &[2, 4, 7, 10, 14][i.min(4)].to_string(), "-pix_fmt", "yuvj420p"]),
|
||||
"webp" if moving => v(&["-t", "20", "-an", "-loop", "0", "-c:v", "libwebp", "-q:v", &[75, 60, 45, 30, 20][i.min(4)].to_string()]),
|
||||
"webp" => v(&["-frames:v", "1", "-c:v", "libwebp", "-q:v", &[88, 75, 60, 45, 30][i.min(4)].to_string()]),
|
||||
"avif" => v(&["-frames:v", "1", "-c:v", "libaom-av1", "-still-picture", "1", "-crf", &[28, 34, 40, 46, 50][i.min(4)].to_string(), "-cpu-used", "6", "-pix_fmt", "yuv420p"]),
|
||||
"jxl" => v(&["-frames:v", "1", "-c:v", "libjxl", "-distance", &["1.0", "2.0", "3.0", "4.5", "6.0"][i.min(4)].to_string()]),
|
||||
"bmp" => v(&["-frames:v", "1"]),
|
||||
"tiff" => v(&["-frames:v", "1"]),
|
||||
"ico" => v(&["-frames:v", "1"]),
|
||||
_ => v(&["-frames:v", "1"]),
|
||||
};
|
||||
args.extend([s("-vf"), vf]);
|
||||
out.push(Attempt { args, note: format!("{}{size_note}{how}", fmt.name.to_uppercase()) });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Convert `input` to the chosen format and quality. Tries smaller settings until it fits `limit`.
|
||||
pub async fn convert_to(input: &[u8], fmt: &Format, quality: Quality, limit: usize) -> Result<Converted, String> {
|
||||
let scratch = Scratch::new().map_err(|e| e.to_string())?;
|
||||
let src = scratch.path("input.bin");
|
||||
std::fs::write(&src, input).map_err(|e| e.to_string())?;
|
||||
let out = scratch.path(&format!("out.{target}"));
|
||||
let kind = kind_of(input);
|
||||
let out = scratch.path(&format!("out.{}", fmt.ext));
|
||||
let info = inspect(&src, input).await;
|
||||
match fmt.ty {
|
||||
Audio if !info.audio => return Err("that file has no sound to make audio from".into()),
|
||||
Video if !info.video => return Err("that file has no picture to make a video from".into()),
|
||||
Image if !info.video => return Err("that file has no picture to make an image from".into()),
|
||||
_ => {}
|
||||
}
|
||||
if matches!(quality, Quality::Kbps(_)) && fmt.ty != Audio {
|
||||
return Err("kbps only applies to audio — pick adaptive or a height like 720p".into());
|
||||
}
|
||||
if matches!(quality, Quality::Height(_)) && fmt.ty == Audio {
|
||||
return Err("a height only applies to pictures and video — pick adaptive or a bitrate like 128k".into());
|
||||
}
|
||||
let attempts = match fmt.ty {
|
||||
Audio => audio_attempts(fmt, quality, &info, limit),
|
||||
Video if fmt.name == "gif" => gif_attempts(quality, &info),
|
||||
Image if fmt.name == "gif" => gif_attempts(quality, &info),
|
||||
Video => video_attempts(fmt, quality, &info),
|
||||
Image => image_attempts(fmt, quality, &info),
|
||||
};
|
||||
let mut last_error = String::new();
|
||||
for attempt in attempts(target, kind) {
|
||||
for attempt in attempts {
|
||||
let mut args: Vec<String> = Vec::new();
|
||||
if kind == Kind::Still && matches!(target, "mp4" | "webm") {
|
||||
if info.still && fmt.ty == Video && fmt.name != "gif" {
|
||||
args.extend([s("-loop"), s("1")]);
|
||||
}
|
||||
args.extend([s("-i"), src.display().to_string()]);
|
||||
args.extend(attempt);
|
||||
args.extend(attempt.args);
|
||||
// extensions ffmpeg can't guess a container from
|
||||
match fmt.ext {
|
||||
"weba" => args.extend([s("-f"), s("webm")]),
|
||||
"3ga" => args.extend([s("-f"), s("3gp")]),
|
||||
"aac" => args.extend([s("-f"), s("adts")]),
|
||||
_ => {}
|
||||
}
|
||||
args.push(out.display().to_string());
|
||||
let _ = std::fs::remove_file(&out);
|
||||
match run(&args, Duration::from_secs(150)).await {
|
||||
match run(&args, Duration::from_secs(240)).await {
|
||||
Ok(()) => {
|
||||
let size = std::fs::metadata(&out).map(|m| m.len() as usize).unwrap_or(0);
|
||||
if size == 0 {
|
||||
last_error = "ffmpeg made an empty file".to_string();
|
||||
} else if size <= limit {
|
||||
return std::fs::read(&out).map_err(|e| e.to_string());
|
||||
let bytes = std::fs::read(&out).map_err(|e| e.to_string())?;
|
||||
return Ok(Converted { bytes, ext: fmt.ext, note: attempt.note });
|
||||
} else {
|
||||
last_error = format!("the result is too big for Discord ({} MB)", size / 1024 / 1024);
|
||||
last_error = format!("the result is too big for Discord ({} MB) — try a lower quality", size / 1024 / 1024);
|
||||
}
|
||||
}
|
||||
Err(e) => last_error = e,
|
||||
|
|
@ -100,35 +499,6 @@ pub async fn convert(input: &[u8], target: &str, limit: usize) -> Result<Vec<u8>
|
|||
Err(last_error)
|
||||
}
|
||||
|
||||
/// Output options per attempt: first the nice version, then smaller ones.
|
||||
fn attempts(target: &str, kind: Kind) -> Vec<Vec<String>> {
|
||||
let v = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::<Vec<_>>();
|
||||
match target {
|
||||
"gif" if kind == Kind::Still => vec![v(&["-frames:v", "1", "-vf", "scale='min(1024,iw)':-2:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse", "-loop", "0"])],
|
||||
"gif" => [(480, 15), (360, 12), (270, 10), (200, 8)]
|
||||
.iter()
|
||||
.map(|(w, f)| {
|
||||
let vf = format!("fps={f},scale='min({w},iw)':-2:flags=lanczos,split[a][b];[a]palettegen=max_colors=128:stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=4");
|
||||
vec![s("-t"), s("20"), s("-an"), s("-vf"), vf, s("-loop"), s("0")]
|
||||
})
|
||||
.collect(),
|
||||
"png" => vec![v(&["-frames:v", "1"])],
|
||||
"jpg" => vec![v(&["-frames:v", "1", "-q:v", "2"]), v(&["-frames:v", "1", "-q:v", "6", "-vf", "scale='min(1280,iw)':-2"])],
|
||||
"webp" if kind == Kind::Still => vec![v(&["-frames:v", "1", "-c:v", "libwebp", "-q:v", "85"])],
|
||||
"webp" => vec![v(&["-t", "20", "-an", "-vf", "fps=15,scale='min(480,iw)':-2", "-loop", "0", "-c:v", "libwebp", "-q:v", "70"]), v(&["-t", "12", "-an", "-vf", "fps=10,scale='min(320,iw)':-2", "-loop", "0", "-c:v", "libwebp", "-q:v", "50"])],
|
||||
"mp4" => [(23, "trunc(iw/2)*2:trunc(ih/2)*2"), (28, "'min(1280,iw)':-2"), (32, "'min(640,iw)':-2")]
|
||||
.iter()
|
||||
.map(|(crf, scale)| v(&["-t", if kind == Kind::Still { "3" } else { "180" }, "-c:v", "libx264", "-preset", "veryfast", "-crf", &crf.to_string(), "-pix_fmt", "yuv420p", "-vf", &format!("scale={scale}"), "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart"]))
|
||||
.collect(),
|
||||
"webm" => [(33, "iw:ih"), (40, "'min(854,iw)':-2")]
|
||||
.iter()
|
||||
.map(|(crf, scale)| v(&["-t", if kind == Kind::Still { "3" } else { "120" }, "-c:v", "libvpx-vp9", "-crf", &crf.to_string(), "-b:v", "0", "-row-mt", "1", "-deadline", "realtime", "-cpu-used", "6", "-pix_fmt", "yuv420p", "-vf", &format!("scale={scale}:force_divisible_by=2"), "-c:a", "libopus", "-b:a", "96k"]))
|
||||
.collect(),
|
||||
"mp3" => vec![v(&["-vn", "-t", "900", "-c:a", "libmp3lame", "-q:a", "2"]), v(&["-vn", "-t", "900", "-c:a", "libmp3lame", "-b:a", "96k"])],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extension(name: &str) -> Option<&str> {
|
||||
Path::new(name).extension().and_then(|e| e.to_str())
|
||||
}
|
||||
|
|
@ -161,17 +531,84 @@ mod tests {
|
|||
std::fs::read(p).unwrap()
|
||||
}
|
||||
|
||||
async fn height_of(bytes: &[u8], scratch: &Scratch, ext: &str) -> u32 {
|
||||
let p = scratch.path(&format!("check.{ext}"));
|
||||
std::fs::write(&p, bytes).unwrap();
|
||||
inspect(&p, bytes).await.height
|
||||
}
|
||||
|
||||
fn fmt(name: &str, ty: MediaType) -> &'static Format {
|
||||
find_format(name, Some(ty)).unwrap_or_else(|| panic!("no {name}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_and_qualities_parse() {
|
||||
assert_eq!(find_format("M4A", None).map(|f| f.name), Some("m4a"));
|
||||
assert_eq!(find_format("m4w", None).map(|f| f.name), Some("m4a"));
|
||||
assert_eq!(find_format(".JPEG", Some(Image)).map(|f| f.ext), Some("jpg"));
|
||||
assert_eq!(find_format("webm", Some(Audio)).map(|f| f.ext), Some("weba"));
|
||||
assert_eq!(find_format("webm", Some(Video)).map(|f| f.ext), Some("webm"));
|
||||
assert!(find_format("mp3", Some(Video)).is_none());
|
||||
assert_eq!(parse_quality("1080p"), Some(Quality::Height(1080)));
|
||||
assert_eq!(parse_quality("192k"), Some(Quality::Kbps(192)));
|
||||
assert_eq!(parse_quality("128 kbps"), Some(Quality::Kbps(128)));
|
||||
assert_eq!(parse_quality("Adaptive"), Some(Quality::Adaptive));
|
||||
assert_eq!(parse_quality("fast"), None);
|
||||
assert_eq!(MediaType::parse("Picture"), Some(Image));
|
||||
for ty in [Image, Video, Audio] {
|
||||
assert!(formats_for(ty).len() >= 9, "{}", ty.name());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn video_converts_to_every_target() {
|
||||
async fn every_audio_format_converts_and_bitrate_matters() {
|
||||
if !have_ffmpeg() {
|
||||
return;
|
||||
}
|
||||
let scratch = Scratch::new().unwrap();
|
||||
let video = sample_video(&scratch).await;
|
||||
for (target, magic) in [("gif", &b"GIF8"[..]), ("png", &b"\x89PNG"[..]), ("jpg", &b"\xff\xd8"[..]), ("webm", &b"\x1aE\xdf\xa3"[..]), ("mp3", &b""[..])] {
|
||||
let out = convert(&video, target, 10 * 1024 * 1024).await.unwrap_or_else(|e| panic!("{target}: {e}"));
|
||||
assert!(out.starts_with(magic) && out.len() > 500, "{target}");
|
||||
for f in formats_for(Audio) {
|
||||
let out = convert_to(&video, f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name));
|
||||
assert!(out.bytes.len() > 200 && out.ext == f.ext, "{}", f.name);
|
||||
}
|
||||
let low = convert_to(&video, fmt("mp3", Audio), Quality::Kbps(32), 20 << 20).await.unwrap();
|
||||
let high = convert_to(&video, fmt("mp3", Audio), Quality::Kbps(320), 20 << 20).await.unwrap();
|
||||
assert!(high.bytes.len() > low.bytes.len() * 3, "{} vs {}", high.bytes.len(), low.bytes.len());
|
||||
assert!(high.note.contains("320 kbps"), "{}", high.note);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_video_format_converts_and_heights_scale_both_ways() {
|
||||
if !have_ffmpeg() {
|
||||
return;
|
||||
}
|
||||
let scratch = Scratch::new().unwrap();
|
||||
let video = sample_video(&scratch).await;
|
||||
for f in formats_for(Video) {
|
||||
let out = convert_to(&video, f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name));
|
||||
assert!(out.bytes.len() > 500 && out.ext == f.ext, "{}", f.name);
|
||||
}
|
||||
let small = convert_to(&video, fmt("mp4", Video), Quality::Height(144), 20 << 20).await.unwrap();
|
||||
assert_eq!(height_of(&small.bytes, &scratch, "mp4").await, 144);
|
||||
let up = convert_to(&video, fmt("mp4", Video), Quality::Height(720), 20 << 20).await.unwrap();
|
||||
assert_eq!(height_of(&up.bytes, &scratch, "mp4").await, 720, "a 240p source is upscaled to 720p");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_image_format_converts_and_upscales() {
|
||||
if !have_ffmpeg() {
|
||||
return;
|
||||
}
|
||||
let scratch = Scratch::new().unwrap();
|
||||
let video = sample_video(&scratch).await;
|
||||
for f in formats_for(Image) {
|
||||
let out = convert_to(&video, f, Quality::Adaptive, 20 << 20).await.unwrap_or_else(|e| panic!("{} {e}", f.name));
|
||||
assert!(out.bytes.len() > 100 && out.ext == f.ext, "{}", f.name);
|
||||
}
|
||||
let png = convert_to(&video, fmt("png", Image), Quality::Adaptive, 20 << 20).await.unwrap();
|
||||
assert_eq!(kind_of(&png.bytes), Kind::Still);
|
||||
let big = convert_to(&png.bytes, fmt("jpg", Image), Quality::Height(900), 20 << 20).await.unwrap();
|
||||
assert_eq!(height_of(&big.bytes, &scratch, "jpg").await, 900);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
|
@ -181,28 +618,31 @@ mod tests {
|
|||
}
|
||||
let scratch = Scratch::new().unwrap();
|
||||
let video = sample_video(&scratch).await;
|
||||
let gif = convert(&video, "gif", 10 << 20).await.unwrap();
|
||||
assert_eq!(kind_of(&gif), Kind::Moving);
|
||||
let mp4 = convert(&gif, "mp4", 10 << 20).await.unwrap();
|
||||
assert_eq!(&mp4[4..8], b"ftyp");
|
||||
let png = convert(&video, "png", 10 << 20).await.unwrap();
|
||||
assert_eq!(kind_of(&png), Kind::Still);
|
||||
let clip = convert(&png, "mp4", 10 << 20).await.unwrap();
|
||||
assert_eq!(&clip[4..8], b"ftyp");
|
||||
let gif = convert_to(&video, fmt("gif", Video), Quality::Adaptive, 10 << 20).await.unwrap();
|
||||
assert_eq!(kind_of(&gif.bytes), Kind::Moving);
|
||||
let mp4 = convert_to(&gif.bytes, fmt("mp4", Video), Quality::Adaptive, 10 << 20).await.unwrap();
|
||||
assert_eq!(&mp4.bytes[4..8], b"ftyp");
|
||||
let png = convert_to(&video, fmt("png", Image), Quality::Adaptive, 10 << 20).await.unwrap();
|
||||
let clip = convert_to(&png.bytes, fmt("mp4", Video), Quality::Adaptive, 10 << 20).await.unwrap();
|
||||
let p = scratch.path("clip.mp4");
|
||||
std::fs::write(&p, &clip).unwrap();
|
||||
std::fs::write(&p, &clip.bytes).unwrap();
|
||||
let (duration, has_video) = probe(&p).await.unwrap();
|
||||
assert!(has_video && duration > 2.0 && duration < 4.5, "duration {duration}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn too_big_results_are_refused() {
|
||||
async fn wrong_combinations_and_too_big_results_are_refused() {
|
||||
if !have_ffmpeg() {
|
||||
return;
|
||||
}
|
||||
let scratch = Scratch::new().unwrap();
|
||||
let video = sample_video(&scratch).await;
|
||||
let err = convert(&video, "gif", 100).await.unwrap_err();
|
||||
let err = convert_to(&video, fmt("gif", Video), Quality::Adaptive, 100).await.err().unwrap();
|
||||
assert!(err.contains("too big"), "{err}");
|
||||
assert!(convert_to(&video, fmt("mp3", Audio), Quality::Height(720), 1 << 20).await.is_err());
|
||||
assert!(convert_to(&video, fmt("mp4", Video), Quality::Kbps(128), 1 << 20).await.is_err());
|
||||
let png = convert_to(&video, fmt("png", Image), Quality::Adaptive, 10 << 20).await.unwrap();
|
||||
let err = convert_to(&png.bytes, fmt("mp3", Audio), Quality::Adaptive, 1 << 20).await.err().unwrap();
|
||||
assert!(err.contains("no sound"), "{err}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,8 +4,7 @@
|
|||
//! The picture can come from an attachment, the message you reply to, someone's avatar (@mention /
|
||||
//! name), a custom emoji or a link; with nothing given, your own avatar is used. GIFs keep their
|
||||
//! animation. Everything is drawn in a worker thread at a sensible size, so a big GIF can't freeze the bot.
|
||||
use super::ffmpeg::{self, Kind};
|
||||
use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_limit, IMAGE_EXTS, VIDEO_EXTS};
|
||||
use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS};
|
||||
use crate::bail_user;
|
||||
use crate::cmd::{Command, Ctx, Opt, OptKind};
|
||||
use crate::converters::find_member;
|
||||
|
|
@ -25,7 +24,6 @@ const MAX_SIDE: u32 = 1024;
|
|||
const MAX_GIF_SIDE: u32 = 480;
|
||||
const MAX_FRAMES: usize = 120;
|
||||
const MAX_IMAGE_BYTES: usize = 15 * 1024 * 1024;
|
||||
const MAX_VIDEO_BYTES: usize = 40 * 1024 * 1024;
|
||||
|
||||
pub const EFFECTS: [&str; 10] = ["speechbubble", "caption", "blur", "pixelate", "flip", "mirror", "deepfry", "vignette", "border", "circle"];
|
||||
pub const FILTERS: [&str; 14] = [
|
||||
|
|
@ -321,10 +319,10 @@ pub fn squish_gif(bytes: &[u8]) -> Option<Vec<u8>> {
|
|||
// ---- finding the picture ----------------------------------------------------------------------
|
||||
|
||||
/// Where the media for a command comes from, and the words left over.
|
||||
async fn pick(ctx: &Ctx, text: &str) -> Result<(String, String)> {
|
||||
pub(super) async fn pick(ctx: &Ctx, text: &str) -> Result<(String, String)> {
|
||||
let state = &ctx.state;
|
||||
if ctx.is_slash() {
|
||||
if let Some(a) = ctx.args.id("image").and_then(|id| ctx.attachments.iter().find(|a| a.id.get() == id)) {
|
||||
if let Some(a) = ctx.args.id("media").and_then(|id| ctx.attachments.iter().find(|a| a.id.get() == id)) {
|
||||
return Ok((a.url.clone(), text.to_string()));
|
||||
}
|
||||
if let Some(u) = ctx.args.user("user") {
|
||||
|
|
@ -343,7 +341,7 @@ async fn pick(ctx: &Ctx, text: &str) -> Result<(String, String)> {
|
|||
}
|
||||
let reply = replied(ctx).await;
|
||||
if let Some(m) = &reply {
|
||||
if let Some(a) = m.attachments.iter().find(|a| has_ext(&a.filename, &IMAGE_EXTS) || has_ext(&a.filename, &VIDEO_EXTS)) {
|
||||
if let Some(a) = m.attachments.iter().find(|a| has_ext(&a.filename, &IMAGE_EXTS) || has_ext(&a.filename, &VIDEO_EXTS) || has_ext(&a.filename, &AUDIO_EXTS)) {
|
||||
return Ok((a.url.clone(), text.to_string()));
|
||||
}
|
||||
for e in &m.embeds {
|
||||
|
|
@ -381,7 +379,7 @@ async fn pick(ctx: &Ctx, text: &str) -> Result<(String, String)> {
|
|||
|
||||
// ---- /image, D!fx ------------------------------------------------------------------------------
|
||||
|
||||
fn resolve_name(name: &str) -> (Option<&'static str>, Option<&'static str>, Option<&'static str>) {
|
||||
fn resolve_name(name: &str) -> (Option<&'static str>, Option<&'static str>) {
|
||||
let n = name.to_lowercase().replace('-', "_");
|
||||
let n = match n.as_str() {
|
||||
"bubble" | "speech" => "speechbubble",
|
||||
|
|
@ -391,89 +389,66 @@ fn resolve_name(name: &str) -> (Option<&'static str>, Option<&'static str>, Opti
|
|||
"sketch" => "pencil_sketch",
|
||||
"oil" => "oil_painting",
|
||||
"popart" => "pop_art",
|
||||
"jpeg" => "jpg",
|
||||
other => other,
|
||||
}
|
||||
.to_string();
|
||||
(
|
||||
EFFECTS.iter().copied().find(|e| *e == n),
|
||||
FILTERS.iter().copied().find(|f| *f == n),
|
||||
ffmpeg::TARGETS.iter().copied().find(|t| *t == n),
|
||||
)
|
||||
(EFFECTS.iter().copied().find(|e| *e == n), FILTERS.iter().copied().find(|f| *f == n))
|
||||
}
|
||||
|
||||
/// Effects/filters first, then conversion: the shared job behind `/image`, `D!fx` and `/convert`.
|
||||
async fn run_job(ctx: &Arc<Ctx>, url: &str, effect: Option<&'static str>, filter: Option<&'static str>, target: Option<&'static str>, opts: Opts) -> Result<()> {
|
||||
/// Effects and filters on a picture or GIF: the shared job behind `/media` and `D!fx`.
|
||||
async fn run_job(ctx: &Arc<Ctx>, url: &str, effect: Option<&'static str>, filter: Option<&'static str>, opts: Opts) -> Result<()> {
|
||||
let limit = upload_limit(ctx);
|
||||
ctx.defer().await?;
|
||||
let cap = if target.is_some() { MAX_VIDEO_BYTES } else { MAX_IMAGE_BYTES };
|
||||
let Some(data) = fetch_limited(&ctx.state, url, cap).await else {
|
||||
bail_user!("I couldn't download that ({} MB max).", cap / 1024 / 1024);
|
||||
let Some(data) = fetch_limited(&ctx.state, url, MAX_IMAGE_BYTES).await else {
|
||||
bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024);
|
||||
};
|
||||
let mut bytes = data;
|
||||
let mut base = effect.or(filter).unwrap_or("image").to_string();
|
||||
let mut ext = "png";
|
||||
if effect.is_some() || filter.is_some() {
|
||||
if !matches!(image::guess_format(&bytes), Ok(image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::Gif | image::ImageFormat::WebP | image::ImageFormat::Bmp)) {
|
||||
bail_user!("Effects and filters work on pictures and GIFs. For a video, use the `convert` option on its own.");
|
||||
}
|
||||
let mut done = None;
|
||||
for side in [MAX_GIF_SIDE, 320, 220] {
|
||||
let (b, o) = (bytes.clone(), opts.clone());
|
||||
let result = tokio::task::spawn_blocking(move || process(&b, effect, filter, &o, side)).await?;
|
||||
let Some((out, e)) = result else { bail_user!("That doesn't look like a picture I can read.") };
|
||||
let fits = out.len() <= limit;
|
||||
done = Some((out, e));
|
||||
if fits || e == "png" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some((out, e)) = done else { bail_user!("That didn't work.") };
|
||||
bytes = out;
|
||||
ext = e;
|
||||
let bytes = data;
|
||||
let base = effect.or(filter).unwrap_or("image").to_string();
|
||||
if !matches!(image::guess_format(&bytes), Ok(image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::Gif | image::ImageFormat::WebP | image::ImageFormat::Bmp)) {
|
||||
bail_user!("Effects and filters work on pictures and GIFs. To change a file's format use `/convert`.");
|
||||
}
|
||||
if let Some(t) = target {
|
||||
bytes = match ffmpeg::convert(&bytes, t, limit).await {
|
||||
Ok(b) => b,
|
||||
Err(e) => bail_user!("I couldn't convert that to **{t}**: {}", escape(&truncate(&e, 200))),
|
||||
};
|
||||
ext = t;
|
||||
if effect.is_none() && filter.is_none() {
|
||||
base = "converted".to_string();
|
||||
let mut done = None;
|
||||
for side in [MAX_GIF_SIDE, 320, 220] {
|
||||
let (b, o) = (bytes.clone(), opts.clone());
|
||||
let result = tokio::task::spawn_blocking(move || process(&b, effect, filter, &o, side)).await?;
|
||||
let Some((out, e)) = result else { bail_user!("That doesn't look like a picture I can read.") };
|
||||
let fits = out.len() <= limit;
|
||||
done = Some((out, e));
|
||||
if fits || e == "png" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some((bytes, ext)) = done else { bail_user!("That didn't work.") };
|
||||
if bytes.len() > limit {
|
||||
bail_user!("The result is too big to upload ({} MB, the limit here is {} MB).", bytes.len() / 1024 / 1024, limit / 1024 / 1024);
|
||||
}
|
||||
let name = format!("{base}.{ext}");
|
||||
let card = if ext == "mp3" { Card::new(None).push(file_display(&name)).build() } else { Card::new(None).gallery(&[&format!("attachment://{name}")]).build() };
|
||||
ctx.reply_file(card, &name, bytes).await
|
||||
ctx.reply_file(Card::new(None).gallery(&[&format!("attachment://{name}")]).build(), &name, bytes).await
|
||||
}
|
||||
|
||||
async fn image_cmd(ctx: Arc<Ctx>) -> Result<()> {
|
||||
let a = &ctx.args;
|
||||
let mut opts = Opts::default();
|
||||
let (effect, filter, mut target, rest);
|
||||
let (effect, filter, rest);
|
||||
if ctx.is_slash() {
|
||||
effect = a.str("effect").and_then(|n| resolve_name(n).0);
|
||||
filter = a.str("filter").and_then(|n| resolve_name(n).1);
|
||||
target = a.str("convert").and_then(|n| resolve_name(n).2);
|
||||
opts.text = a.str("text").unwrap_or("").to_string();
|
||||
opts.bottom = a.str("bubble_position") == Some("bottom");
|
||||
opts.radius = a.int("blur_radius").unwrap_or(5).clamp(1, 20) as f32;
|
||||
opts.size = a.int("pixel_size").unwrap_or(10).clamp(2, 50) as u32;
|
||||
opts.level = a.int("deepfry_level").unwrap_or(3).clamp(1, 5) as u32;
|
||||
rest = String::new();
|
||||
if effect.is_none() && filter.is_none() && target.is_none() {
|
||||
bail_user!("Pick an `effect`, a `filter` or something to `convert` to.");
|
||||
if effect.is_none() && filter.is_none() {
|
||||
bail_user!("Pick an `effect` or a `filter`. To change a file's format use `/convert`.");
|
||||
}
|
||||
} else {
|
||||
let name = a.str("name").unwrap_or("");
|
||||
let (e, f, t) = resolve_name(name);
|
||||
if e.is_none() && f.is_none() && t.is_none() {
|
||||
bail_user!("`{}` isn't an effect, filter or format — see `{}help fx`.", escape(&truncate(name, 40)), ctx.state.prefix(ctx.guild_id));
|
||||
let (e, f) = resolve_name(name);
|
||||
if e.is_none() && f.is_none() {
|
||||
bail_user!("`{}` isn't an effect or filter — see `{}help fx`. To change a file's format use `{}convert`.", escape(&truncate(name, 40)), ctx.state.prefix(ctx.guild_id), ctx.state.prefix(ctx.guild_id));
|
||||
}
|
||||
(effect, filter, target) = (e, f, t);
|
||||
(effect, filter) = (e, f);
|
||||
rest = a.str("rest").unwrap_or("").to_string();
|
||||
}
|
||||
if effect == Some("caption") && ctx.is_slash() && opts.text.is_empty() {
|
||||
|
|
@ -493,20 +468,7 @@ async fn image_cmd(ctx: Arc<Ctx>) -> Result<()> {
|
|||
opts.level = n.clamp(1, 5) as u32;
|
||||
}
|
||||
}
|
||||
if effect.is_none() && filter.is_none() {
|
||||
target = target.or(Some("gif"));
|
||||
}
|
||||
run_job(&ctx, &url, effect, filter, target, opts).await
|
||||
}
|
||||
|
||||
async fn convert_cmd(ctx: Arc<Ctx>) -> Result<()> {
|
||||
let name = ctx.args.str("format").unwrap_or("");
|
||||
let Some(target) = resolve_name(name).2 else {
|
||||
bail_user!("Convert to what? One of: {}.", ffmpeg::TARGETS.join(", "));
|
||||
};
|
||||
let rest = ctx.args.str("source").unwrap_or("").to_string();
|
||||
let (url, _) = pick(&ctx, &rest).await?;
|
||||
run_job(&ctx, &url, None, None, Some(target), Opts::default()).await
|
||||
run_job(&ctx, &url, effect, filter, opts).await
|
||||
}
|
||||
|
||||
// ---- petpet ---------------------------------------------------------------------------------------
|
||||
|
|
@ -554,34 +516,25 @@ async fn petpet(ctx: Arc<Ctx>) -> Result<()> {
|
|||
}
|
||||
|
||||
pub fn commands() -> Vec<Command> {
|
||||
let fx_help = format!("Edit a picture or GIF: reply to one, attach one, or give a @user / link / emoji (default: your avatar). Effects: {}. Filters: {}. Or a format to convert to: {}.", EFFECTS.join(", "), FILTERS.join(", "), ffmpeg::TARGETS.join(", "));
|
||||
let fx_help = format!("Edit a picture or GIF: reply to one, attach one, or give a @user / link / emoji (default: your avatar). Effects: {}. Filters: {}. To change a file's format use `convert`.", EFFECTS.join(", "), FILTERS.join(", "));
|
||||
let fx_help: &'static str = Box::leak(fx_help.into_boxed_str());
|
||||
vec![
|
||||
Command::new("fx", "fun", fx_help, |c| image_cmd(c).boxed())
|
||||
.aliases(&["effect", "filter", "imagefx"])
|
||||
.slash_as("image")
|
||||
.usage("<effect | filter | format> [text]")
|
||||
.opt(Opt::opt("name", "Effect, filter or format", OptKind::String).prefix_only())
|
||||
.slash_as("media")
|
||||
.usage("<effect | filter> [text]")
|
||||
.opt(Opt::opt("name", "Effect or filter", OptKind::String).prefix_only())
|
||||
.opt(Opt::opt("rest", "Text, a link, a @user…", OptKind::String).prefix_only())
|
||||
.opt(Opt::opt("image", "An image, GIF or video to edit", OptKind::Attachment).slash_only())
|
||||
.opt(Opt::opt("media", "A picture or GIF to edit", OptKind::Attachment).slash_only())
|
||||
.opt(Opt::opt("user", "…or use someone's avatar", OptKind::User).slash_only())
|
||||
.opt(Opt::opt("url", "…or a link", OptKind::String).slash_only())
|
||||
.opt(Opt::opt("effect", "Speech bubble, caption, blur, deepfry…", OptKind::String).choices(&EFFECTS).slash_only())
|
||||
.opt(Opt::opt("filter", "Colour filter: sepia, gotham, cyberpunk…", OptKind::String).choices(&FILTERS).slash_only())
|
||||
.opt(Opt::opt("convert", "Turn it into a GIF, MP4, WebM, PNG, JPG, WebP or MP3", OptKind::String).choices(&ffmpeg::TARGETS).slash_only())
|
||||
.opt(Opt::opt("text", "Text for the caption effect", OptKind::String).slash_only())
|
||||
.opt(Opt::opt("bubble_position", "Where the speech bubble goes", OptKind::String).choices(&["top", "bottom"]).slash_only())
|
||||
.opt(Opt::opt("blur_radius", "Blur strength (1–20)", OptKind::Integer).range(1, 20).slash_only())
|
||||
.opt(Opt::opt("pixel_size", "Pixelate block size (2–50)", OptKind::Integer).range(2, 50).slash_only())
|
||||
.opt(Opt::opt("deepfry_level", "Deepfry strength (1–5)", OptKind::Integer).range(1, 5).slash_only()),
|
||||
Command::new("convert", "fun", "Convert a picture, GIF or video to GIF, MP4, WebM, PNG, JPG, WebP or MP3", |c| convert_cmd(c).boxed())
|
||||
.aliases(&["conv"])
|
||||
.usage("<format> [link | @user] (or reply to / attach a file)")
|
||||
.opt(Opt::req("format", "What to turn it into", OptKind::String).choices(&ffmpeg::TARGETS))
|
||||
.opt(Opt::opt("source", "A link, @user or emoji (or attach / reply)", OptKind::String).prefix_only())
|
||||
.opt(Opt::opt("image", "A picture, GIF or video", OptKind::Attachment).slash_only())
|
||||
.opt(Opt::opt("user", "…or use someone's avatar", OptKind::User).slash_only())
|
||||
.opt(Opt::opt("url", "…or a link", OptKind::String).slash_only()),
|
||||
Command::new("petpet", "fun", "Petpet GIF of someone's avatar or a custom emoji (reply to a message for its author)", |c| petpet(c).boxed())
|
||||
.aliases(&["patpat", "pet"])
|
||||
.usage("[@user | emoji]")
|
||||
|
|
@ -622,8 +575,7 @@ mod tests {
|
|||
assert_eq!(resolve_name("Pencil-Sketch").1, Some("pencil_sketch"));
|
||||
assert_eq!(resolve_name("bw").1, Some("grayscale"));
|
||||
assert_eq!(resolve_name("fry").0, Some("deepfry"));
|
||||
assert_eq!(resolve_name("jpeg").2, Some("jpg"));
|
||||
assert_eq!(resolve_name("nonsense"), (None, None, None));
|
||||
assert_eq!(resolve_name("nonsense"), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ use twilight_model::channel::Message;
|
|||
use twilight_model::id::marker::UserMarker;
|
||||
use twilight_model::id::Id;
|
||||
|
||||
pub mod convert;
|
||||
pub mod download;
|
||||
pub mod emoji;
|
||||
pub mod ffmpeg;
|
||||
|
|
@ -17,6 +18,7 @@ pub fn commands() -> Vec<Command> {
|
|||
let mut v = Vec::new();
|
||||
v.extend(quote::commands());
|
||||
v.extend(images::commands());
|
||||
v.extend(convert::commands());
|
||||
v.extend(emoji::commands());
|
||||
v.extend(download::commands());
|
||||
v
|
||||
|
|
@ -75,6 +77,7 @@ pub async fn replied(ctx: &Ctx) -> Option<Message> {
|
|||
|
||||
/// File name extensions we treat as pictures / videos.
|
||||
pub const IMAGE_EXTS: [&str; 6] = ["png", "jpg", "jpeg", "gif", "webp", "bmp"];
|
||||
pub const AUDIO_EXTS: [&str; 16] = ["mp3", "wav", "ogg", "opus", "m4a", "aac", "flac", "wma", "aiff", "aif", "ac3", "mp2", "amr", "spx", "mka", "weba"];
|
||||
pub const VIDEO_EXTS: [&str; 9] = ["mp4", "mov", "webm", "mkv", "avi", "m4v", "mpeg", "mpg", "ogv"];
|
||||
|
||||
pub fn has_ext(name: &str, list: &[&str]) -> bool {
|
||||
|
|
|
|||
20
src/main.rs
20
src/main.rs
|
|
@ -364,14 +364,30 @@ async fn on_autocomplete(state: Arc<State>, i: twilight_model::application::inte
|
|||
use twilight_model::application::command::{CommandOptionChoice, CommandOptionChoiceValue};
|
||||
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseData, InteractionResponseType};
|
||||
let Some(InteractionData::ApplicationCommand(data)) = i.data.as_ref() else { return };
|
||||
let Some(suggest) = state.registry.find_slash(&data.name).and_then(|c| c.suggest) else { return };
|
||||
let Some(command) = state.registry.find_slash(&data.name) else { return };
|
||||
let (suggest, suggest_with) = (command.suggest, command.suggest_with);
|
||||
if suggest.is_none() && suggest_with.is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(user) = i.author() else { return };
|
||||
let focused = data.options.iter().find_map(|o| match &o.value {
|
||||
CommandOptionValue::Focused(text, _) => Some((o.name.clone(), text.clone())),
|
||||
_ => None,
|
||||
});
|
||||
let Some((name, text)) = focused else { return };
|
||||
let found = tokio::time::timeout(Duration::from_millis(2500), suggest(state.clone(), name, text, i.guild_id, user.id)).await.unwrap_or_default();
|
||||
let siblings: std::collections::HashMap<String, String> = data
|
||||
.options
|
||||
.iter()
|
||||
.filter_map(|o| match &o.value {
|
||||
CommandOptionValue::String(v) => Some((o.name.clone(), v.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let found = match (suggest_with, suggest) {
|
||||
(Some(f), _) => tokio::time::timeout(Duration::from_millis(2500), f(state.clone(), name, text, siblings)).await.unwrap_or_default(),
|
||||
(None, Some(f)) => tokio::time::timeout(Duration::from_millis(2500), f(state.clone(), name, text, i.guild_id, user.id)).await.unwrap_or_default(),
|
||||
(None, None) => return,
|
||||
};
|
||||
let choices: Vec<CommandOptionChoice> = found
|
||||
.into_iter()
|
||||
.take(25)
|
||||
|
|
|
|||
Loading…
Reference in a new issue