/convert: type is the kind of file; the output list adapts to what it can become
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
parent
cf55ca8e6d
commit
07a5ae4fdf
2 changed files with 72 additions and 33 deletions
|
|
@ -1,11 +1,13 @@
|
|||
//! `/convert` · `D!convert` — turn any picture, clip or sound into any image, video or audio format.
|
||||
//!
|
||||
//! `/convert type:image file:<file> output:gif quality:720p` — the slash command asks for a **type** (image / video / audio), then an **output** format that depends on it (as you type
|
||||
//! `/convert type:video file:<file> output:gif quality:720p` — the **type** is what you are converting (image / video /
|
||||
//! audio) and the **output** list adapts to it: a picture or GIF can become another picture format or a clip, a video can
|
||||
//! become a clip, a GIF or picture, or just its sound, and sound stays sound (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::ffmpeg::{self, find_format, parse_quality, Converted, MediaType, Quality, HEIGHTS, KBPS};
|
||||
use super::images::pick;
|
||||
use super::{fetch_limited, upload_limit};
|
||||
use crate::bail_user;
|
||||
|
|
@ -46,44 +48,56 @@ fn kbps_label(k: u32) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
fn media_type_of(siblings: &HashMap<String, String>) -> Option<MediaType> {
|
||||
siblings.get("type").and_then(|t| MediaType::parse(t)).or_else(|| siblings.get("output").and_then(|f| find_format(f, None)).map(|f| f.ty))
|
||||
/// The kind of file being converted, from the `type` option (or from the output format typed so far).
|
||||
fn input_type(siblings: &HashMap<String, String>) -> Option<MediaType> {
|
||||
siblings.get("type").and_then(|t| MediaType::parse(t))
|
||||
}
|
||||
|
||||
/// What the dropdowns show: formats of the chosen type, and qualities that fit the type (and the format).
|
||||
/// Each output with a small tag, so a mixed list reads clearly.
|
||||
fn tagged(f: &ffmpeg::Format) -> String {
|
||||
let tag = match f.ty {
|
||||
MediaType::Image => "🖼️",
|
||||
MediaType::Video => "🎬",
|
||||
MediaType::Audio => "🎵",
|
||||
};
|
||||
format!("{tag} {}", f.label)
|
||||
}
|
||||
|
||||
/// What the dropdowns show: the outputs this kind of file can become, and qualities that fit the output.
|
||||
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);
|
||||
let input = input_type(&siblings);
|
||||
match option.as_str() {
|
||||
"output" => {
|
||||
let list: Vec<&ffmpeg::Format> = match ty {
|
||||
Some(t) => formats_for(t),
|
||||
let list: Vec<&ffmpeg::Format> = match input {
|
||||
Some(t) => ffmpeg::outputs_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()))
|
||||
.map(|f| (tagged(f), f.name.to_string()))
|
||||
.take(25)
|
||||
.collect()
|
||||
}
|
||||
"quality" => {
|
||||
let lossless = siblings.get("output").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"))));
|
||||
let out = siblings.get("output").and_then(|f| find_format(f, None));
|
||||
let kind = out.map(|f| f.ty).or(input);
|
||||
let mut list = vec![("Adaptive — best that fits Discord".to_string(), "adaptive".to_string())];
|
||||
if out.is_some_and(|f| f.lossless) && kind == Some(MediaType::Audio) {
|
||||
list = vec![("Lossless — no bitrate to pick".to_string(), "adaptive".to_string())];
|
||||
} else if kind == Some(MediaType::Audio) {
|
||||
list.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"))));
|
||||
list.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()
|
||||
list.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(", ")
|
||||
ffmpeg::outputs_for(ty).iter().map(|f| f.name).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// Sizes in a sentence.
|
||||
|
|
@ -121,12 +135,15 @@ async fn convert_cmd(ctx: Arc<Ctx>) -> Result<()> {
|
|||
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 {
|
||||
let Some(fmt) = find_format(&format, None) else {
|
||||
match ty {
|
||||
Some(t) => bail_user!("`{}` isn't an {} format. Try: {}.", escape(&truncate(&format, 30)), t.name(), format_list(t)),
|
||||
Some(t) => bail_user!("I don't know `{}`. A {} can become: {}.", 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)),
|
||||
}
|
||||
};
|
||||
if let Some(t) = ty.filter(|t| !ffmpeg::outputs_for(*t).iter().any(|f| f.name == fmt.name)) {
|
||||
bail_user!("A {} can't become **{}**. It can become: {}.", t.name(), fmt.name.to_uppercase(), format_list(t));
|
||||
}
|
||||
let quality = if quality_text.is_empty() {
|
||||
Quality::Adaptive
|
||||
} else {
|
||||
|
|
@ -157,8 +174,8 @@ 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] <output> [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("output", "The format to make (the list depends on the type)", OptKind::String).autocomplete())
|
||||
.opt(Opt::req("type", "What kind of file you are converting (the outputs adapt to it)", OptKind::String).choices(&["image", "video", "audio"]).slash_only())
|
||||
.opt(Opt::req("output", "The format to make — the list shows what that kind of file can become", 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("file", "The picture, GIF, video or audio to convert", OptKind::Attachment).slash_only())
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ const fn f(name: &'static str, ext: &'static str, ty: MediaType, label: &'static
|
|||
|
||||
use MediaType::{Audio, Image, Video};
|
||||
|
||||
pub const FORMATS: [Format; 38] = [
|
||||
pub const FORMATS: [Format; 37] = [
|
||||
f("png", "png", Image, "PNG — lossless", true),
|
||||
f("jpg", "jpg", Image, "JPG — small photos", false),
|
||||
f("webp", "webp", Image, "WebP — small, can animate", false),
|
||||
|
|
@ -124,7 +124,6 @@ pub const FORMATS: [Format; 38] = [
|
|||
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),
|
||||
|
|
@ -140,7 +139,7 @@ pub const FORMATS: [Format; 38] = [
|
|||
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("weba", "weba", Audio, "WebM audio (Opus)", false),
|
||||
f("3ga", "3ga", Audio, "3GA — 3GP audio (AAC)", false),
|
||||
];
|
||||
|
||||
|
|
@ -152,7 +151,21 @@ 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).
|
||||
/// What a file of this kind can be turned into, most useful first: a picture or a GIF can become any picture format
|
||||
/// or a clip; a video can become a clip, a GIF or picture, or just its sound; sound stays sound.
|
||||
pub fn outputs_for(input: MediaType) -> Vec<&'static Format> {
|
||||
let order: &[&str] = match input {
|
||||
Image => &["png", "jpg", "webp", "gif", "avif", "jxl", "bmp", "tiff", "ico", "mp4", "webm", "mkv", "mov", "avi", "hevc", "av1", "wmv", "flv", "ogv", "mpeg"],
|
||||
Video => &[
|
||||
"mp4", "webm", "mkv", "mov", "avi", "gif", "mp3", "opus", "m4a", "ogg", "flac", "wav", "aac", "hevc", "av1", "wmv", "flv", "ogv", "mpeg", "wma", "ac3", "png", "jpg", "webp", "avif", "jxl", "bmp", "tiff", "ico", "mp2", "alac", "aiff", "amr",
|
||||
"spx", "mka", "weba", "3ga",
|
||||
],
|
||||
Audio => &["mp3", "opus", "m4a", "ogg", "flac", "wav", "aac", "alac", "aiff", "wma", "ac3", "mp2", "weba", "mka", "3ga", "amr", "spx"],
|
||||
};
|
||||
order.iter().filter_map(|n| FORMATS.iter().find(|f| f.name == *n)).collect()
|
||||
}
|
||||
|
||||
/// A format by name; `ty` (when given) must match its kind.
|
||||
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() {
|
||||
|
|
@ -165,7 +178,6 @@ pub fn find_format(name: &str, ty: Option<MediaType>) -> Option<&'static Format>
|
|||
"vorbis" | "oga" => "ogg",
|
||||
"wave" => "wav",
|
||||
"aif" | "aifc" => "aiff",
|
||||
"weba" => "webm",
|
||||
"x264" | "h264" | "m4v" => "mp4",
|
||||
"jpegxl" => "jxl",
|
||||
other => other,
|
||||
|
|
@ -265,7 +277,7 @@ fn kbps_text(k: u32) -> String {
|
|||
/// Default bitrate when the person says "adaptive": good quality for the codec.
|
||||
fn default_kbps(fmt: &str) -> u32 {
|
||||
match fmt {
|
||||
"opus" | "mka" | "webm" => 128,
|
||||
"opus" | "mka" | "weba" => 128,
|
||||
"amr" => 12,
|
||||
"spx" => 32,
|
||||
"ogg" => 160,
|
||||
|
|
@ -276,7 +288,7 @@ fn default_kbps(fmt: &str) -> u32 {
|
|||
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"],
|
||||
("opus", _) | ("weba", _) | ("mka", _) => &["-c:a", "libopus", "-vbr", "on"],
|
||||
("m4a", _) | ("aac", _) | ("3ga", _) => &["-c:a", "aac"],
|
||||
("ogg", _) => &["-c:a", "libvorbis"],
|
||||
("wma", _) => &["-c:a", "wmav2"],
|
||||
|
|
@ -298,7 +310,7 @@ fn audio_attempts(fmt: &Format, q: Quality, info: &Info, limit: usize) -> Vec<At
|
|||
}
|
||||
let ceiling = match fmt.name {
|
||||
"ac3" => 640,
|
||||
"opus" | "webm" | "mka" => 510,
|
||||
"opus" | "weba" | "mka" => 510,
|
||||
"spx" => 44,
|
||||
_ => 320,
|
||||
};
|
||||
|
|
@ -546,8 +558,18 @@ mod tests {
|
|||
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("weba", Some(Audio)).map(|f| f.ext), Some("weba"));
|
||||
assert!(find_format("webm", Some(Audio)).is_none());
|
||||
assert_eq!(find_format("webm", Some(Video)).map(|f| f.ext), Some("webm"));
|
||||
assert_eq!(find_format("gif", None).map(|f| f.ty), Some(Image));
|
||||
// the list adapts to what you have: a GIF/picture can become a clip, a clip can become sound, sound only sound
|
||||
let has = |input: MediaType, name: &str| outputs_for(input).iter().any(|f| f.name == name);
|
||||
assert!(has(Image, "mp4") && has(Image, "gif") && !has(Image, "mp3"));
|
||||
assert!(has(Video, "gif") && has(Video, "mp3") && has(Video, "png") && has(Video, "mp4"));
|
||||
assert!(has(Audio, "opus") && !has(Audio, "mp4") && !has(Audio, "gif"));
|
||||
for ty in [Image, Video, Audio] {
|
||||
assert_eq!(outputs_for(ty).len(), outputs_for(ty).iter().map(|f| f.name).collect::<std::collections::HashSet<_>>().len());
|
||||
}
|
||||
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)));
|
||||
|
|
@ -618,7 +640,7 @@ mod tests {
|
|||
}
|
||||
let scratch = Scratch::new().unwrap();
|
||||
let video = sample_video(&scratch).await;
|
||||
let gif = convert_to(&video, fmt("gif", Video), Quality::Adaptive, 10 << 20).await.unwrap();
|
||||
let gif = convert_to(&video, fmt("gif", Image), 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");
|
||||
|
|
@ -637,7 +659,7 @@ mod tests {
|
|||
}
|
||||
let scratch = Scratch::new().unwrap();
|
||||
let video = sample_video(&scratch).await;
|
||||
let err = convert_to(&video, fmt("gif", Video), Quality::Adaptive, 100).await.err().unwrap();
|
||||
let err = convert_to(&video, fmt("gif", Image), 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());
|
||||
|
|
|
|||
Loading…
Reference in a new issue