diff --git a/Cargo.toml b/Cargo.toml index 91a7830..0e809e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,6 @@ rust-version = "1.89" description = "Free Media Xpress (FMX) - A lightweight, fast all-in-one media, document and disc converter with a clean GUI" license = "MIT OR Apache-2.0" repository = "https://github.com/sudo-py-dev/fmx" -homepage = "https://github.com/sudo-py-dev/fmx" [dependencies] calamine = "0.38.0" diff --git a/locales/de.json b/locales/de.json index faf3240..96d56e9 100644 --- a/locales/de.json +++ b/locales/de.json @@ -602,6 +602,22 @@ "preset.deleted": "Voreinstellung „{name}“ gelöscht", "preset.missing": "Diese Voreinstellung gibt es nicht mehr.", "preset.max_side": "bis {px} px", + "image_preset.row": "Format-Voreinstellung", + "image_preset.none": "Nicht festgelegt: Qualität und Größe unten werden verwendet", + "image_preset.configure": "Voreinstellung festlegen", + "image_preset.title": "{format}-Voreinstellung", + "image_preset.hint": "Wird bei jeder Umwandlung in {format} anstelle der allgemeinen Qualität und Größe verwendet.", + "image_preset.lossless": "{format} ist verlustfrei, daher lässt sich nur die Breite festlegen. Wird bei jeder Umwandlung in {format} verwendet.", + "image_preset.no_encoder": "Die {format}-Qualität braucht ffmpeg, das nicht gefunden wurde. {format} wird daher verlustfrei gespeichert, und nur die Breite lässt sich festlegen.", + "image_preset.quality_hint": "Höher behält mehr Details, niedriger ergibt kleinere Dateien", + "image_preset.max_width": "Maximale Breite", + "image_preset.max_width_hint": "Breitere Bilder werden verkleinert, kleinere nie vergrößert", + "image_preset.summary": "Qualität {quality} · {width}", + "image_preset.width_px": "bis {px} px breit", + "image_preset.original_width": "Originalbreite", + "image_preset.remove": "Voreinstellung entfernen", + "image_preset.saved": "{format}-Voreinstellung gespeichert", + "image_preset.removed": "{format}-Voreinstellung entfernt", "settings.install_program": "Installation / Download", "settings.install_hint": "Optionale Programme über die folgenden Links installieren. Die Befehlszeilenwerkzeuge zum PATH hinzufügen und erneut suchen. Ausführbare Dateien können auch in tools/bin neben fmx abgelegt werden.", "welcome.title": "Willkommen bei FMX", diff --git a/locales/en.json b/locales/en.json index ff02004..829ef18 100644 --- a/locales/en.json +++ b/locales/en.json @@ -602,6 +602,22 @@ "preset.deleted": "Preset “{name}” deleted", "preset.missing": "That preset no longer exists.", "preset.max_side": "up to {px} px", + "image_preset.row": "Format preset", + "image_preset.none": "Not set: the quality and size below are used", + "image_preset.configure": "Configure preset", + "image_preset.title": "{format} preset", + "image_preset.hint": "Used every time an image is converted to {format}, in place of the shared quality and size.", + "image_preset.lossless": "{format} is lossless, so only the width can be set. Used every time an image is converted to {format}.", + "image_preset.no_encoder": "{format} quality needs ffmpeg, which wasn’t found, so {format} is saved lossless and only the width can be set.", + "image_preset.quality_hint": "Higher keeps more detail; lower makes smaller files", + "image_preset.max_width": "Max width", + "image_preset.max_width_hint": "Wider images are scaled down; smaller ones are never enlarged", + "image_preset.summary": "Quality {quality} · {width}", + "image_preset.width_px": "up to {px} px wide", + "image_preset.original_width": "original width", + "image_preset.remove": "Remove preset", + "image_preset.saved": "{format} preset saved", + "image_preset.removed": "{format} preset removed", "settings.install_program": "Installation / download", "settings.install_hint": "Install optional programs using the links below. Make their command-line tools available on PATH, then click Rescan. You can also place executables in tools/bin beside fmx.", "welcome.title": "Welcome to FMX", diff --git a/locales/es.json b/locales/es.json index e34a070..60c0c11 100644 --- a/locales/es.json +++ b/locales/es.json @@ -602,6 +602,22 @@ "preset.deleted": "Ajuste «{name}» eliminado", "preset.missing": "Ese ajuste ya no existe.", "preset.max_side": "hasta {px} px", + "image_preset.row": "Ajuste del formato", + "image_preset.none": "Sin definir: se usan la calidad y el tamaño de abajo", + "image_preset.configure": "Configurar ajuste", + "image_preset.title": "Ajuste de {format}", + "image_preset.hint": "Se usa cada vez que una imagen se convierte a {format}, en lugar de la calidad y el tamaño generales.", + "image_preset.lossless": "{format} no tiene pérdida, así que solo se puede fijar el ancho. Se usa cada vez que una imagen se convierte a {format}.", + "image_preset.no_encoder": "La calidad de {format} necesita ffmpeg, que no se encontró, así que {format} se guarda sin pérdida y solo se puede fijar el ancho.", + "image_preset.quality_hint": "Más alta conserva más detalle; más baja da archivos más pequeños", + "image_preset.max_width": "Ancho máximo", + "image_preset.max_width_hint": "Las imágenes más anchas se reducen; las pequeñas nunca se amplían", + "image_preset.summary": "Calidad {quality} · {width}", + "image_preset.width_px": "hasta {px} px de ancho", + "image_preset.original_width": "ancho original", + "image_preset.remove": "Quitar ajuste", + "image_preset.saved": "Ajuste de {format} guardado", + "image_preset.removed": "Ajuste de {format} quitado", "settings.install_program": "Instalación / descarga", "settings.install_hint": "Instala los programas opcionales con los enlaces siguientes. Añade sus herramientas de línea de comandos al PATH y vuelve a buscar. También puedes colocar los ejecutables en tools/bin junto a fmx.", "welcome.title": "Te damos la bienvenida a FMX", diff --git a/locales/fr.json b/locales/fr.json index e07b602..122dd95 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -602,6 +602,22 @@ "preset.deleted": "Préréglage « {name} » supprimé", "preset.missing": "Ce préréglage n’existe plus.", "preset.max_side": "jusqu’à {px} px", + "image_preset.row": "Préréglage du format", + "image_preset.none": "Non défini : la qualité et la taille ci-dessous sont utilisées", + "image_preset.configure": "Configurer le préréglage", + "image_preset.title": "Préréglage {format}", + "image_preset.hint": "Utilisé à chaque conversion d’une image en {format}, à la place de la qualité et de la taille communes.", + "image_preset.lossless": "{format} est sans perte : seule la largeur peut être réglée. Utilisé à chaque conversion d’une image en {format}.", + "image_preset.no_encoder": "La qualité {format} nécessite ffmpeg, introuvable : {format} est donc enregistré sans perte et seule la largeur peut être réglée.", + "image_preset.quality_hint": "Plus haute garde plus de détails ; plus basse donne des fichiers plus légers", + "image_preset.max_width": "Largeur maximale", + "image_preset.max_width_hint": "Les images plus larges sont réduites ; les plus petites ne sont jamais agrandies", + "image_preset.summary": "Qualité {quality} · {width}", + "image_preset.width_px": "jusqu’à {px} px de large", + "image_preset.original_width": "largeur d’origine", + "image_preset.remove": "Supprimer le préréglage", + "image_preset.saved": "Préréglage {format} enregistré", + "image_preset.removed": "Préréglage {format} supprimé", "settings.install_program": "Installation / téléchargement", "settings.install_hint": "Installez les programmes facultatifs avec les liens ci-dessous. Ajoutez leurs outils en ligne de commande au PATH, puis relancez la détection. Vous pouvez aussi placer les exécutables dans tools/bin à côté de fmx.", "welcome.title": "Bienvenue dans FMX", diff --git a/locales/he.json b/locales/he.json index 07bdb7a..eb5b522 100644 --- a/locales/he.json +++ b/locales/he.json @@ -602,6 +602,22 @@ "preset.deleted": "ההגדרה \"{name}\" נמחקה", "preset.missing": "ההגדרה הזו כבר לא קיימת.", "preset.max_side": "עד {px} פיקסלים", + "image_preset.row": "הגדרה קבועה לפורמט", + "image_preset.none": "לא הוגדרה: נעשה שימוש באיכות ובגודל שלמטה", + "image_preset.configure": "הגדרת קבועה", + "image_preset.title": "הגדרה קבועה ל־{format}", + "image_preset.hint": "משמשת בכל המרה של תמונה ל־{format}, במקום האיכות והגודל המשותפים.", + "image_preset.lossless": "{format} הוא פורמט ללא אובדן, לכן אפשר לקבוע רק את הרוחב. משמשת בכל המרה של תמונה ל־{format}.", + "image_preset.no_encoder": "האיכות של {format} דורשת ffmpeg, שלא נמצא, לכן {format} נשמר ללא אובדן ואפשר לקבוע רק את הרוחב.", + "image_preset.quality_hint": "גבוהה שומרת יותר פרטים; נמוכה יוצרת קבצים קטנים יותר", + "image_preset.max_width": "רוחב מרבי", + "image_preset.max_width_hint": "תמונות רחבות יותר מוקטנות; קטנות יותר אף פעם לא מוגדלות", + "image_preset.summary": "איכות {quality} · {width}", + "image_preset.width_px": "עד {px} פיקסלים ברוחב", + "image_preset.original_width": "רוחב מקורי", + "image_preset.remove": "הסרת ההגדרה", + "image_preset.saved": "ההגדרה ל־{format} נשמרה", + "image_preset.removed": "ההגדרה ל־{format} הוסרה", "settings.install_program": "התקנה / הורדה", "settings.install_hint": "התקינו תוכנות נוספות באמצעות הקישורים למטה. הוסיפו את כלי שורת הפקודה שלהן ל־PATH ולחצו על סריקה מחדש. ניתן גם למקם קובצי הפעלה בתיקיית tools/bin לצד fmx.", "welcome.title": "ברוכים הבאים ל־FMX", diff --git a/locales/ru.json b/locales/ru.json index e042b91..6792668 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -602,6 +602,22 @@ "preset.deleted": "Пресет «{name}» удалён", "preset.missing": "Этот пресет больше не существует.", "preset.max_side": "до {px} пикс.", + "image_preset.row": "Пресет формата", + "image_preset.none": "Не задан: используются качество и размер ниже", + "image_preset.configure": "Настроить пресет", + "image_preset.title": "Пресет {format}", + "image_preset.hint": "Применяется при каждом преобразовании изображения в {format} вместо общих качества и размера.", + "image_preset.lossless": "{format} сжимает без потерь, поэтому задаётся только ширина. Применяется при каждом преобразовании изображения в {format}.", + "image_preset.no_encoder": "Для качества {format} нужен ffmpeg, но он не найден, поэтому {format} сохраняется без потерь и задаётся только ширина.", + "image_preset.quality_hint": "Выше — больше деталей, ниже — меньше файлы", + "image_preset.max_width": "Макс. ширина", + "image_preset.max_width_hint": "Более широкие изображения уменьшаются, меньшие никогда не увеличиваются", + "image_preset.summary": "Качество {quality} · {width}", + "image_preset.width_px": "до {px} px в ширину", + "image_preset.original_width": "исходная ширина", + "image_preset.remove": "Удалить пресет", + "image_preset.saved": "Пресет {format} сохранён", + "image_preset.removed": "Пресет {format} удалён", "settings.install_program": "Установка / скачивание", "settings.install_hint": "Установите дополнительные программы по ссылкам ниже. Добавьте их инструменты командной строки в PATH, затем нажмите «Проверить снова». Исполняемые файлы также можно поместить в папку tools/bin рядом с fmx.", "download.only_subtitles": "Только субтитры", diff --git a/src/app.rs b/src/app.rs index bca88c3..fa29ec4 100644 --- a/src/app.rs +++ b/src/app.rs @@ -223,6 +223,14 @@ struct PresetDialog { name: String, } +/// The Configure Preset box for one image format. +struct ImagePresetDialog { + format: ImageFormat, + preset: options::ImageFormatPreset, + /// The format already had a preset, so it can be removed. + existed: bool, +} + /// What happens once the whole queue has finished. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum AfterDone { @@ -266,6 +274,7 @@ pub struct FmxApp { category: Category, show_favorites: bool, preset_dialog: Option, + image_preset_dialog: Option, /// Whether the selected tool's editor is open (otherwise the tool grid shows). in_editor: bool, search: String, @@ -391,6 +400,7 @@ impl FmxApp { category: settings.last_tool.category(), show_favorites: !settings.favorite_tools.is_empty() || !settings.presets.is_empty(), preset_dialog: None, + image_preset_dialog: None, in_editor: false, search: String::new(), reset_tool_scroll: false, @@ -472,6 +482,12 @@ impl FmxApp { name: app.tool_title(), }); } + if crate::devshot::wants_menu("image_preset") + && let Tool::ToImage(format) = app.tool + { + app.welcome_step = None; + app.open_image_preset(format); + } if let Some(section) = crate::devshot::wants_settings() { app.show_settings = true; app.settings_tab = match section.as_str() { @@ -566,7 +582,12 @@ impl FmxApp { self.toasts.push(ToastKind::Error, tr("preset.missing")); return; }; - self.quick_convert(files, &preset.options, |file| { + // Format presets are app-wide, not part of a saved preset. + let options = Options { + image_presets: self.settings.options.image_presets.clone(), + ..preset.options + }; + self.quick_convert(files, &options, |file| { preset_takes(preset.tool, file).then_some(preset.tool) }); } @@ -676,9 +697,11 @@ impl FmxApp { self.select_tool(preset.tool); let edit = std::mem::take(&mut self.settings.options.edit); let photos = std::mem::take(&mut self.settings.options.collage_photos); + let image_presets = std::mem::take(&mut self.settings.options.image_presets); self.settings.options = Options { edit, collage_photos: photos, + image_presets, ..preset.options }; } @@ -3350,6 +3373,8 @@ impl FmxApp { if matches!(tool, Tool::Record | Tool::RecordAudio | Tool::Screenshot) { self.poll_capture_devices(ui.ctx()); } + let mut configure_format = None; + let has_ffmpeg = self.toolbox.get(External::Ffmpeg).is_some(); let opts = &mut self.settings.options; match tool { Tool::Slideshow => { @@ -3390,9 +3415,35 @@ impl FmxApp { Tool::ToAudio(_) | Tool::Rotate | Tool::Speed | Tool::Delogo | Tool::PdfCompress => { quality_row(ui, &mut opts.quality); } - Tool::ToImage(_) | Tool::ImagesToPdf => { + Tool::ToImage(format) => { + let preset = opts.image_presets.get(&format).copied(); + let summary = preset.map_or_else( + || tr("image_preset.none").to_owned(), + |p| image_preset_summary(p, quality_applies(format, has_ffmpeg)), + ); + row_hint(ui, tr("image_preset.row"), &summary, |ui| { + if widgets::button( + ui, + Some(icons::SLIDERS), + tr("image_preset.configure"), + Kind::Secondary, + Size::Small, + ) + .clicked() + { + configure_format = Some(format); + } + }); + // A format preset sets quality and size itself. + if preset.is_none() { + quality_row(ui, &mut opts.quality); + } + image_rows(ui, opts, preset.is_none()); + watermark_row(ui, &mut opts.edit, "image_wm_corner"); + } + Tool::ImagesToPdf => { quality_row(ui, &mut opts.quality); - image_rows(ui, opts); + image_rows(ui, opts, true); watermark_row(ui, &mut opts.edit, "image_wm_corner"); } Tool::ToDevice(device) => { @@ -3687,6 +3738,150 @@ impl FmxApp { rect_editor(ui, &mut opts.delogo) }); } + if let Some(format) = configure_format { + self.open_image_preset(format); + } + } + + /// Opens Configure Preset for `format`, starting from its preset or, when + /// it has none, from the current shared settings. + fn open_image_preset(&mut self, format: ImageFormat) { + let opts = &self.settings.options; + let existing = opts.image_presets.get(&format).copied(); + let preset = existing.unwrap_or(options::ImageFormatPreset { + quality: opts.quality.pick(92, 82, 65), + max_width: opts.image_max_side, + }); + self.image_preset_dialog = Some(ImagePresetDialog { + format, + preset, + existed: existing.is_some(), + }); + } + + /// The Configure Preset box: quality and maximum width for one image format. + fn image_preset_window(&mut self, ctx: &egui::Context) { + enum Outcome { + Save, + Remove, + } + let Some(dialog) = &mut self.image_preset_dialog else { + return; + }; + let width = (ctx.content_rect().width() - 64.0).clamp(1.0, 440.0); + let format = dialog.format; + let adjustable = quality_applies(format, self.toolbox.get(External::Ffmpeg).is_some()); + let mut outcome = None; + let modal = egui::Modal::new(Id::unique("image_preset_dialog")).show(ctx, |ui| { + ui.set_width(width); + dir::vertical(ui, |ui| { + ui.heading(trf("image_preset.title", &[("format", &format.label())])); + ui.add_space(4.0); + let hint = if adjustable { + trf("image_preset.hint", &[("format", &format.label())]) + } else if format.has_quality() { + // Without ffmpeg, WebP is written by the lossless native encoder. + trf("image_preset.no_encoder", &[("format", &format.label())]) + } else { + trf("image_preset.lossless", &[("format", &format.label())]) + }; + ui.add(Label::new(RichText::new(hint).color(theme::palette(ui).text_weak)).wrap()); + ui.add_space(10.0); + if adjustable { + row_hint( + ui, + tr("option.quality"), + tr("image_preset.quality_hint"), + |ui| { + theme::slider( + ui, + Slider::new( + &mut dialog.preset.quality, + options::MIN_IMAGE_QUALITY..=options::MAX_IMAGE_QUALITY, + ), + ); + }, + ); + } + row_hint( + ui, + tr("image_preset.max_width"), + tr("image_preset.max_width_hint"), + |ui| { + optional_number( + ui, + &mut dialog.preset.max_width, + 1920, + options::MIN_IMAGE_SIDE..=options::MAX_IMAGE_SIDE, + " px", + tr("option.original"), + ); + }, + ); + ui.add_space(14.0); + ui.horizontal(|ui| { + if dialog.existed + && widgets::button( + ui, + None, + tr("image_preset.remove"), + Kind::Ghost, + Size::Regular, + ) + .clicked() + { + outcome = Some(Outcome::Remove); + } + ui.with_layout(dir::trailing(Align::Center), |ui| { + if widgets::button( + ui, + None, + tr("action.save"), + Kind::Primary, + Size::Regular, + ) + .clicked() + { + outcome = Some(Outcome::Save); + } + if widgets::button( + ui, + None, + tr("action.cancel"), + Kind::Secondary, + Size::Regular, + ) + .clicked() + { + ui.close(); + } + }); + }); + }); + }); + match outcome { + Some(Outcome::Save) => { + let dialog = self.image_preset_dialog.take().expect("open"); + self.settings + .options + .image_presets + .insert(format, dialog.preset.clamped()); + self.toasts.push( + ToastKind::Success, + trf("image_preset.saved", &[("format", &format.label())]), + ); + } + Some(Outcome::Remove) => { + self.image_preset_dialog = None; + self.settings.options.image_presets.remove(&format); + self.toasts.push( + ToastKind::Success, + trf("image_preset.removed", &[("format", &format.label())]), + ); + } + None if modal.should_close() => self.image_preset_dialog = None, + None => {} + } } fn advanced_video(&mut self, ui: &mut egui::Ui, format: VideoFormat) { @@ -6545,17 +6740,44 @@ fn trim_rows(ui: &mut egui::Ui, edit: &mut Edit) { }); } -fn image_rows(ui: &mut egui::Ui, opts: &mut options::Options) { - row(ui, tr("option.max_side"), |ui| { - optional_number( - ui, - &mut opts.image_max_side, - 1920, - options::MIN_IMAGE_SIDE..=options::MAX_IMAGE_SIDE, - " px", - tr("option.original"), - ); - }); +/// What a format preset does, in one line: its quality and width limit. +/// Whether a preset's quality changes the output: the format is lossy and the +/// encoder that will write it reads the setting (WebP needs ffmpeg's libwebp; +/// the native fallback is lossless). +fn quality_applies(format: ImageFormat, has_ffmpeg: bool) -> bool { + format.has_quality() && (format != ImageFormat::Webp || has_ffmpeg) +} + +fn image_preset_summary(preset: options::ImageFormatPreset, show_quality: bool) -> String { + let width = preset.max_width.map_or_else( + || tr("image_preset.original_width").to_owned(), + |px| trf("image_preset.width_px", &[("px", &px)]), + ); + if show_quality { + trf( + "image_preset.summary", + &[("quality", &preset.quality), ("width", &width)], + ) + } else { + width + } +} + +/// Image size, rotation and grayscale rows; `show_size` is off when a format +/// preset sets the size instead. +fn image_rows(ui: &mut egui::Ui, opts: &mut options::Options, show_size: bool) { + if show_size { + row(ui, tr("option.max_side"), |ui| { + optional_number( + ui, + &mut opts.image_max_side, + 1920, + options::MIN_IMAGE_SIDE..=options::MAX_IMAGE_SIDE, + " px", + tr("option.original"), + ); + }); + } row(ui, tr("option.rotation"), |ui| { let mut choices: Vec> = vec![None]; choices.extend(Rotation::ALL.map(Some)); @@ -7071,6 +7293,7 @@ impl eframe::App for FmxApp { self.preview_window(&ctx); self.welcome_window(&ctx); self.preset_window(&ctx); + self.image_preset_window(&ctx); if let Some(result) = self .shortcut_result .as_ref() diff --git a/src/catalog.rs b/src/catalog.rs index 4ff66e7..8c671ed 100644 --- a/src/catalog.rs +++ b/src/catalog.rs @@ -723,6 +723,11 @@ impl ImageFormat { } /// ffmpeg encoder flags for formats the native encoders don't cover. + /// Formats with lossy compression, whose quality can be chosen. + pub fn has_quality(self) -> bool { + matches!(self, Self::Jpeg | Self::Webp | Self::Avif | Self::Jxl) + } + pub fn ffmpeg_encoder(self) -> Option<&'static [&'static str]> { match self { Self::Avif => Some(&[ diff --git a/src/devshot.rs b/src/devshot.rs index 19d74b9..fe49072 100644 --- a/src/devshot.rs +++ b/src/devshot.rs @@ -5,12 +5,13 @@ //! - `FMX_SCREENSHOT_SETTINGS=1` opens Settings (`=queue`, `=updates`, //! `=programs` or `=about` opens that section); //! - `FMX_SCREENSHOT_EXPAND=1` opens every collapsible section; -//! - `FMX_SCREENSHOT_TOOL=record` opens that tool (`screenshot`, `frames`, `trim`, `rotate`, `mp4`, `download`, `resize`, `cd`); +//! - `FMX_SCREENSHOT_TOOL=record` opens that tool (`screenshot`, `frames`, `trim`, `rotate`, `mp4`, `download`, `resize`, `jpg`, `cd`); //! - `FMX_SCREENSHOT_ENQUEUE=1` adds the editor's files to the queue //! (`FMX_SCREENSHOT_RUNNING=1` then shows the first two as running); //! - `FMX_SCREENSHOT_SIZE=x` resizes the window; //! - `FMX_SCREENSHOT_MENU=` opens that drop-down (e.g. `after_done`, `presets`), -//! or `save_preset` the dialog that names a new preset; +//! `save_preset` the dialog that names a new preset, or `image_preset` +//! Configure Preset for the open image tool; //! - `FMX_SCREENSHOT_UPDATE=1` pretends a newer release was found //! (`=downloading:0.4` pretends it is 40 % downloaded). //! @@ -71,6 +72,7 @@ pub fn wants_tool() -> Option { "mp4" => Some(Tool::ToVideo(crate::catalog::VideoFormat::Mp4)), "download" => Some(Tool::Download), "resize" => Some(Tool::ToImage(crate::catalog::ImageFormat::Png)), + "jpg" => Some(Tool::ToImage(crate::catalog::ImageFormat::Jpeg)), "cd" => Some(Tool::CdToAudio), _ => None, } diff --git a/src/imaging.rs b/src/imaging.rs index 5af3183..4931108 100644 --- a/src/imaging.rs +++ b/src/imaging.rs @@ -109,9 +109,19 @@ fn decode_png(png: &[u8], max_alloc: u64) -> Result { /// Applies resize/rotation/grayscale options. Never upscales. fn transform(img: DynamicImage, opts: &Options, hard_cap: Option) -> DynamicImage { - let user_cap = opts - .image_max_side - .map(|s| s.clamp(options::MIN_IMAGE_SIDE, options::MAX_IMAGE_SIDE)); + transform_sized(img, opts, opts.image_max_side, None, hard_cap) +} + +/// [`transform`] with the longest side limited to `max_side` and the final +/// width (after rotation) to `max_width`, keeping proportions. +fn transform_sized( + img: DynamicImage, + opts: &Options, + max_side: Option, + max_width: Option, + hard_cap: Option, +) -> DynamicImage { + let user_cap = max_side.map(|s| s.clamp(options::MIN_IMAGE_SIDE, options::MAX_IMAGE_SIDE)); let cap = match (user_cap, hard_cap) { (Some(a), Some(b)) => Some(a.min(b)), (a, b) => a.or(b), @@ -130,6 +140,14 @@ fn transform(img: DynamicImage, opts: &Options, hard_cap: Option) -> Dynami Some(Rotation::FlipVertical) => img.flipv(), None => img, }; + let img = match max_width { + Some(w) if img.width() > w => { + let h = (u64::from(img.height()) * u64::from(w) + u64::from(img.width()) / 2) + / u64::from(img.width()); + img.resize_exact(w, (h as u32).max(1), FilterType::Lanczos3) + } + _ => img, + }; if opts.grayscale { img.grayscale() } else { img } } @@ -151,9 +169,56 @@ fn jpeg_quality(opts: &Options) -> u8 { opts.quality.pick(92, 82, 65) } +/// The quality (1-100) the user set for `format` with Configure Preset. +fn preset_quality(opts: &Options, format: ImageFormat) -> Option { + opts.image_presets + .get(&format) + .map(|p| p.clamped().quality) + .filter(|_| format.has_quality()) +} + /// libwebp's quality for lossy WebP. -fn webp_quality(opts: &Options) -> &'static str { - opts.quality.pick("90", "80", "65") +fn webp_quality(opts: &Options) -> String { + preset_quality(opts, ImageFormat::Webp).map_or_else( + || opts.quality.pick("90", "80", "65").to_owned(), + |q| q.to_string(), + ) +} + +/// ffmpeg encoder flags for `format`, with the preset's quality when one is set. +fn ffmpeg_flags(opts: &Options, format: ImageFormat) -> Vec { + let mut flags: Vec = format + .ffmpeg_encoder() + .unwrap_or_default() + .iter() + .map(|f| (*f).to_owned()) + .collect(); + let Some(q) = preset_quality(opts, format) else { + return flags; + }; + let (key, value) = match format { + // libaom's CRF runs from 0 (best) to 63. + ImageFormat::Avif => ("-crf", ((u32::from(100 - q) * 63 + 50) / 100).to_string()), + // libjxl's Butteraugli distance: 0 is lossless, 1 visually lossless + // (JxlEncoderDistanceFromQuality's mapping). + ImageFormat::Jxl => { + let d = if q >= 100 { + 0.0 + } else if q >= 30 { + 0.1 + f32::from(100 - q) * 0.09 + } else { + // ffmpeg's libjxl wrapper accepts distances up to 15. + let q = f32::from(q); + (53.0 / 3000.0 * q * q - 23.0 / 20.0 * q + 25.0).min(15.0) + }; + ("-distance", format!("{d:.2}")) + } + _ => return flags, + }; + if let Some(i) = flags.iter().position(|f| f == key) { + flags[i + 1] = value; + } + flags } fn encode_jpeg(img: &DynamicImage, quality: u8, out: impl Write) -> Result<(), ImageError> { @@ -171,8 +236,13 @@ pub fn convert( ffmpeg: Option<&Path>, ) -> Result<(), ImageError> { let hard_cap = (format == ImageFormat::Ico).then_some(ICO_MAX_SIDE); + // A format preset replaces the shared size limit with its own width limit. + let (max_side, max_width) = match opts.image_presets.get(&format) { + Some(p) => (None, p.clamped().max_width), + None => (opts.image_max_side, None), + }; let img = watermark( - transform(open(input, ffmpeg)?, opts, hard_cap), + transform_sized(open(input, ffmpeg)?, opts, max_side, max_width, hard_cap), opts, ffmpeg, )?; @@ -195,15 +265,16 @@ fn write_image( "-c:v", "libwebp", "-quality", - webp_quality(opts), + &webp_quality(opts), "-compression_level", "6", ]; return encode_with_ffmpeg(img, output, format, &flags, ffmpeg); } let Some(codec) = format.codec() else { - let flags = format.ffmpeg_encoder().unwrap_or_default(); - return encode_with_ffmpeg(img, output, format, flags, ffmpeg); + let flags = ffmpeg_flags(opts, format); + let flags: Vec<&str> = flags.iter().map(String::as_str).collect(); + return encode_with_ffmpeg(img, output, format, &flags, ffmpeg); }; let mut tmp = tempfile::NamedTempFile::new_in(dir)?; { @@ -242,7 +313,11 @@ fn write_image( image::ExtendedColorType::Rgba8, )?; } - ImageFormat::Jpeg => encode_jpeg(img, jpeg_quality(opts), &mut out)?, + ImageFormat::Jpeg => encode_jpeg( + img, + preset_quality(opts, format).unwrap_or_else(|| jpeg_quality(opts)), + &mut out, + )?, // PNG and TIFF keep 16-bit depth; the rest want 8-bit RGBA. ImageFormat::Png | ImageFormat::Tiff => img.write_to(&mut out, codec)?, _ => DynamicImage::ImageRgba8(img.to_rgba8()).write_to(&mut out, codec)?, @@ -1087,6 +1162,76 @@ mod tests { assert_eq!((small.width(), small.height()), (10, 5)); } + #[test] + fn format_preset_limits_width_after_rotation() { + let opts = Options { + image_rotation: Some(Rotation::Clockwise), + ..Options::default() + }; + // 40x80 turns into 80x40, then is held to 20 px wide. + let img = transform_sized(DynamicImage::new_rgb8(40, 80), &opts, None, Some(20), None); + assert_eq!((img.width(), img.height()), (20, 10)); + let small = transform_sized(DynamicImage::new_rgb8(10, 5), &opts, None, Some(20), None); + assert_eq!((small.width(), small.height()), (5, 10)); + } + + #[test] + fn format_preset_replaces_shared_size_and_quality() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("in.png"); + DynamicImage::new_rgb8(3000, 1500).save(&input).unwrap(); + let mut opts = Options { + image_max_side: Some(800), + ..Options::default() + }; + opts.image_presets.insert( + ImageFormat::Jpeg, + options::ImageFormatPreset { + quality: 95, + max_width: Some(2400), + }, + ); + let jpg = dir.path().join("out.jpg"); + convert(&input, &jpg, ImageFormat::Jpeg, &opts, None).unwrap(); + assert_eq!(image::image_dimensions(&jpg).unwrap(), (2400, 1200)); + assert_eq!(preset_quality(&opts, ImageFormat::Jpeg), Some(95)); + // Formats without a preset keep the shared limit. + let png = dir.path().join("out.png"); + convert(&input, &png, ImageFormat::Png, &opts, None).unwrap(); + assert_eq!(image::image_dimensions(&png).unwrap(), (800, 400)); + } + + #[test] + fn format_preset_quality_sets_ffmpeg_flags() { + let mut opts = Options::default(); + assert!(ffmpeg_flags(&opts, ImageFormat::Avif).contains(&"30".to_owned())); + for (format, quality) in [(ImageFormat::Avif, 100), (ImageFormat::Jxl, 100)] { + opts.image_presets.insert( + format, + options::ImageFormatPreset { + quality, + max_width: None, + }, + ); + } + let avif = ffmpeg_flags(&opts, ImageFormat::Avif); + let crf = avif.iter().position(|f| f == "-crf").unwrap(); + assert_eq!(avif[crf + 1], "0"); + let jxl = ffmpeg_flags(&opts, ImageFormat::Jxl); + assert_eq!(jxl, ["-c:v", "libjxl", "-distance", "0.00"]); + for (quality, distance) in [(30, "6.40"), (20, "9.07"), (1, "15.00")] { + opts.image_presets.insert( + ImageFormat::Jxl, + options::ImageFormatPreset { + quality, + max_width: None, + }, + ); + let jxl = ffmpeg_flags(&opts, ImageFormat::Jxl); + assert_eq!(jxl[3], distance, "quality {quality}"); + } + } + #[test] fn join_stacks_to_common_width() { let a = DynamicImage::new_rgb8(100, 50); diff --git a/src/options.rs b/src/options.rs index 276700e..4921eda 100644 --- a/src/options.rs +++ b/src/options.rs @@ -1000,6 +1000,41 @@ pub const MIN_FRAME_INTERVAL_S: f32 = 0.1; pub const MAX_FRAME_INTERVAL_S: f32 = 3600.0; pub const MIN_IMAGE_SIDE: u32 = 16; pub const MAX_IMAGE_SIDE: u32 = 16_384; +pub const MIN_IMAGE_QUALITY: u8 = 1; +pub const MAX_IMAGE_QUALITY: u8 = 100; + +/// The quality and size the user chose for one image format; used every time +/// an image is converted to that format, in place of the shared settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ImageFormatPreset { + /// 1 (smallest file) to 100 (best quality); only formats with lossy + /// compression (see [`ImageFormat::has_quality`]) use it. + pub quality: u8, + /// Widest the output may be, keeping its proportions; `None` keeps the + /// original width. Images are never enlarged. + pub max_width: Option, +} + +impl Default for ImageFormatPreset { + fn default() -> Self { + Self { + quality: 90, + max_width: None, + } + } +} + +impl ImageFormatPreset { + pub fn clamped(self) -> Self { + Self { + quality: self.quality.clamp(MIN_IMAGE_QUALITY, MAX_IMAGE_QUALITY), + max_width: self + .max_width + .map(|w| w.clamp(MIN_IMAGE_SIDE, MAX_IMAGE_SIDE)), + } + } +} pub const MAX_VIDEO_KBPS: u32 = 200_000; pub const MAX_AUDIO_KBPS: u32 = 640; pub const MAX_VOLUME_DB: f32 = 30.0; @@ -1145,6 +1180,9 @@ pub struct Options { pub join_audio_format: AudioFormat, /// Longest image side after resizing; `None` keeps the original size. pub image_max_side: Option, + /// Per-format quality and width, set with Configure Preset; a format + /// listed here ignores `quality` and `image_max_side`. + pub image_presets: std::collections::HashMap, pub grayscale: bool, pub image_rotation: Option, pub split_by_parts: bool, @@ -1226,6 +1264,7 @@ impl Default for Options { speed: 1.5, join_audio_format: AudioFormat::Mp3, image_max_side: None, + image_presets: std::collections::HashMap::new(), grayscale: false, image_rotation: None, split_by_parts: false,