Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Add everyday media tools: compress, merge, slideshow, extract audio, remove metadata

cre8ive-marketing0d2273470467
diff --git a/src/Filee.App/Assets/i18n/ar.json b/src/Filee.App/Assets/i18n/ar.json
index 7ee866f4..69a9198a 100644
--- a/src/Filee.App/Assets/i18n/ar.json
+++ b/src/Filee.App/Assets/i18n/ar.json
@@ -76,6 +76,7 @@
"error.no_route": "لا يوجد محرك يستطيع إجراء هذا التحويل",
"error.cannot_turn": "التدوير والانعكاس متاحان للصور فقط",
"error.too_many_frames": "عدد الإطارات كبير جدًا لحفظها كصور. زِد قيمة «كل إطار رقم N»",
+ "error.too_many_pictures": "عدد الصور كبير جدًا لفيديو واحد، قسّمها على عدة فيديوهات",
"error.not_enough_space": "لا توجد مساحة كافية على القرص لحفظ الصور",
"error.no_motion_photo": "لا تحتوي هذه الصورة على فيديو يستطيع Filee قراءته (صورة Motion Photo من Android، أو Live Photo من iPhone مع ملف MOV بجانبها)",
"error.live_photo_start": "يبدأ المقطع بعد نهاية هذا الفيديو. اختر «بداية المقطع» أبكر",
@@ -212,6 +213,14 @@
"preset.extract_motion": "استخراج فيديو Live Photo",
"preset.live_photo_iphone": "Live Photo (iPhone)",
"preset.motion_photo_android": "Motion Photo (Android)",
+ "preset.compress_image": "ضغط الصورة",
+ "preset.compress_video": "ضغط الفيديو",
+ "preset.video_from_images": "فيديو من الصور",
+ "preset.extract_audio": "استخراج الصوت",
+ "preset.merge_videos": "دمج الفيديوهات",
+ "preset.compress_audio": "ضغط الصوت",
+ "preset.merge_audio": "دمج الصوت",
+ "preset.remove_metadata": "إزالة البيانات الوصفية",
"format.folder": "مجلد",
"format.category.Image": "صورة",
"format.category.Pdf": "PDF",
@@ -476,6 +485,9 @@
"presets.frame_estimate": "تنتج دقيقة من فيديو بمعدل 30 إطارًا/ث {0} صورة، بحد أقصى {1} لكل فيديو.",
"presets.extract_motion_photo": "استخراج فيديو Live/Motion Photo",
"presets.extract_motion_photo_hint": "تتحول الصورة إلى الفيديو المحفوظ معها: المضمّن في Motion Photo من Android، أو ملف MOV بجانب Live Photo من iPhone.\nتتحول الصور الأخرى إلى فيديو للصورة الثابتة.",
+ "presets.slide_seconds": "ثوانٍ لكل صورة",
+ "presets.crossfade": "تلاشٍ متداخل بين الصور",
+ "presets.crossfade_hint": "تتلاشى كل صورة في التالية خلال ثانية بدلًا من الانتقال المفاجئ.",
"presets.group.live_photo": "Live / Motion Photo",
"presets.live_photo": "يصبح الفيديو",
"presets.live_photo.None": "إطارًا ثابتًا واحدًا",
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index d6024c30..ccd8d77d 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -82,6 +82,7 @@
"error.no_route": "No engine can do this conversion",
"error.cannot_turn": "Rotate and flip work on images only",
"error.too_many_frames": "Too many frames to save as pictures, raise \"Every Nth frame\"",
+ "error.too_many_pictures": "Too many pictures for one video, split them into several",
"error.not_enough_space": "Not enough free disk space for the pictures",
"error.no_motion_photo": "This photo has no video Filee can read (an Android Motion Photo, or an iPhone Live Photo with its MOV next to it)",
"error.live_photo_start": "The clip starts after the end of this video. Choose an earlier \"Clip start\"",
@@ -222,6 +223,14 @@
"preset.extract_motion": "Extract Live Photo video",
"preset.live_photo_iphone": "Live Photo (iPhone)",
"preset.motion_photo_android": "Motion Photo (Android)",
+ "preset.compress_image": "Compress image",
+ "preset.compress_video": "Compress video",
+ "preset.video_from_images": "Video from images",
+ "preset.extract_audio": "Extract audio",
+ "preset.merge_videos": "Merge videos",
+ "preset.compress_audio": "Compress audio",
+ "preset.merge_audio": "Merge audio",
+ "preset.remove_metadata": "Remove metadata",
"format.folder": "Folder",
"format.category.Image": "Image",
@@ -491,6 +500,9 @@
"presets.frame_estimate": "One minute of 30 fps video gives {0} pictures, at most {1} per video.",
"presets.extract_motion_photo": "Extract Live/Motion Photo video",
"presets.extract_motion_photo_hint": "A photo becomes the video saved with it: the one inside an Android Motion Photo, or the MOV next to an iPhone Live Photo.\nOther pictures become a video of the still picture.",
+ "presets.slide_seconds": "Seconds per picture",
+ "presets.crossfade": "Crossfade between pictures",
+ "presets.crossfade_hint": "Each picture fades into the next over a second instead of cutting to it.",
"presets.group.live_photo": "Live / Motion Photo",
"presets.live_photo": "A video becomes",
"presets.live_photo.None": "One still frame",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 89007a3e..921e1036 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -76,6 +76,7 @@
"error.no_route": "Ningún motor puede hacer esta conversión",
"error.cannot_turn": "Rotar y voltear solo funcionan con imágenes",
"error.too_many_frames": "Demasiados fotogramas para guardar como imágenes; aumenta «Cada N fotogramas»",
+ "error.too_many_pictures": "Demasiadas imágenes para un vídeo; divídelas en varios",
"error.not_enough_space": "Espacio libre en disco insuficiente para las imágenes",
"error.no_motion_photo": "Esta foto no tiene un vídeo que Filee pueda leer (una Motion Photo de Android o una Live Photo de iPhone con su MOV al lado)",
"error.live_photo_start": "El clip empieza después del final de este vídeo. Elige un «Inicio del clip» anterior",
@@ -212,6 +213,14 @@
"preset.extract_motion": "Extraer vídeo de Live Photo",
"preset.live_photo_iphone": "Live Photo (iPhone)",
"preset.motion_photo_android": "Motion Photo (Android)",
+ "preset.compress_image": "Comprimir imagen",
+ "preset.compress_video": "Comprimir vídeo",
+ "preset.video_from_images": "Vídeo de imágenes",
+ "preset.extract_audio": "Extraer audio",
+ "preset.merge_videos": "Unir vídeos",
+ "preset.compress_audio": "Comprimir audio",
+ "preset.merge_audio": "Unir audio",
+ "preset.remove_metadata": "Quitar metadatos",
"format.folder": "Carpeta",
"format.category.Image": "Imagen",
"format.category.Pdf": "PDF",
@@ -476,6 +485,9 @@
"presets.frame_estimate": "Un minuto de vídeo a 30 fps genera {0} imágenes, como máximo {1} por vídeo.",
"presets.extract_motion_photo": "Extraer vídeo de Live/Motion Photo",
"presets.extract_motion_photo_hint": "La foto se convierte en el vídeo guardado con ella: el que lleva dentro una Motion Photo de Android o el MOV junto a una Live Photo de iPhone.\nLas demás imágenes se convierten en un vídeo de la imagen fija.",
+ "presets.slide_seconds": "Segundos por imagen",
+ "presets.crossfade": "Fundido entre imágenes",
+ "presets.crossfade_hint": "Cada imagen se funde con la siguiente durante un segundo en lugar de cortar.",
"presets.group.live_photo": "Live Photo / Motion Photo",
"presets.live_photo": "Un vídeo se convierte en",
"presets.live_photo.None": "Un fotograma fijo",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index dde78607..8ef98e60 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -76,6 +76,7 @@
"error.no_route": "कोई भी इंजन यह कन्वर्ज़न नहीं कर सकता",
"error.cannot_turn": "घुमाना और पलटना केवल इमेज पर काम करता है",
"error.too_many_frames": "तस्वीरों के रूप में सहेजने के लिए बहुत ज़्यादा फ़्रेम हैं, \"हर Nवाँ फ़्रेम\" बढ़ाएँ",
+ "error.too_many_pictures": "एक वीडियो के लिए तस्वीरें बहुत ज़्यादा हैं, इन्हें कई हिस्सों में बाँटें",
"error.not_enough_space": "तस्वीरों के लिए डिस्क पर पर्याप्त खाली जगह नहीं है",
"error.no_motion_photo": "इस फ़ोटो में ऐसा कोई वीडियो नहीं है जिसे Filee पढ़ सके (Android मोशन फ़ोटो, या पास में अपनी MOV फ़ाइल वाली iPhone लाइव फ़ोटो)",
"error.live_photo_start": "क्लिप इस वीडियो के ख़त्म होने के बाद शुरू होती है। \"क्लिप की शुरुआत\" पहले चुनें",
@@ -212,6 +213,14 @@
"preset.extract_motion": "लाइव फ़ोटो वीडियो निकालें",
"preset.live_photo_iphone": "लाइव फ़ोटो (iPhone)",
"preset.motion_photo_android": "मोशन फ़ोटो (Android)",
+ "preset.compress_image": "इमेज कंप्रेस करें",
+ "preset.compress_video": "वीडियो कंप्रेस करें",
+ "preset.video_from_images": "तस्वीरों से वीडियो",
+ "preset.extract_audio": "ऑडियो निकालें",
+ "preset.merge_videos": "वीडियो जोड़ें",
+ "preset.compress_audio": "ऑडियो कंप्रेस करें",
+ "preset.merge_audio": "ऑडियो जोड़ें",
+ "preset.remove_metadata": "मेटाडेटा हटाएँ",
"format.folder": "फ़ोल्डर",
"format.category.Image": "इमेज",
"format.category.Pdf": "PDF",
@@ -476,6 +485,9 @@
"presets.frame_estimate": "30 fps के एक मिनट के वीडियो से {0} तस्वीरें बनती हैं, प्रति वीडियो अधिकतम {1}।",
"presets.extract_motion_photo": "लाइव/मोशन फ़ोटो का वीडियो निकालें",
"presets.extract_motion_photo_hint": "फ़ोटो उसके साथ सहेजा गया वीडियो बन जाती है: Android मोशन फ़ोटो के अंदर वाला वीडियो, या iPhone लाइव फ़ोटो के पास रखी उसी नाम की MOV फ़ाइल।\nबाकी तस्वीरें स्थिर तस्वीर का वीडियो बनती हैं।",
+ "presets.slide_seconds": "हर तस्वीर के सेकंड",
+ "presets.crossfade": "तस्वीरों के बीच क्रॉसफ़ेड",
+ "presets.crossfade_hint": "हर तस्वीर सीधे बदलने के बजाय एक सेकंड में अगली तस्वीर में घुल जाती है।",
"presets.group.live_photo": "लाइव / मोशन फ़ोटो",
"presets.live_photo": "वीडियो बनता है",
"presets.live_photo.None": "एक स्थिर फ़्रेम",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index afc5f5d3..59894213 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -76,6 +76,7 @@
"error.no_route": "この変換に対応するエンジンがありません",
"error.cannot_turn": "回転と反転は画像でのみ使えます",
"error.too_many_frames": "画像として保存するフレーム数が多すぎます。「Nフレームごと」の値を大きくしてください",
+ "error.too_many_pictures": "1本の動画にするには画像が多すぎます。いくつかに分けてください",
"error.not_enough_space": "画像を保存するための空き容量が不足しています",
"error.no_motion_photo": "この写真には、Fileeが読み取れる動画がありません(Androidのモーションフォト、または隣にMOVがあるiPhoneのLive Photo)",
"error.live_photo_start": "クリップの開始位置が動画の終わりより後です。「クリップの開始」をもっと前にしてください",
@@ -212,6 +213,14 @@
"preset.extract_motion": "Live Photoの動画を抽出",
"preset.live_photo_iphone": "Live Photo(iPhone)",
"preset.motion_photo_android": "モーションフォト(Android)",
+ "preset.compress_image": "画像を圧縮",
+ "preset.compress_video": "動画を圧縮",
+ "preset.video_from_images": "写真から動画",
+ "preset.extract_audio": "音声を抽出",
+ "preset.merge_videos": "動画を結合",
+ "preset.compress_audio": "音声を圧縮",
+ "preset.merge_audio": "音声を結合",
+ "preset.remove_metadata": "メタデータを削除",
"format.folder": "フォルダー",
"format.category.Image": "画像",
"format.category.Pdf": "PDF",
@@ -476,6 +485,9 @@
"presets.frame_estimate": "30 fpsの動画は、1分あたり{0}枚の画像になります(動画1本につき最大{1}枚)。",
"presets.extract_motion_photo": "Live Photo・モーションフォトの動画を抽出",
"presets.extract_motion_photo_hint": "写真と一緒に保存された動画を取り出します。Androidのモーションフォトは写真の中の動画、iPhoneのLive Photoは隣にある同じ名前のMOVを使います。\nほかの画像は静止画の動画になります。",
+ "presets.slide_seconds": "1枚あたりの秒数",
+ "presets.crossfade": "写真の間をクロスフェード",
+ "presets.crossfade_hint": "次の写真へ切り替えず、1秒かけて徐々に移り変わります。",
"presets.group.live_photo": "Live Photo/モーションフォト",
"presets.live_photo": "動画の保存方法",
"presets.live_photo.None": "静止画1枚",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 115bfc7e..7d2bd40a 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -82,6 +82,7 @@
"error.no_route": "이 변환을 할 수 있는 엔진이 없어요",
"error.cannot_turn": "회전·반전은 이미지에만 할 수 있어요",
"error.too_many_frames": "프레임이 너무 많아요. 'N번째 프레임마다' 값을 늘려 주세요",
+ "error.too_many_pictures": "한 동영상에 넣기엔 사진이 너무 많아요. 여러 번에 나눠 주세요",
"error.not_enough_space": "이미지를 저장할 디스크 공간이 부족해요",
"error.no_motion_photo": "이 사진에서 읽을 수 있는 동영상을 찾지 못했어요 (안드로이드 모션 포토, 또는 옆에 MOV가 있는 아이폰 라이브 포토)",
"error.live_photo_start": "클립 시작이 동영상 끝보다 뒤예요. \"클립 시작\"을 더 앞으로 정해 주세요",
@@ -222,6 +223,14 @@
"preset.extract_motion": "라이브 포토 동영상 추출",
"preset.live_photo_iphone": "라이브 포토 (아이폰)",
"preset.motion_photo_android": "모션 포토 (안드로이드)",
+ "preset.compress_image": "이미지 압축",
+ "preset.compress_video": "동영상 압축",
+ "preset.video_from_images": "사진으로 동영상",
+ "preset.extract_audio": "오디오 추출",
+ "preset.merge_videos": "동영상 합치기",
+ "preset.compress_audio": "오디오 압축",
+ "preset.merge_audio": "오디오 합치기",
+ "preset.remove_metadata": "메타데이터 제거",
"format.folder": "폴더",
"format.category.Image": "이미지",
@@ -491,6 +500,9 @@
"presets.frame_estimate": "30fps 동영상 1분이면 이미지 {0}장이 생겨요. 동영상 하나에 최대 {1}장까지예요.",
"presets.extract_motion_photo": "라이브/모션 포토 동영상 추출",
"presets.extract_motion_photo_hint": "사진과 함께 저장된 동영상을 꺼내요. 안드로이드 모션 포토는 사진 안의 동영상을, 아이폰 라이브 포토는 옆에 있는 같은 이름의 MOV를 써요.\n다른 이미지는 정지 화면 동영상이 돼요.",
+ "presets.slide_seconds": "사진당 초",
+ "presets.crossfade": "사진 사이 크로스페이드",
+ "presets.crossfade_hint": "다음 사진으로 바로 넘어가지 않고 1초 동안 서서히 바뀌어요.",
"presets.group.live_photo": "라이브 / 모션 포토",
"presets.live_photo": "동영상을 이렇게 저장",
"presets.live_photo.None": "정지 화면 한 장",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index 2e2da36b..227d60f9 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -82,6 +82,7 @@
"error.no_route": "Żaden silnik nie wykona tej konwersji",
"error.cannot_turn": "Obracanie i odbicie działają tylko na obrazach",
"error.too_many_frames": "Za dużo klatek do zapisania jako obrazy, zwiększ „Co N-ta klatka”",
+ "error.too_many_pictures": "Za dużo zdjęć na jedno wideo, podziel je na kilka",
"error.not_enough_space": "Za mało wolnego miejsca na dysku na obrazy",
"error.no_motion_photo": "To zdjęcie nie ma wideo, które Filee może odczytać (Motion Photo z Androida lub Live Photo z iPhone'a z plikiem MOV obok)",
"error.live_photo_start": "Klip zaczyna się po końcu tego wideo. Wybierz wcześniejszy „Początek klipu”",
@@ -222,6 +223,14 @@
"preset.extract_motion": "Wyodrębnij wideo z Live Photo",
"preset.live_photo_iphone": "Live Photo (iPhone)",
"preset.motion_photo_android": "Motion Photo (Android)",
+ "preset.compress_image": "Kompresuj obraz",
+ "preset.compress_video": "Kompresuj wideo",
+ "preset.video_from_images": "Wideo ze zdjęć",
+ "preset.extract_audio": "Wyodrębnij dźwięk",
+ "preset.merge_videos": "Połącz wideo",
+ "preset.compress_audio": "Kompresuj dźwięk",
+ "preset.merge_audio": "Połącz dźwięk",
+ "preset.remove_metadata": "Usuń metadane",
"format.folder": "Folder",
"format.category.Image": "Obraz",
@@ -491,6 +500,9 @@
"presets.frame_estimate": "Minuta wideo w 30 kl./s daje {0} obrazów, najwyżej {1} na wideo.",
"presets.extract_motion_photo": "Wyodrębnij wideo z Live/Motion Photo",
"presets.extract_motion_photo_hint": "Zdjęcie staje się zapisanym z nim wideo: tym wewnątrz Motion Photo z Androida lub plikiem MOV obok Live Photo z iPhone'a.\nInne obrazy stają się wideo z nieruchomym obrazem.",
+ "presets.slide_seconds": "Sekundy na zdjęcie",
+ "presets.crossfade": "Przenikanie między zdjęciami",
+ "presets.crossfade_hint": "Każde zdjęcie przez sekundę przechodzi w następne zamiast nagłego cięcia.",
"presets.group.live_photo": "Live Photo / Motion Photo",
"presets.live_photo": "Wideo staje się",
"presets.live_photo.None": "Jedną nieruchomą klatką",
diff --git a/src/Filee.App/Assets/i18n/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 3eb526c7..bbdb49b6 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -82,6 +82,7 @@
"error.no_route": "Нет движка для такой конвертации",
"error.cannot_turn": "Поворот и отражение работают только с изображениями",
"error.too_many_frames": "Слишком много кадров для сохранения картинками — увеличьте «Каждый N-й кадр»",
+ "error.too_many_pictures": "Слишком много картинок для одного видео — разделите их на несколько",
"error.not_enough_space": "Не хватает места на диске для картинок",
"error.no_motion_photo": "В этом фото нет видео, которое Filee может прочитать (Motion Photo с Android или Live Photo с iPhone с файлом MOV рядом)",
"error.live_photo_start": "Клип начинается после конца этого видео. Выберите более раннее «Начало клипа»",
@@ -222,6 +223,14 @@
"preset.extract_motion": "Видео из Live Photo",
"preset.live_photo_iphone": "Live Photo (iPhone)",
"preset.motion_photo_android": "Motion Photo (Android)",
+ "preset.compress_image": "Сжать изображение",
+ "preset.compress_video": "Сжать видео",
+ "preset.video_from_images": "Видео из фото",
+ "preset.extract_audio": "Извлечь звук",
+ "preset.merge_videos": "Объединить видео",
+ "preset.compress_audio": "Сжать аудио",
+ "preset.merge_audio": "Объединить аудио",
+ "preset.remove_metadata": "Удалить метаданные",
"format.folder": "Папка",
"format.category.Image": "Изображение",
@@ -491,6 +500,9 @@
"presets.frame_estimate": "Минута видео с 30 кадрами в секунду даст картинок: {0}, не больше {1} на одно видео.",
"presets.extract_motion_photo": "Извлекать видео из Live/Motion Photo",
"presets.extract_motion_photo_hint": "Фото превращается в видео, сохранённое вместе с ним: встроенное в Motion Photo с Android или файл MOV рядом с Live Photo с iPhone.\nДругие картинки превращаются в видео из неподвижного кадра.",
+ "presets.slide_seconds": "Секунд на картинку",
+ "presets.crossfade": "Плавный переход между картинками",
+ "presets.crossfade_hint": "Каждая картинка за секунду плавно сменяется следующей, без резкой склейки.",
"presets.group.live_photo": "Live Photo / Motion Photo",
"presets.live_photo": "Видео становится",
"presets.live_photo.None": "Одним неподвижным кадром",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 6247a2b0..f3f8f9cc 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -82,6 +82,7 @@
"error.no_route": "没有引擎可以完成此转换",
"error.cannot_turn": "只能旋转和翻转图片",
"error.too_many_frames": "帧数太多,请调大“每 N 帧”",
+ "error.too_many_pictures": "图片太多,无法放进一个视频,请分成几次",
"error.not_enough_space": "磁盘空间不足,无法保存这些图片",
"error.no_motion_photo": "这张照片中没有可读取的视频(安卓动态照片,或旁边有 MOV 的 iPhone 实况照片)",
"error.live_photo_start": "片段开始位置在视频结束之后。请把“片段开始”设得更早",
@@ -222,6 +223,14 @@
"preset.extract_motion": "提取实况/动态照片视频",
"preset.live_photo_iphone": "实况照片(iPhone)",
"preset.motion_photo_android": "动态照片(安卓)",
+ "preset.compress_image": "压缩图片",
+ "preset.compress_video": "压缩视频",
+ "preset.video_from_images": "图片生成视频",
+ "preset.extract_audio": "提取音频",
+ "preset.merge_videos": "合并视频",
+ "preset.compress_audio": "压缩音频",
+ "preset.merge_audio": "合并音频",
+ "preset.remove_metadata": "移除元数据",
"format.folder": "文件夹",
"format.category.Image": "图片",
@@ -491,6 +500,9 @@
"presets.frame_estimate": "30 fps 的视频每分钟生成 {0} 张图片,每个视频最多 {1} 张。",
"presets.extract_motion_photo": "提取实况/动态照片中的视频",
"presets.extract_motion_photo_hint": "取出与照片一起保存的视频。安卓动态照片取其中内嵌的视频,iPhone 实况照片取旁边同名的 MOV。\n其他图片仍转换为静态画面的视频。",
+ "presets.slide_seconds": "每张图片秒数",
+ "presets.crossfade": "图片之间交叉淡化",
+ "presets.crossfade_hint": "每张图片在一秒内渐变到下一张,而不是直接切换。",
"presets.group.live_photo": "实况/动态照片",
"presets.live_photo": "视频保存为",
"presets.live_photo.None": "一张静态画面",
diff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.cs
index f06ce0dc..bb6164d7 100644
--- a/src/Filee.App/Services/AppHost.cs
+++ b/src/Filee.App/Services/AppHost.cs
@@ -56,7 +56,8 @@ public static class AppHost
EngineRegistry.FindPdfMerger(sp.GetRequiredService<IReadOnlyList<IConverter>>()),
sp.GetRequiredService<ILogger<JobQueue>>(),
EngineRegistry.FindFileCombiner(sp.GetRequiredService<IReadOnlyList<IConverter>>()),
- EngineRegistry.FindTiffMerger(sp.GetRequiredService<IReadOnlyList<IConverter>>())));
+ EngineRegistry.FindTiffMerger(sp.GetRequiredService<IReadOnlyList<IConverter>>()),
+ EngineRegistry.FindMediaJoiner(sp.GetRequiredService<IReadOnlyList<IConverter>>())));
// Files dragged from a browser with only an address are downloaded without the browser's cookies.
services.AddSingleton(_ => new WebDownloader(userAgent: $"Filee/{typeof(AppHost).Assembly.GetName().Version?.ToString(3)}"));
diff --git a/src/Filee.App/Services/PresetAvailability.cs b/src/Filee.App/Services/PresetAvailability.cs
index 55ee80f6..1955cb6e 100644
--- a/src/Filee.App/Services/PresetAvailability.cs
+++ b/src/Filee.App/Services/PresetAvailability.cs
@@ -106,6 +106,23 @@ public sealed class PresetAvailability
if (formats.Count == 0)
return new(PresetUse.Unusable, _loc["error.unsupported_source"]);
+ // "Merge videos" / "Merge audio" / "Video from images": FFmpeg joins the files, so a route into the target (or,
+ // for pictures, into PNG and from PNG into a video) says whether it is installed.
+ if (preset.JoinsIntoOneMedia)
+ {
+ var target = preset.TargetFormat;
+ bool Joinable(RoutePlanner planner) => formats.Any(f => preset.Media.Slideshow
+ ? f.Category is FormatCategory.Image or FormatCategory.Vector
+ && (f.Id == "png" || planner.CanConvert(f.Id, "png")) && planner.CanConvert("png", target)
+ : (f.Category == FormatCategory.Video || f.Category == FormatCategory.Audio && target == "m4a")
+ && planner.CanConvert(f.Id, target));
+ if (Joinable(installedPlanner()))
+ return new(PresetUse.Usable, null);
+ return packageEnabling(Joinable) is { } joiner
+ ? new(PresetUse.NeedsPackage, _loc.Format("engine.reason.needs_package", joiner.Name))
+ : new(PresetUse.Unusable, _loc["error.no_route"]);
+ }
+
var merge = preset.Pdf.MergeIntoSingle && preset.TargetFormat == "pdf";
var turns = preset.Image.TurnsOrMirrors;
string TargetFor(FileFormat f) => preset.TargetFormat == BuiltInData.SameAsSource ? f.Id : preset.TargetFormat;
diff --git a/src/Filee.App/Services/RadialController.cs b/src/Filee.App/Services/RadialController.cs
index 16e0bdd8..7682481f 100644
--- a/src/Filee.App/Services/RadialController.cs
+++ b/src/Filee.App/Services/RadialController.cs
@@ -327,7 +327,8 @@ public sealed class RadialController(
return;
}
- if (preset.TargetFormat == "pdf" && preset.Pdf.MergeIntoSingle && sources.Count > 1)
+ // Merged PDFs, joined clips and slideshows follow the order the user picks.
+ if ((preset.TargetFormat == "pdf" && preset.Pdf.MergeIntoSingle || preset.JoinsIntoOneMedia) && sources.Count > 1)
{
Close(animate: false);
_ = MergeInOrderAsync(sources, preset.Clone(), web);
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index d76f638b..5758e1c0 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -127,6 +127,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_livePhotoLength = _edit.Media.LivePhotoLength;
_livePhotoCover = _edit.Media.LivePhotoCover;
_frameInterval = _edit.Media.FrameInterval > 0 ? _edit.Media.FrameInterval : 1;
+ _isSlideshow = _edit.Media.Slideshow;
+ _slideSeconds = _edit.Media.SlideDuration;
+ _crossfade = _edit.Media.Crossfade;
_traceMode = TraceModes.First(m => m.Value == _edit.Trace.Mode);
_animationSpeed = AnimationSpeeds.First(s => s.Value == _edit.Image.PlaybackSpeed);
_traceColors = Math.Clamp(_edit.Trace.Colors, TracingOptions.MinColors, TracingOptions.MaxColors);
@@ -205,7 +208,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding),
nameof(AudioCodecs), nameof(AudioCodecChoice), nameof(ShowAudioCodec),
nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote),
- nameof(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace), nameof(ShowExtractMotionPhoto),
+ nameof(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace), nameof(ShowExtractMotionPhoto), nameof(ShowSlideshow),
nameof(ShowLivePhotoChoice), nameof(LivePhotoKinds), nameof(LivePhotoChoice), nameof(IsLivePhoto), nameof(LivePhotoHint))]
private Choice<string> _target;
@@ -419,6 +422,11 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[ObservableProperty, NotifyPropertyChangedFor(nameof(FrameEstimate))]
private int _frameInterval = 1;
+ /// <summary>"Video from images" (MediaOptions.Slideshow): how long each picture shows, and fades between them.</summary>
+ private readonly bool _isSlideshow;
+ [ObservableProperty] private double _slideSeconds;
+ [ObservableProperty] private bool _crossfade;
+
/// <summary>How many pictures a minute of 30 fps video gives at the chosen interval, and the limit per video.</summary>
public string FrameEstimate => _loc.Format("presets.frame_estimate",
(int)Math.Ceiling(1800.0 / Math.Clamp(FrameInterval, 1, 1000)), MediaOptions.MaxFrames.ToString("N0", System.Globalization.CultureInfo.InvariantCulture));
@@ -518,6 +526,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public bool ShowExtractNote => TargetId == FormatRegistry.Folder;
/// <summary>"Save every frame" of a video: PNG and JPG (format ids, <see cref="MediaOptions.FrameTargets"/>).</summary>
public bool ShowSaveEveryFrame => !IsTool && !IsLivePhoto && MediaOptions.FrameTargets.Contains(TargetId);
+ /// <summary>The slideshow options, for a preset that makes a video of pictures (MP4).</summary>
+ public bool ShowSlideshow => _isSlideshow && MediaOptions.JoinTargets.Contains(TargetId) && TargetIsVideo;
/// <summary>The video of a Live / Motion Photo: MP4 and MOV (<see cref="MediaOptions.MotionPhotoTargets"/>).</summary>
public bool ShowExtractMotionPhoto => !IsTool && MediaOptions.MotionPhotoTargets.Contains(TargetId);
/// <summary>
@@ -617,6 +627,11 @@ public sealed partial class PresetEditorViewModel : ObservableObject
media.SaveEveryFrame = ShowSaveEveryFrame && SaveEveryFrame;
media.FrameInterval = media.SaveEveryFrame ? Math.Clamp(FrameInterval, 1, 1000) : 1;
media.ExtractMotionPhoto = ShowExtractMotionPhoto && ExtractMotionPhoto;
+ if (ShowSlideshow)
+ {
+ media.SlideSeconds = double.IsFinite(SlideSeconds) ? Math.Clamp(SlideSeconds, MediaOptions.MinSlideSeconds, MediaOptions.MaxSlideSeconds) : 3;
+ media.Crossfade = Crossfade;
+ }
media.LivePhoto = IsLivePhoto ? _livePhotoValue : LivePhotoKind.None;
static double Seconds(double value, double fallback, double min, double max) =>
double.IsFinite(value) ? Math.Clamp(value, min, max) : fallback;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 8c81df87..717ccbcc 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -193,6 +193,14 @@
<TextBlock Classes="h2" Text="{DynamicResource presets.group.media}" />
<CheckBox Content="{DynamicResource presets.extract_motion_photo}" IsChecked="{Binding ExtractMotionPhoto}"
IsVisible="{Binding ShowExtractMotionPhoto}" ToolTip.Tip="{DynamicResource presets.extract_motion_photo_hint}" />
+ <StackPanel Spacing="6" IsVisible="{Binding ShowSlideshow}">
+ <Grid ColumnDefinitions="Auto,12,120">
+ <TextBlock Classes="label" VerticalAlignment="Center" Text="{DynamicResource presets.slide_seconds}" />
+ <NumericUpDown Grid.Column="2" Value="{Binding SlideSeconds}" Minimum="0.5" Maximum="60" Increment="0.5" FormatString="0.#" />
+ </Grid>
+ <CheckBox Content="{DynamicResource presets.crossfade}" IsChecked="{Binding Crossfade}"
+ ToolTip.Tip="{DynamicResource presets.crossfade_hint}" />
+ </StackPanel>
<Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowMediaQuality}">
<StackPanel>
<TextBlock Classes="label" Text="{DynamicResource presets.media_quality}" />
diff --git a/src/Filee.Cli/CliHost.cs b/src/Filee.Cli/CliHost.cs
index 14bb8b43..6dff13a2 100644
--- a/src/Filee.Cli/CliHost.cs
+++ b/src/Filee.Cli/CliHost.cs
@@ -36,7 +36,7 @@ internal sealed class CliHost : IAsyncDisposable
var converters = EngineRegistry.CreateAll(new EngineEnvironment(store.Directory));
var catalog = new ConverterCatalog(converters) { Priority = store.Settings.EnginePriority };
var queue = new JobQueue(catalog, EngineRegistry.FindPdfMerger(converters), combiner: EngineRegistry.FindFileCombiner(converters),
- tiffMerger: EngineRegistry.FindTiffMerger(converters));
+ tiffMerger: EngineRegistry.FindTiffMerger(converters), mediaJoiner: EngineRegistry.FindMediaJoiner(converters));
return new CliHost(store, catalog, queue);
}
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index 3a84b9d8..11b521b9 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -196,6 +196,29 @@ public interface ITiffMerger
Task MergeAsync(IReadOnlyList<string> inputPaths, string outputPath, Presets.ImageOptions options, CancellationToken cancellationToken);
}
+/// <summary>
+/// Joins several videos or audio files into one, one after the other, or turns pictures into one video ("Merge
+/// videos", "Merge audio", "Video from images"). Implemented by the FFmpeg engine; <see cref="JobQueue"/> uses it when
+/// a preset joins files (<see cref="Preset.JoinsIntoOneMedia"/>).
+/// </summary>
+public interface IMediaJoiner
+{
+ /// <summary>True if files can be joined into <paramref name="format"/> now (FFmpeg is installed).</summary>
+ bool CanJoinInto(string format);
+
+ /// <summary>
+ /// Writes every file of <paramref name="inputPaths"/>, in order, into <paramref name="outputPath"/>: video or audio
+ /// clips back to back, or pictures shown one after the other (<see cref="MediaOptions.Slideshow"/>).
+ /// </summary>
+ /// <param name="inputPaths">Videos, audio files, or pictures (PNG, as the image engines wrote them).</param>
+ /// <param name="outputPath">File to create; removed again when the join fails.</param>
+ /// <param name="format">Target format id, <c>"mp4"</c> or <c>"m4a"</c>.</param>
+ /// <param name="preset">Options, e.g. <see cref="MediaOptions.SlideSeconds"/>.</param>
+ /// <param name="workDirectory">Scratch directory for intermediate files; deleted after the job.</param>
+ Task JoinAsync(IReadOnlyList<string> inputPaths, string outputPath, string format, Preset preset,
+ string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken);
+}
+
/// <summary>
/// Packs several files, unchanged, into one archive ("Compress into one archive"). Implemented by the archive engine;
/// <see cref="JobQueue"/> uses it when a preset sets <see cref="ArchiveOptions.CombineIntoOne"/>.
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 9cf06228..dd04a7ec 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -17,6 +17,7 @@ public sealed class JobQueue : IAsyncDisposable
private readonly IPdfMerger? _pdfMerger;
private readonly IFileCombiner? _combiner;
private readonly ITiffMerger? _tiffMerger;
+ private readonly IMediaJoiner? _mediaJoiner;
private readonly ILogger _log;
private readonly Channel<ConversionJob> _channel = Channel.CreateUnbounded<ConversionJob>();
private readonly ConcurrentDictionary<string, SemaphoreSlim> _engineGates = new();
@@ -35,13 +36,15 @@ public sealed class JobQueue : IAsyncDisposable
/// <param name="log">Optional logger.</param>
/// <param name="combiner">Used by "Compress into one archive" presets (<see cref="ArchiveOptions.CombineIntoOne"/>).</param>
/// <param name="tiffMerger">Used by multi-page TIFF presets (<see cref="ImageOptions.MultiPageTiff"/>).</param>
+ /// <param name="mediaJoiner">Used by "Merge videos", "Merge audio" and "Video from images" (<see cref="Preset.JoinsIntoOneMedia"/>).</param>
public JobQueue(ConverterCatalog catalog, IPdfMerger? pdfMerger = null, ILogger<JobQueue>? log = null, IFileCombiner? combiner = null,
- ITiffMerger? tiffMerger = null)
+ ITiffMerger? tiffMerger = null, IMediaJoiner? mediaJoiner = null)
{
_catalog = catalog;
_pdfMerger = pdfMerger;
_combiner = combiner;
_tiffMerger = tiffMerger;
+ _mediaJoiner = mediaJoiner;
_log = log ?? (ILogger)NullLogger.Instance;
_worker = Task.Run(WorkLoopAsync);
}
@@ -102,8 +105,12 @@ public sealed class JobQueue : IAsyncDisposable
// One file is enough: a 10-page PDF becomes one 10-page TIFF.
var multiPageTiff = job.Preset.Image.MultiPageTiff && job.Preset.TargetFormat == "tiff" && _tiffMerger is not null;
+ // Clips back to back, or pictures one after the other, in the order they were dropped.
+ var join = job.Preset.JoinsIntoOneMedia && _mediaJoiner is not null;
- if (merge)
+ if (join)
+ await RunJoinedMediaAsync(job, planner, workDir);
+ else if (merge)
await RunMergedAsync(job, planner, workDir);
else if (multiPageTiff)
await RunMultiPageTiffAsync(job, planner, workDir);
@@ -333,6 +340,127 @@ public sealed class JobQueue : IAsyncDisposable
Notify(job);
}
+ /// <summary>
+ /// "Merge videos" / "Merge audio": the videos or audio files go into one file as they are. "Video from images":
+ /// every picture becomes PNG in the work directory first (a PNG is taken as it is), with its orientation applied by
+ /// the image engines, then the pictures become one video. The output is named after the first file.
+ /// </summary>
+ private async Task RunJoinedMediaAsync(ConversionJob job, RoutePlanner planner, string workDir)
+ {
+ var slideshow = job.Preset.Media.Slideshow;
+ var target = FormatRegistry.Get(job.Preset.TargetFormat);
+ var parts = new IReadOnlyList<string>?[job.Files.Count];
+ await Parallel.ForEachAsync(Enumerable.Range(0, job.Files.Count),
+ new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
+ async (i, _) =>
+ {
+ var file = job.Files[i];
+ if (Stopped(file))
+ return;
+ var source = FormatRegistry.Detect(file.SourcePath);
+ if (source is null)
+ {
+ FailFile(job, file, "error.unsupported_source", "." + FormatRegistry.ExtensionOf(file.SourcePath));
+ return;
+ }
+ if (IsEmptyFile(file.SourcePath))
+ {
+ FailFile(job, file, "error.empty_file", null);
+ return;
+ }
+ if (slideshow)
+ {
+ parts[i] = source.Id == "png" && !job.Preset.Image.TurnsOrMirrors
+ ? [file.SourcePath]
+ : await RunFileAsync(job, file, i + 1, planner, workDir, finalOutput: false, intermediate: "png");
+ return;
+ }
+ // A video's sound can join an audio file; a picture or a document joins nothing.
+ var joins = source.Category == FormatCategory.Video
+ || source.Category == FormatCategory.Audio && target.Category == FormatCategory.Audio;
+ if (!joins)
+ {
+ FailFile(job, file, "error.no_route", $"{source.Id} → {target.Id}");
+ return;
+ }
+ parts[i] = [file.SourcePath];
+ });
+
+ var joined = job.Files.Where((f, i) => parts[i] is { Count: > 0 } && f.State != FileState.Failed).ToList();
+ var inputs = parts.Where(p => p is not null).SelectMany(p => p!).ToList();
+ if (inputs.Count == 0 || job.CancellationToken.IsCancellationRequested)
+ {
+ Notify(job);
+ return;
+ }
+
+ var first = joined[0];
+ var output = CreateFinalAllocator(job, first.SourcePath, 1).Allocate(target.PrimaryExtension);
+ if (output is null)
+ {
+ foreach (var f in joined)
+ {
+ f.State = FileState.Skipped;
+ f.Progress = 1;
+ }
+ Notify(job);
+ return;
+ }
+
+ foreach (var f in joined)
+ f.State = FileState.Running;
+ Notify(job);
+ var floor = joined.Min(f => f.Progress);
+ var progress = new Progress<double>(p =>
+ {
+ // Reports arrive on the thread pool, possibly out of order: progress only moves forward.
+ var value = floor + (1 - floor) * Math.Clamp(p, 0, 1);
+ if (value <= first.Progress)
+ return;
+ foreach (var f in joined)
+ f.Progress = value;
+ Notify(job);
+ });
+
+ try
+ {
+ await _mediaJoiner!.JoinAsync(inputs, output, target.Id, job.Preset, workDir, progress, job.CancellationToken);
+ first.Outputs.Add(output);
+ foreach (var f in joined)
+ {
+ f.State = FileState.Done;
+ f.Progress = 1;
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ foreach (var f in joined)
+ f.State = FileState.Cancelled;
+ }
+ catch (ConversionRefusedException ex)
+ {
+ _log.LogInformation("Joining {Count} file(s) into {Output} was refused: {Reason}", inputs.Count, output, ex.Message);
+ foreach (var f in joined)
+ FailFile(job, f, ex.ErrorKey, ex.Detail);
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Joining {Count} file(s) into {Output} failed", inputs.Count, output);
+ foreach (var f in joined)
+ FailFile(job, f, "error.conversion_failed", ex.Message);
+ }
+ Notify(job);
+ }
+
+ private void FailFile(ConversionJob job, FileResult file, string key, string? detail)
+ {
+ file.State = FileState.Failed;
+ file.ErrorKey = key;
+ file.ErrorDetail = detail;
+ file.Progress = 1;
+ Notify(job);
+ }
+
/// <summary>A file that would be used as it is although the preset turns or mirrors it.</summary>
private void FailUnturned(ConversionJob job, FileResult file, string detail)
{
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index 4a3c96c0..d9342014 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -75,6 +75,7 @@ public static class BuiltInData
.. FramePresets(),
.. MotionPhotoPresets(),
.. LivePhotoPresets(),
+ .. MediaToolPresets(),
new() { Id = "to-docx", Name = "DOCX", TargetFormat = "docx" },
new() { Id = "to-hwpx", Name = "HWPX", TargetFormat = "hwpx" },
.. HwpPresets(),
@@ -111,6 +112,62 @@ public static class BuiltInData
new() { Id = "motion-photo-android", NameKey = "preset.motion_photo_android", TargetFormat = "jpg", Media = { LivePhoto = LivePhotoKind.Android } },
];
+ /// <summary>
+ /// Everyday tools (added in settings schema 33): smaller copies of images, videos and audio, a video of photos,
+ /// a video's sound as M4A, videos or audio files joined into one, and a copy without metadata. On the back faces
+ /// of the images, PDF, video and audio donuts where they have room.
+ /// </summary>
+ public static List<Preset> MediaToolPresets() =>
+ [
+ new()
+ {
+ // Quality 75 like most photo apps' "smaller"; a JPEG saved below it stays at its own quality.
+ Id = "compress-image", NameKey = "preset.compress_image", TargetFormat = SameAsSource,
+ Image = { Quality = 75, MaxCompression = true, TiffCompression = TiffCompression.Zip },
+ Output = { FileNamePattern = "{name}_compressed" },
+ },
+ new()
+ {
+ // H.264 at the Small quality, at most 1080p: plays everywhere, a fraction of a phone video's size.
+ Id = "compress-video", NameKey = "preset.compress_video", TargetFormat = "mp4",
+ Media = { Quality = MediaQuality.Small, MaxHeight = 1080 }, Output = { FileNamePattern = "{name}_compressed" },
+ },
+ new()
+ {
+ Id = "video-from-images", NameKey = "preset.video_from_images", TargetFormat = "mp4",
+ Media = { Slideshow = true }, Output = { FileNamePattern = "{name}_video" },
+ },
+ new()
+ {
+ Id = "extract-audio", NameKey = "preset.extract_audio", TargetFormat = "m4a",
+ Media = { CopyAudioWhenPossible = true },
+ },
+ new()
+ {
+ Id = "merge-videos", NameKey = "preset.merge_videos", TargetFormat = "mp4",
+ Media = { JoinIntoOne = true }, Output = { FileNamePattern = "{name}_merged" },
+ },
+ new()
+ {
+ // AAC at the Small quality: 128 kbit/s for stereo.
+ Id = "compress-audio", NameKey = "preset.compress_audio", TargetFormat = "m4a",
+ Media = { Quality = MediaQuality.Small }, Output = { FileNamePattern = "{name}_compressed" },
+ },
+ new()
+ {
+ Id = "merge-audio", NameKey = "preset.merge_audio", TargetFormat = "m4a",
+ Media = { JoinIntoOne = true }, Output = { FileNamePattern = "{name}_merged" },
+ },
+ new()
+ {
+ // Everything goes, the colour profile too; the preset editor can keep it. File dates are new ones.
+ Id = "remove-metadata", NameKey = "preset.remove_metadata", TargetFormat = SameAsSource,
+ Image = { Quality = 90, KeepMetadata = false, KeepColorProfile = false, KeepSourceQuality = true },
+ Pdf = { RemoveMetadata = true }, Media = { RemoveMetadata = true },
+ Output = { FileNamePattern = "{name}_clean" },
+ },
+ ];
+
/// <summary>
/// "Compress PDF": pictures at 150 dpi, the rest compressed losslessly (added in settings schema 20). On no default
/// donut, the PDF donut is full: users add it in Settings → Toolbar.
@@ -363,14 +420,15 @@ public static class BuiltInData
Id = "images", NameKey = "profile.images",
Extensions = ExtensionsOf(FormatCategory.Image),
PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "trace-svg", "trace-line-art", "to-tiff", "to-bmp", "to-ico", "half-size"],
- BackPresetIds = ["tool-crop", "rotate", "flip", "remove-background", "grayscale", "extract-motion", "to-avif", "to-gif", "merge-pdf", "zip-all"],
+ BackPresetIds = ["tool-crop", "rotate", "flip", "remove-background", "grayscale", "extract-motion", "to-avif", "to-gif", "merge-pdf",
+ "compress-image", "remove-metadata", "zip-all"],
},
new()
{
Id = "pdf", NameKey = "profile.pdf",
Extensions = ["pdf"],
PresetIds = [.. PdfDonut],
- BackPresetIds = ["compress-pdf", "to-webp", "to-tiff", "to-html", "to-odt", "to-rtf", "to-azw3", "to-cbz", "zip-all"],
+ BackPresetIds = ["compress-pdf", "to-webp", "to-tiff", "to-html", "to-odt", "to-rtf", "to-azw3", "to-cbz", "remove-metadata", "zip-all"],
},
new()
{
@@ -460,14 +518,14 @@ public static class BuiltInData
// Every frame as pictures is on no front (a long video gives thousands of files): behind a flip, a drop that
// misses its slice doesn't start it. Live / Motion Photos of a clip are there too.
BackPresetIds = ["mp4-av1", "to-webp", "extract-frames-png", "extract-frames-jpg", "live-photo-iphone", "motion-photo-android",
- "to-m4a", "to-wav", "to-flac", "zip-all"],
+ "extract-audio", "to-wav", "to-flac", "compress-video", "merge-videos", "zip-all"],
},
new()
{
Id = "audio", NameKey = "profile.audio",
Extensions = ExtensionsOf(FormatCategory.Audio),
PresetIds = ["to-mp3", "mp3-128", "to-m4a", "to-wav", "to-flac", "to-ogg", "to-opus", "to-aac"],
- BackPresetIds = ["to-alac", "zip-all"],
+ BackPresetIds = ["to-alac", "compress-audio", "merge-audio", "remove-metadata", "zip-all"],
},
new()
{
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index ed631510..09a8b205 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -164,6 +164,14 @@ public sealed class Preset
MediaOptions.LivePhotoTargets(Media.LivePhoto).Contains(TargetFormat)
&& Formats.FormatRegistry.FindById(sourceFormat)?.Category == Formats.FormatCategory.Video;
+ /// <summary>
+ /// True for "Merge videos", "Merge audio" and "Video from images": every dropped file goes, in order, into one
+ /// video or audio file (<see cref="MediaOptions.JoinIntoOne"/>, <see cref="MediaOptions.Slideshow"/>).
+ /// </summary>
+ [JsonIgnore]
+ public bool JoinsIntoOneMedia =>
+ (Media.JoinIntoOne || Media.Slideshow) && MediaOptions.JoinTargets.Contains(TargetFormat);
+
/// <summary>True for a <see cref="PresetKind.Tool"/>.</summary>
[JsonIgnore]
public bool IsTool => Kind == PresetKind.Tool;
@@ -273,6 +281,18 @@ public sealed class ImageOptions
/// </summary>
public bool KeepColorProfile { get; set; } = true;
+ /// <summary>
+ /// "Compress image": PNG with zlib's best compression, and a JPEG never saved above the quality it had (a photo
+ /// saved at 75 would otherwise come back at the preset's quality, bigger and no better).
+ /// </summary>
+ public bool MaxCompression { get; set; }
+
+ /// <summary>
+ /// JPEG → JPEG at the quality the photo had (ImageMagick's estimate), not at <see cref="Quality"/>: "Remove
+ /// metadata" re-encodes the picture as little as it can. Other targets use <see cref="Quality"/>.
+ /// </summary>
+ public bool KeepSourceQuality { get; set; }
+
/// <summary>Convert to grayscale.</summary>
public bool Grayscale { get; set; }
@@ -403,6 +423,12 @@ public sealed class PdfOptions
[JsonConverter(typeof(LenientEnumJsonConverter<PdfCompression>))]
public PdfCompression Compression { get; set; }
+ /// <summary>
+ /// For PDF → PDF: drop the document information (title, author, dates, creator) and every XMP packet. Pages,
+ /// links, bookmarks and form fields stay as they are.
+ /// </summary>
+ public bool RemoveMetadata { get; set; }
+
/// <summary>
/// With <see cref="Compression"/>: also let Ghostscript rewrite the PDF when it is installed, and keep whichever
/// result is smaller. Off by default: it rewrites the whole file (fonts, structure), not only the pictures.
@@ -545,6 +571,60 @@ public sealed class MediaOptions
/// </summary>
public const long MaxFrames = 100_000;
+ /// <summary>Targets the dropped files can be joined into (<see cref="JoinIntoOne"/>, <see cref="Slideshow"/>).</summary>
+ public static readonly IReadOnlyList<string> JoinTargets = ["mp4", "m4a"];
+
+ /// <summary>
+ /// MP4 or M4A: every dropped video (or audio file) goes, in order and without gaps, into one file named after the
+ /// first. Clips that share codecs and picture size are copied; others are encoded to match the first.
+ /// </summary>
+ public bool JoinIntoOne { get; set; }
+
+ /// <summary>
+ /// MP4: the dropped pictures become one video, each shown for <see cref="SlideSeconds"/>, fitted into
+ /// <see cref="SlideshowWidth"/> × <see cref="SlideshowHeight"/> with black bars.
+ /// </summary>
+ public bool Slideshow { get; set; }
+
+ /// <summary>Shortest and longest time one picture of a <see cref="Slideshow"/> is shown, in seconds.</summary>
+ public const double MinSlideSeconds = 0.5, MaxSlideSeconds = 60;
+
+ /// <summary>With <see cref="Slideshow"/>: how long each picture is shown, in seconds.</summary>
+ public double SlideSeconds { get; set; } = 3;
+
+ /// <summary>With <see cref="Slideshow"/>: fade from one picture into the next instead of cutting.</summary>
+ public bool Crossfade { get; set; } = true;
+
+ /// <summary>With <see cref="Crossfade"/>: how long a fade takes, in seconds (at most half a picture's time).</summary>
+ public double CrossfadeSeconds { get; set; } = 1;
+
+ /// <summary>Frame size of a <see cref="Slideshow"/> (1080p unless the preset says otherwise).</summary>
+ public int SlideshowWidth { get; set; } = 1920;
+
+ /// <inheritdoc cref="SlideshowWidth"/>
+ public int SlideshowHeight { get; set; } = 1080;
+
+ /// <summary>
+ /// Audio target: copy the sound as it is when the target takes its codec (AAC from a phone video into M4A), with
+ /// no bitrate, channel or Small quality asking for an encode. Off: always encoded, as before the option existed.
+ /// </summary>
+ public bool CopyAudioWhenPossible { get; set; }
+
+ /// <summary>
+ /// Video and audio: drop the tags (title, artist, dates, location, camera, encoder) and chapters, copying the
+ /// streams as they are. Only when the file keeps its format.
+ /// </summary>
+ public bool RemoveMetadata { get; set; }
+
+ /// <summary><see cref="SlideSeconds"/> within its limits (a hand-edited preset file may hold anything).</summary>
+ [JsonIgnore]
+ public double SlideDuration => double.IsFinite(SlideSeconds) ? Math.Clamp(SlideSeconds, MinSlideSeconds, MaxSlideSeconds) : 3;
+
+ /// <summary>The fade between two pictures in seconds: 0 without <see cref="Crossfade"/>, never over half a picture's time.</summary>
+ [JsonIgnore]
+ public double FadeDuration => Crossfade && double.IsFinite(CrossfadeSeconds) && CrossfadeSeconds > 0
+ ? Math.Min(CrossfadeSeconds, SlideDuration / 2)
+ : 0;
public MediaOptions Clone() => (MediaOptions)MemberwiseClone();
}
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 4f488dcb..3df95d28 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -112,7 +112,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 32;
+ public const int CurrentSchemaVersion = 33;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index 7aff0c84..15e65f5d 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -750,6 +750,48 @@ internal static class SettingsMigrations
// v32: logs and script source, Video CD DAT and Workbench archives learn their donuts; custom claims stay put.
if (from < 32)
changed |= LearnExtensions(profiles, out _, ["log", "py", "pac", "bat", "command", "dat", "wbpz"]);
+ // v33: everyday tools (compress image / video / audio, video from images, extract audio, merge videos / audio,
+ // remove metadata), after "Motion Photo (Android)" as in a new library, and on the back faces of the
+ // built-in donuts before "One ZIP" where they have room and the user hasn't put them there already.
+ if (from < 33)
+ changed |= AddMediaTools(presets, profiles);
+ return changed;
+ }
+
+ /// <summary>Where schema 33 offers its tools: (donut, presets for its back face).</summary>
+ private static readonly (string Profile, string[] Presets)[] Version33Offers =
+ [
+ ("images", ["compress-image", "remove-metadata"]),
+ ("pdf", ["remove-metadata"]),
+ ("video", ["compress-video", "merge-videos"]),
+ ("audio", ["compress-audio", "merge-audio", "remove-metadata"]),
+ ];
+
+ private static bool AddMediaTools(List<Preset> presets, List<ToolbarProfile> profiles)
+ {
+ var changed = false;
+ var at = presets.FindLastIndex(p => p.Id is "motion-photo-android" or "live-photo-iphone" or "extract-motion");
+ at = at < 0 ? presets.Count : at + 1;
+ foreach (var tool in BuiltInData.MediaToolPresets())
+ {
+ if (presets.Any(p => p.Id == tool.Id))
+ continue;
+ presets.Insert(Math.Min(at++, presets.Count), tool);
+ changed = true;
+ }
+ foreach (var (profileId, ids) in Version33Offers)
+ {
+ if (profiles.FirstOrDefault(p => p.Id == profileId) is not { BackPresetIds: { } back } profile)
+ continue;
+ foreach (var id in ids)
+ {
+ if (back.Contains(id) || profile.PresetIds.Contains(id) || back.Count >= ToolbarProfile.MaxSlices
+ || presets.All(p => p.Id != id))
+ continue;
+ InsertBefore(back, id, "zip-all");
+ changed = true;
+ }
+ }
return changed;
}
diff --git a/src/Filee.Engines/EngineRegistry.cs b/src/Filee.Engines/EngineRegistry.cs
index b9c0f010..dc9a98ed 100644
--- a/src/Filee.Engines/EngineRegistry.cs
+++ b/src/Filee.Engines/EngineRegistry.cs
@@ -81,4 +81,8 @@ public static class EngineRegistry
/// <summary>Finds the engine that packs several files into one archive ("Compress into one archive").</summary>
public static IFileCombiner? FindFileCombiner(IEnumerable<IConverter> converters) =>
converters.OfType<IFileCombiner>().FirstOrDefault();
+
+ /// <summary>The engine that joins videos, audio files and pictures into one (FFmpeg).</summary>
+ public static IMediaJoiner? FindMediaJoiner(IEnumerable<IConverter> converters) =>
+ converters.OfType<IMediaJoiner>().FirstOrDefault();
}
diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.cs
index 1679e1a9..5fbb8469 100644
--- a/src/Filee.Engines/Magick/ImageEncoder.cs
+++ b/src/Filee.Engines/Magick/ImageEncoder.cs
@@ -283,8 +283,12 @@ internal static class ImageEncoder
var quality = (uint)Math.Clamp(options.Quality, 1, 100);
// Turning a JPEG has to re-encode it: at the photo's own quality (Magick's estimate when it read the file), not
// above it, or a phone photo saved at 75 comes back at 95, bigger and no better.
- if (options.TurnsOrMirrors && targetFormat == "jpg" && image.Format == MagickFormat.Jpeg && image.Quality is > 0 and <= 100)
- quality = Math.Min(quality, image.Quality);
+ // "Compress image" likewise never raises a photo's quality, and "Remove metadata" keeps it as it was.
+ var sourceQuality = targetFormat == "jpg" && image.Format == MagickFormat.Jpeg && image.Quality is > 0 and <= 100 ? image.Quality : 0;
+ if ((options.TurnsOrMirrors || options.MaxCompression) && sourceQuality > 0)
+ quality = Math.Min(quality, sourceQuality);
+ if (options.KeepSourceQuality && sourceQuality > 0)
+ quality = sourceQuality;
switch (targetFormat)
{
case "jpg":
@@ -301,6 +305,11 @@ internal static class ImageEncoder
if (options.WebpLossless)
image.Settings.SetDefine(MagickFormat.WebP, "lossless", true);
break;
+ case "png" when options.MaxCompression:
+ // zlib level 9 with adaptive row filters: the smallest PNG ImageMagick writes, the same pixels.
+ image.Settings.SetDefine(MagickFormat.Png, "compression-level", "9");
+ image.Settings.SetDefine(MagickFormat.Png, "compression-filter", "5");
+ break;
case "tiff":
image.Settings.Compression = options.TiffCompression switch
{
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
index dd7f8a26..94be8ec1 100644
--- a/src/Filee.Engines/Media/FfmpegConverter.cs
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -5,7 +5,8 @@
// writer). Container and codec choices live in MediaEncoding, the process handling in FfmpegRunner, hardware encoders
// in HardwareVideo (options) and HardwareProbe (which one works here).
// Live / Motion Photos (Android, iPhone) give their video when a preset asks for it (LivePhotoSource, MotionPhoto), and
-// a clip of a video becomes one (LivePhotoWriter).
+// a clip of a video becomes one (LivePhotoWriter). Clips and pictures are joined into one file by IMediaJoiner
+// (MediaJoining), and "Remove metadata" copies a file's streams without its tags.
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
@@ -22,7 +23,7 @@ namespace Filee.Engines.Media;
/// <summary>Converts video and audio files with Filee's own copy of FFmpeg.</summary>
/// <param name="logger">Receives which hardware encoders work and why a hardware encode was redone in software.</param>
-public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter, IImageTransformer
+public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter, IImageTransformer, IMediaJoiner
{
private static readonly ConcurrentDictionary<string, string> Versions = new();
@@ -146,6 +147,24 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
: null;
var media = step.Preset.Media;
+ // "Remove metadata": the streams as they are, in the same format, without tags.
+ if (media.RemoveMetadata && step.From == step.To && !still
+ && (MediaEncoding.VideoTargets.ContainsKey(step.To) || MediaEncoding.AudioTargets.ContainsKey(step.To)))
+ {
+ try
+ {
+ await RunPassesAsync(ffmpeg, [new FfmpegPass(MediaEncoding.WithoutMetadata(input, output, step.To, info), 1)], output,
+ info.Duration, progress, cancellationToken);
+ }
+ catch
+ {
+ TryDelete(output);
+ throw;
+ }
+ progress?.Report(1);
+ return [output];
+ }
+
var encoders = still ? null : EncodersOf(ffmpeg);
// Hardware encoding (preset option): the first GPU encoder that passes its test encode, if any.
HardwareEncoder? hardware = null;
@@ -182,6 +201,103 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
return [output];
}
+ public bool CanJoinInto(string format) => MediaOptions.JoinTargets.Contains(format) && (_tools ?? Locate()) is not null;
+
+ public async Task JoinAsync(IReadOnlyList<string> inputPaths, string outputPath, string format, Preset preset,
+ string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var (ffmpeg, ffprobe) = _tools ?? Locate() ?? throw new InvalidOperationException("FFmpeg was not found.");
+ var scratch = Path.Combine(workDirectory, "join-" + Guid.NewGuid().ToString("N")[..8]);
+ Directory.CreateDirectory(scratch);
+ var media = preset.Media;
+ try
+ {
+ if (media.Slideshow)
+ {
+ await SlideshowAsync(ffmpeg, inputPaths, outputPath, media, scratch, progress, cancellationToken);
+ }
+ else
+ {
+ // Probing takes the first few percent.
+ var clips = new List<(string Path, MediaInfo Info)>();
+ for (var i = 0; i < inputPaths.Count; i++)
+ {
+ var path = Path.GetFullPath(inputPaths[i]);
+ clips.Add((path, await MediaInfo.ProbeAsync(ffprobe, path, cancellationToken)));
+ progress?.Report(0.05 * (i + 1) / inputPaths.Count);
+ }
+ var duration = TimeSpan.FromSeconds(clips.Sum(c => c.Info.Duration?.TotalSeconds ?? 0));
+ List<string> args;
+ if (format == "m4a")
+ {
+ if (clips.FirstOrDefault(c => c.Info.Audio is null && c.Info.Video is null) is { Path: { } silent })
+ throw new InvalidOperationException($"{Path.GetFileName(silent)} has no sound.");
+ args = MediaJoining.EncodeAudio(clips, outputPath, media, scratch);
+ }
+ else if (MediaJoining.CanCopyVideos([.. clips.Select(c => c.Info)], media))
+ {
+ var list = Path.Combine(scratch, "clips.txt");
+ await File.WriteAllTextAsync(list, MediaJoining.ConcatList(clips.Select(c => c.Path)), cancellationToken);
+ args = MediaJoining.CopyVideos(list, outputPath, clips[0].Info);
+ }
+ else
+ {
+ var encoder = MediaEncoding.VideoEncoder("mp4", "libx264", media.VideoCodec, EncodersOf(ffmpeg));
+ args = MediaJoining.EncodeVideos(clips, outputPath, media, encoder, scratch);
+ }
+ await RunJoinPassAsync(ffmpeg, args, duration, progress, 0.05, 1, cancellationToken);
+ }
+ if (!File.Exists(outputPath) || new FileInfo(outputPath).Length == 0)
+ throw new InvalidOperationException("FFmpeg did not write any output.");
+ }
+ catch
+ {
+ TryDelete(outputPath);
+ throw;
+ }
+ progress?.Report(1);
+ }
+
+ /// <summary>
+ /// Pictures → one video: each picture is fitted into the frame as a small JPEG first (a fifth of the progress),
+ /// then the slides are encoded with their fades.
+ /// </summary>
+ private async Task SlideshowAsync(string ffmpeg, IReadOnlyList<string> pictures, string output, MediaOptions media, string scratch,
+ IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ if (pictures.Count > MediaJoining.MaxSlides)
+ throw new ConversionRefusedException("error.too_many_pictures", $"{pictures.Count} > {MediaJoining.MaxSlides}");
+ var (width, height) = MediaJoining.SlideshowFrame(media);
+ var slides = new List<string>();
+ for (var i = 0; i < pictures.Count; i++)
+ {
+ var slide = Path.Combine(scratch, $"slide-{i + 1:D4}.jpg");
+ await RunJoinPassAsync(ffmpeg, MediaJoining.PrepareSlide(Path.GetFullPath(pictures[i]), slide, width, height), null,
+ null, 0, 0, cancellationToken);
+ slides.Add(slide);
+ progress?.Report(0.2 * (i + 1) / pictures.Count);
+ }
+ var encoder = MediaEncoding.VideoEncoder("mp4", "libx264", media.VideoCodec, EncodersOf(ffmpeg));
+ await RunJoinPassAsync(ffmpeg, MediaJoining.Slideshow(slides, output, media, encoder, scratch),
+ MediaJoining.SlideshowDuration(slides.Count, media), progress, 0.2, 1, cancellationToken);
+ }
+
+ /// <summary>Runs one join pass, mapping FFmpeg's position onto <paramref name="from"/> … <paramref name="to"/> of the progress.</summary>
+ private static async Task RunJoinPassAsync(string ffmpeg, IReadOnlyList<string> arguments, TimeSpan? duration, IProgress<double>? progress,
+ double from, double to, CancellationToken cancellationToken)
+ {
+ var total = duration?.TotalSeconds ?? 0;
+ Action<double>? onPosition = progress is null || total <= 0
+ ? null
+ : seconds => progress.Report(from + (to - from) * Math.Clamp(seconds / total, 0, 1));
+ var result = await FfmpegRunner.RunAsync(ffmpeg, arguments, onPosition, cancellationToken);
+ if (result.ExitCode != 0)
+ {
+ var reason = FfmpegRunner.Summarize(result.StandardError);
+ throw new InvalidOperationException($"FFmpeg failed (exit code {result.ExitCode}){(reason.Length > 0 ? ": " + reason : ".")}");
+ }
+ }
+
/// <summary>
/// The video of a Live / Motion Photo as <see cref="ConversionStep.To"/>: copied out of the photo (or from next to
/// it) into the work directory, converted there like any video and moved into place once finished, so a failure
diff --git a/src/Filee.Engines/Media/MediaEncoding.cs b/src/Filee.Engines/Media/MediaEncoding.cs
index be71f1a5..361f139a 100644
--- a/src/Filee.Engines/Media/MediaEncoding.cs
+++ b/src/Filee.Engines/Media/MediaEncoding.cs
@@ -278,7 +278,7 @@ internal static class MediaEncoding
/// with AAC in MOV) become MP4 this way. Only codecs the target's usual players handle are listed: MP4/MOV keep to
/// what Apple devices and browsers play, WebM to what the WebM specification allows.
/// </summary>
- private static readonly Dictionary<string, (HashSet<string> Video, HashSet<string> Audio)> Remuxable = new()
+ internal static readonly Dictionary<string, (HashSet<string> Video, HashSet<string> Audio)> Remuxable = new()
{
["mp4"] = (["h264", "hevc"], ["aac", "alac", "ac3", "eac3", "mp3"]),
["m4v"] = (["h264", "hevc"], ["aac", "alac", "ac3", "eac3", "mp3"]),
@@ -373,7 +373,7 @@ internal static class MediaEncoding
/// <summary>PAL (25 fps) for 25/50 fps sources, NTSC (29.97 fps) for everything else.</summary>
internal static bool IsPal(double fps) => Math.Abs(fps - 25) < 0.5 || Math.Abs(fps - 50) < 1 || Math.Abs(fps - 12.5) < 0.3;
- private static IEnumerable<string> VideoCodecArguments(string target, string codec, MediaQuality quality, VideoStreamInfo video, bool pal)
+ internal static IEnumerable<string> VideoCodecArguments(string target, string codec, MediaQuality quality, VideoStreamInfo video, bool pal)
{
// Constant quantizer for the MPEG-style codecs: 2 is the best useful value, 4 good, 7 visibly compressed.
var quantizer = Text(Choose(quality, 2, 4, 7));
@@ -485,7 +485,7 @@ internal static class MediaEncoding
return den == 1 ? num.ToString(CultureInfo.InvariantCulture) : $"{num}/{den}";
}
- private static IEnumerable<string> ContainerArguments(string target) => target switch
+ internal static IEnumerable<string> ContainerArguments(string target) => target switch
{
// Moves the index to the front so playback (and web streaming) can start before the file is loaded.
"mp4" or "m4v" or "mov" or "3gp" or "3g2" or "m4a" or "m4b" => ["-movflags", "+faststart"],
@@ -500,7 +500,7 @@ internal static class MediaEncoding
_ => [],
};
- private static IEnumerable<string> MetadataArguments(int from = 0)
+ internal static IEnumerable<string> MetadataArguments(int from = 0)
{
// Keep title, artist, dates, … (chapters are kept by default); an empty value removes a tag.
yield return "-map_metadata";
@@ -527,15 +527,72 @@ internal static class MediaEncoding
args.AddRange(["-map", $"0:{cover}", "-c:v", "copy", "-disposition:v:0", "attached_pic"]);
if (extras is { AttachmentFile: { } picture, AttachmentMime: { } mime })
args.AddRange(["-attach", picture, "-metadata:s:t", "mimetype=" + mime, "-metadata:s:t", "filename=" + Path.GetFileName(picture)]);
- var codec = AudioEncoder(target, spec.AudioCodec, options);
- args.AddRange(AudioCodecArguments(target, codec, options, audio, inVideo: false));
- args.AddRange(ChannelAndRateArguments(target, codec, options, audio.SampleRate));
+ if (CanCopyIntoAudio(target, audio, options))
+ {
+ // "Extract audio": the phone video's AAC goes into the M4A as it is, without a second encode.
+ args.AddRange(["-c:a", "copy"]);
+ }
+ else
+ {
+ var codec = AudioEncoder(target, spec.AudioCodec, options);
+ args.AddRange(AudioCodecArguments(target, codec, options, audio, inVideo: false));
+ args.AddRange(ChannelAndRateArguments(target, codec, options, audio.SampleRate));
+ }
args.AddRange(MetadataArguments(extras?.MetadataFile is null ? 0 : 1));
args.AddRange(ContainerArguments(target));
args.AddRange(["-f", spec.Muxer, "-progress", "pipe:1", output]);
return args;
}
+ /// <summary>Audio codecs an audio target takes as they are (<see cref="MediaOptions.CopyAudioWhenPossible"/>).</summary>
+ private static readonly Dictionary<string, HashSet<string>> CopyableAudio = new()
+ {
+ ["m4a"] = ["aac", "alac"],
+ ["m4b"] = ["aac", "alac"],
+ ["aac"] = ["aac"],
+ ["mp3"] = ["mp3"],
+ ["flac"] = ["flac"],
+ ["opus"] = ["opus"],
+ ["ogg"] = ["vorbis"],
+ };
+
+ /// <summary>
+ /// True when the preset copies sound it can (<see cref="MediaOptions.CopyAudioWhenPossible"/>) and this sound can be
+ /// copied into <paramref name="target"/>: the target takes its codec (only ALAC when the preset asks for Apple
+ /// Lossless), and no bitrate, channel count or Small quality asks for an encode.
+ /// </summary>
+ internal static bool CanCopyIntoAudio(string target, AudioStreamInfo audio, MediaOptions options)
+ {
+ if (!options.CopyAudioWhenPossible || options.Quality == MediaQuality.Small || options.AudioBitrateKbps > 0
+ || options.AudioChannels is 1 or 2 && options.AudioChannels != audio.Channels
+ || audio.Codec is not { } codec || !CopyableAudio.TryGetValue(target, out var codecs) || !codecs.Contains(codec))
+ return false;
+ return MediaCodecs.Effective(target, options.AudioCodec) != Core.Presets.AudioCodec.Alac || codec == "alac";
+ }
+
+ // ───────────────────────── Without metadata ─────────────────────────
+
+ /// <summary>
+ /// "Remove metadata": the file's video, audio and subtitle streams copied as they are into the same format, with no
+ /// tags (title, artist, dates, location, camera, encoder), per-stream tags or chapters. Data tracks (an iPhone's
+ /// timed location and camera metadata) are left out; album art stays.
+ /// </summary>
+ public static List<string> WithoutMetadata(string input, string output, string target, MediaInfo info)
+ {
+ var spec = VideoTargets.TryGetValue(target, out var video) ? video
+ : AudioTargets.TryGetValue(target, out var audio) ? audio
+ : throw new NotSupportedException($"FFmpeg cannot write '{target}'.");
+ List<string> args = [.. Common, "-i", input];
+ // A video's pictures without cover art (0:V); an audio file's cover art (0:v) stays with it.
+ args.AddRange(["-map", info.Video is not null ? "0:V?" : "0:v?", "-map", "0:a?", "-map", "0:s?", "-c", "copy"]);
+ if (info.Video?.Codec == "hevc" && target is "mp4" or "m4v" or "mov")
+ args.AddRange(["-tag:v", "hvc1"]);
+ args.AddRange(["-map_metadata", "-1", "-map_metadata:s", "-1", "-map_chapters", "-1", "-fflags", "+bitexact"]);
+ args.AddRange(ContainerArguments(target));
+ args.AddRange(["-max_muxing_queue_size", "4096", "-f", spec.Muxer, "-progress", "pipe:1", output]);
+ return args;
+ }
+
/// <summary>
/// The audio encoder of a target: the PCM format the preset picks for WAV and W64, ALAC for M4A / M4B when the
/// preset asks for Apple Lossless, else the target's usual one.
@@ -767,7 +824,7 @@ internal static class MediaEncoding
}
/// <summary>Images have no pixel aspect ratio: anamorphic video (DV, DVD) is stretched to square pixels first.</summary>
- private static string SquarePixels(VideoStreamInfo video) =>
+ internal static string SquarePixels(VideoStreamInfo video) =>
Math.Abs(video.SampleAspect - 1) > 0.01 ? "scale=w='trunc(iw*sar/2)*2':h=ih,setsar=1," : "";
// ───────────────────────── Still frame ─────────────────────────
@@ -840,7 +897,7 @@ internal static class MediaEncoding
// ───────────────────────── Helpers ─────────────────────────
- private static T Choose<T>(MediaQuality quality, T high, T balanced, T small) => quality switch
+ internal static T Choose<T>(MediaQuality quality, T high, T balanced, T small) => quality switch
{
MediaQuality.High => high,
MediaQuality.Small => small,
@@ -849,7 +906,7 @@ internal static class MediaEncoding
private static string Text(int value) => value.ToString(CultureInfo.InvariantCulture);
- private static int Even(double value) => Math.Max(2, (int)Math.Round(value / 2) * 2);
+ internal static int Even(double value) => Math.Max(2, (int)Math.Round(value / 2) * 2);
/// <summary>The even number at or below <paramref name="value"/> (a tiny rounding margin keeps 1080.0000001 at 1080).</summary>
private static int EvenDown(double value) => Math.Max(2, (int)Math.Floor(value / 2 + 1e-6) * 2);
diff --git a/src/Filee.Engines/Media/MediaJoining.cs b/src/Filee.Engines/Media/MediaJoining.cs
new file mode 100644
index 00000000..bca79430
--- /dev/null
+++ b/src/Filee.Engines/Media/MediaJoining.cs
@@ -0,0 +1,286 @@
+// Several files into one with FFmpeg: video clips or audio files back to back ("Merge videos", "Merge audio") and
+// pictures shown one after the other, with crossfades if the preset asks ("Video from images"). Pure apart from the
+// filter graph file of a long graph, like MediaEncoding: the command lines are unit tested without FFmpeg.
+// FfmpegConverter runs them.
+
+using System.Globalization;
+using Filee.Core.Presets;
+
+namespace Filee.Engines.Media;
+
+/// <summary>Command lines that join files.</summary>
+internal static class MediaJoining
+{
+ /// <summary>Most pictures one slideshow takes: every picture is an FFmpeg input, held while the video is encoded.</summary>
+ public const int MaxSlides = 300;
+
+ /// <summary>Frames per second of a slideshow: smooth fades, and what every player plays.</summary>
+ public const int SlideshowFps = 30;
+
+ /// <summary>The rate every clip's sound is brought to before the clips are joined (what video uses most).</summary>
+ private const int JoinSampleRate = 48000;
+
+ /// <summary>
+ /// A filter graph longer than this goes into a file (<c>-/filter_complex</c>): Windows limits a whole command line
+ /// to 32,767 characters, and every clip adds a chain to the graph.
+ /// </summary>
+ internal const int MaxInlineGraph = 8000;
+
+ // ───────────────────────── Videos ─────────────────────────
+
+ /// <summary>
+ /// True when the clips can be joined without an encode: every one is a video MP4 takes as it is, all with the same
+ /// codec, picture size, pixel format, turn and pixel shape, and the same kind of sound (or none at all). Videos from
+ /// one phone usually are.
+ /// </summary>
+ public static bool CanCopyVideos(IReadOnlyList<MediaInfo> clips, MediaOptions options)
+ {
+ if (clips.Count == 0 || clips[0].Video is not { } first)
+ return false;
+ var sameVideo = clips.All(c => c.Video is { } v && MediaEncoding.CanCopyVideo("mp4", v, options)
+ && v.Codec == first.Codec && v.Width == first.Width && v.Height == first.Height && v.PixelFormat == first.PixelFormat
+ && v.Rotation == first.Rotation && Math.Abs(v.SampleAspect - first.SampleAspect) < 0.01);
+ if (!sameVideo)
+ return false;
+ if (clips[0].Audio is not { } sound)
+ return clips.All(c => c.Audio is null);
+ return clips.All(c => c.Audio is { } a && MediaEncoding.CanCopyAudio("mp4", a, options)
+ && a.Codec == sound.Codec && a.SampleRate == sound.SampleRate && a.Channels == sound.Channels);
+ }
+
+ /// <summary>The list of the concat demuxer: one <c>file '…'</c> line per clip, quotes escaped.</summary>
+ public static string ConcatList(IEnumerable<string> paths) =>
+ string.Concat(paths.Select(path => "file '" + Path.GetFullPath(path).Replace("'", @"'\''", StringComparison.Ordinal) + "'\n"));
+
+ /// <summary>Clips that share codecs and size, copied one after the other into one MP4 (<see cref="CanCopyVideos"/>).</summary>
+ public static List<string> CopyVideos(string listFile, string output, MediaInfo first)
+ {
+ List<string> args = [.. MediaEncoding.Common, "-f", "concat", "-safe", "0", "-i", listFile, "-map", "0:V:0"];
+ if (first.Audio is not null)
+ args.AddRange(["-map", "0:a:0"]);
+ args.AddRange(["-c", "copy"]);
+ if (first.Video?.Codec == "hevc")
+ args.AddRange(["-tag:v", "hvc1"]);
+ args.AddRange(MediaEncoding.MetadataArguments());
+ args.AddRange(MediaEncoding.ContainerArguments("mp4"));
+ args.AddRange(["-max_muxing_queue_size", "4096", "-f", "mp4", "-progress", "pipe:1", output]);
+ return args;
+ }
+
+ /// <summary>
+ /// The frame every clip is fitted into: the first clip's picture as it is shown (turned, square pixels), even, and
+ /// no taller than <see cref="MediaOptions.MaxHeight"/>.
+ /// </summary>
+ internal static (int Width, int Height) JoinFrame(VideoStreamInfo first, int maxHeight)
+ {
+ var height = (double)Math.Max(2, first.DisplayHeight);
+ if (maxHeight > 0)
+ height = Math.Min(height, Math.Max(16, maxHeight));
+ return (MediaEncoding.Even(height * first.DisplayAspect), MediaEncoding.Even(height));
+ }
+
+ /// <summary>
+ /// Clips of any codec and size encoded into one MP4 (H.264, or the preset's codec, and AAC): each is fitted into the
+ /// first clip's frame with black bars, at its frame rate. A clip without sound is silent for its length when
+ /// others have sound.
+ /// </summary>
+ /// <param name="encoder">The video encoder (<see cref="MediaEncoding.VideoEncoder"/>).</param>
+ /// <param name="workDirectory">Where a long filter graph is written (<see cref="MaxInlineGraph"/>).</param>
+ /// <exception cref="InvalidOperationException">A clip has no video, or FFmpeg can't tell how long a silent one is.</exception>
+ public static List<string> EncodeVideos(IReadOnlyList<(string Path, MediaInfo Info)> clips, string output, MediaOptions options,
+ string encoder, string workDirectory)
+ {
+ var first = clips[0].Info.Video ?? throw new InvalidOperationException($"{Path.GetFileName(clips[0].Path)} has no video stream.");
+ var (width, height) = JoinFrame(first, options.MaxHeight);
+ var fps = MediaEncoding.NearestRate(first.FrameRate) ?? "30";
+ var withSound = clips.Any(c => c.Info.Audio is not null);
+
+ var graph = new List<string>();
+ var segments = "";
+ for (var i = 0; i < clips.Count; i++)
+ {
+ var (path, info) = clips[i];
+ var video = info.Video ?? throw new InvalidOperationException($"{Path.GetFileName(path)} has no video stream.");
+ graph.Add($"[{i}:V:0]{MediaEncoding.SquarePixels(video)}{Fit(width, height)},fps={fps},format=yuv420p[v{i}]");
+ segments += $"[v{i}]";
+ if (!withSound)
+ continue;
+ graph.Add(info.Audio is not null ? $"[{i}:a:0]{Resample("stereo")}[a{i}]" : $"{Silence(path, info, "stereo")}[a{i}]");
+ segments += $"[a{i}]";
+ }
+ graph.Add($"{segments}concat=n={clips.Count}:v=1:a={(withSound ? 1 : 0)}[v]{(withSound ? "[a]" : "")}");
+
+ List<string> args = [.. MediaEncoding.Common];
+ foreach (var (path, _) in clips)
+ args.AddRange(["-i", path]);
+ args.AddRange(GraphArguments(string.Join(';', graph), workDirectory));
+ args.AddRange(["-map", "[v]"]);
+ args.AddRange(MediaEncoding.VideoCodecArguments("mp4", encoder, options.Quality, first, pal: false));
+ if (withSound)
+ args.AddRange(["-map", "[a]", "-c:a", "aac", "-b:a", Text(AacKbps(options, 2)) + "k"]);
+ else
+ args.Add("-an");
+ args.AddRange(MediaEncoding.MetadataArguments());
+ args.AddRange(MediaEncoding.ContainerArguments("mp4"));
+ args.AddRange(["-max_muxing_queue_size", "4096", "-f", "mp4", "-progress", "pipe:1", output]);
+ return args;
+ }
+
+ // ───────────────────────── Audio ─────────────────────────
+
+ /// <summary>
+ /// Audio files (or the sound of videos) decoded and joined into one M4A, sample after sample: no gap and no
+ /// encoder padding between them, which copying the clips' AAC would leave. Mono when every clip is mono, else
+ /// stereo; AAC at the preset's quality or bitrate, or Apple Lossless when the preset asks for it.
+ /// </summary>
+ /// <exception cref="InvalidOperationException">A file has no sound and FFmpeg can't tell how long it is.</exception>
+ public static List<string> EncodeAudio(IReadOnlyList<(string Path, MediaInfo Info)> clips, string output, MediaOptions options,
+ string workDirectory)
+ {
+ var mono = clips.All(c => c.Info.Audio is { Channels: 1 });
+ var layout = mono ? "mono" : "stereo";
+ var graph = new List<string>();
+ var segments = "";
+ for (var i = 0; i < clips.Count; i++)
+ {
+ var (path, info) = clips[i];
+ graph.Add(info.Audio is not null ? $"[{i}:a:0]{Resample(layout)}[a{i}]" : $"{Silence(path, info, layout)}[a{i}]");
+ segments += $"[a{i}]";
+ }
+ graph.Add($"{segments}concat=n={clips.Count}:v=0:a=1[a]");
+
+ List<string> args = [.. MediaEncoding.Common];
+ foreach (var (path, _) in clips)
+ args.AddRange(["-i", path]);
+ args.AddRange(GraphArguments(string.Join(';', graph), workDirectory));
+ args.AddRange(["-map", "[a]", "-vn"]);
+ if (MediaCodecs.Effective("m4a", options.AudioCodec) == AudioCodec.Alac)
+ args.AddRange(["-c:a", "alac"]);
+ else
+ args.AddRange(["-c:a", "aac", "-b:a", Text(AacKbps(options, mono ? 1 : 2)) + "k"]);
+ args.AddRange(MediaEncoding.MetadataArguments());
+ args.AddRange(MediaEncoding.ContainerArguments("m4a"));
+ args.AddRange(["-f", "ipod", "-progress", "pipe:1", output]);
+ return args;
+ }
+
+ /// <summary>The preset's AAC bitrate, else 256 / 192 / 128 kbit/s per stereo pair by quality (half for mono).</summary>
+ private static int AacKbps(MediaOptions options, int channels) =>
+ options.AudioBitrateKbps > 0
+ ? Math.Clamp(options.AudioBitrateKbps, 16, 512)
+ : MediaEncoding.Choose(options.Quality, 256, 192, 128) * channels / 2;
+
+ private static string Resample(string layout) =>
+ $"aresample={JoinSampleRate},aformat=sample_fmts=fltp:sample_rates={JoinSampleRate}:channel_layouts={layout}";
+
+ /// <summary>Silence as long as a clip without sound, so the sound of the clips after it stays in step.</summary>
+ private static string Silence(string path, MediaInfo info, string layout)
+ {
+ var seconds = info.Duration?.TotalSeconds ?? 0;
+ if (seconds <= 0)
+ throw new InvalidOperationException($"{Path.GetFileName(path)} has no sound, and FFmpeg can't tell how long it is.");
+ return $"aevalsrc=0:c={layout}:s={JoinSampleRate}:d={Seconds(seconds)},{Resample(layout)}";
+ }
+
+ // ───────────────────────── Pictures ─────────────────────────
+
+ /// <summary>The slideshow frame of a preset: even, between 16 and 8K, 1080p by default.</summary>
+ public static (int Width, int Height) SlideshowFrame(MediaOptions options) =>
+ (MediaEncoding.Even(Math.Clamp(options.SlideshowWidth, 16, 7680)), MediaEncoding.Even(Math.Clamp(options.SlideshowHeight, 16, 4320)));
+
+ /// <summary>How long a slideshow of <paramref name="count"/> pictures plays: the fades overlap the pictures.</summary>
+ public static TimeSpan SlideshowDuration(int count, MediaOptions options) => count <= 0
+ ? TimeSpan.Zero
+ : TimeSpan.FromSeconds(count * options.SlideDuration - (count - 1) * options.FadeDuration);
+
+ /// <summary>
+ /// One picture fitted into the slideshow frame (black bars, transparency on black) as a JPEG at FFmpeg's best
+ /// quality: the slideshow then holds a small 1080p picture per slide instead of a full-size photo.
+ /// </summary>
+ public static List<string> PrepareSlide(string picture, string output, int width, int height) =>
+ [
+ .. MediaEncoding.Common, "-i", picture, "-map", "0:V:0",
+ "-vf", $"premultiply=inplace=1,{Fit(width, height, ":flags=lanczos")}",
+ "-frames:v", "1", "-update", "1", "-c:v", "mjpeg", "-q:v", "2", "-f", "image2", output,
+ ];
+
+ /// <summary>
+ /// The prepared slides (<see cref="PrepareSlide"/>) as one MP4: each shown for <see cref="MediaOptions.SlideDuration"/>,
+ /// fading into the next over <see cref="MediaOptions.FadeDuration"/> (a cut without crossfades). BT.709 in TV range,
+ /// 30 frames per second, no sound.
+ /// </summary>
+ /// <param name="encoder">The video encoder (<see cref="MediaEncoding.VideoEncoder"/>).</param>
+ /// <param name="workDirectory">Where a long filter graph is written (<see cref="MaxInlineGraph"/>).</param>
+ public static List<string> Slideshow(IReadOnlyList<string> slides, string output, MediaOptions options, string encoder, string workDirectory)
+ {
+ var (width, height) = SlideshowFrame(options);
+ var show = Seconds(options.SlideDuration);
+ var fade = options.FadeDuration;
+ var graph = new List<string>();
+ for (var i = 0; i < slides.Count; i++)
+ {
+ // One decoded frame per picture, repeated for its time: no picture is read more than once.
+ graph.Add($"[{i}:v]scale=out_color_matrix=bt709:out_range=tv,format=yuv420p,setsar=1,fps={SlideshowFps}," +
+ $"tpad=stop_mode=clone:stop_duration={show},trim=duration={show},setpts=PTS-STARTPTS[s{i}]");
+ }
+ if (slides.Count == 1)
+ {
+ graph.Add("[s0]null[out]");
+ }
+ else if (fade > 0)
+ {
+ // Each fade starts where the previous output ends minus the fade: k × (show − fade).
+ var previous = "s0";
+ for (var k = 1; k < slides.Count; k++)
+ {
+ var label = k == slides.Count - 1 ? "out" : $"x{k}";
+ graph.Add($"[{previous}][s{k}]xfade=transition=fade:duration={Seconds(fade)}:offset={Seconds(k * (options.SlideDuration - fade))}[{label}]");
+ previous = label;
+ }
+ }
+ else
+ {
+ graph.Add($"{string.Concat(Enumerable.Range(0, slides.Count).Select(i => $"[s{i}]"))}concat=n={slides.Count}:v=1:a=0[out]");
+ }
+
+ List<string> args = [.. MediaEncoding.Common];
+ foreach (var slide in slides)
+ args.AddRange(["-i", slide]);
+ args.AddRange(GraphArguments(string.Join(';', graph), workDirectory));
+ args.AddRange(["-map", "[out]"]);
+ // Pictures cost an encoder little: one step above the preset's quality, as a single picture's video does.
+ var quality = options.Quality == MediaQuality.Small ? MediaQuality.Balanced : MediaQuality.High;
+ var frame = new VideoStreamInfo(width, height, 1, 0, SlideshowFps, PixelFormat: "yuv420p");
+ args.AddRange(MediaEncoding.VideoCodecArguments("mp4", encoder, quality, frame, pal: false));
+ args.AddRange(["-r", Text(SlideshowFps), "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-an"]);
+ args.AddRange(MediaEncoding.ContainerArguments("mp4"));
+ args.AddRange(["-f", "mp4", "-progress", "pipe:1", output]);
+ return args;
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ /// <summary>Fits a picture into <paramref name="width"/> × <paramref name="height"/>, centred, with black bars.</summary>
+ /// <param name="scaleOptions">More options of the scale filter, e.g. <c>":flags=lanczos"</c>.</param>
+ private static string Fit(int width, int height, string scaleOptions = "") =>
+ $"scale={width}:{height}:force_original_aspect_ratio=decrease:force_divisible_by=2{scaleOptions}," +
+ $"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:black,setsar=1";
+
+ /// <summary>
+ /// <c>-filter_complex</c> with the graph, or <c>-/filter_complex</c> with a file holding it when it is long
+ /// (<see cref="MaxInlineGraph"/>).
+ /// </summary>
+ internal static string[] GraphArguments(string graph, string workDirectory)
+ {
+ if (graph.Length <= MaxInlineGraph)
+ return ["-filter_complex", graph];
+ Directory.CreateDirectory(workDirectory);
+ var file = Path.Combine(workDirectory, $"graph-{Guid.NewGuid():N}.txt");
+ File.WriteAllText(file, graph);
+ return ["-/filter_complex", file];
+ }
+
+ private static string Seconds(double seconds) => seconds.ToString("0.###", CultureInfo.InvariantCulture);
+
+ private static string Text(int value) => value.ToString(CultureInfo.InvariantCulture);
+}
diff --git a/src/Filee.Engines/Pdf/PdfSharpConverter.cs b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
index 4f64ac75..97b09639 100644
--- a/src/Filee.Engines/Pdf/PdfSharpConverter.cs
+++ b/src/Filee.Engines/Pdf/PdfSharpConverter.cs
@@ -1,5 +1,5 @@
-// Builds PDFs from images, splits / extracts PDF pages, merges PDFs and makes PDFs smaller (PDFsharp, MIT; the
-// compression itself is in PdfCompressor, with Ghostscript as an optional second try).
+// Builds PDFs from images, splits / extracts PDF pages, merges PDFs, makes PDFs smaller (PDFsharp, MIT; the
+// compression itself is in PdfCompressor, with Ghostscript as an optional second try) and removes their metadata.
using Filee.Core.Conversion;
using Filee.Core.Presets;
@@ -36,6 +36,8 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>
step.From != "pdf" ? Task.Run(() => ImageToPdf(step, progress, cancellationToken), cancellationToken)
+ : step.Preset.Pdf is { Compression: PdfCompression.None, RemoveMetadata: true, SplitPages: false, PageRange: "" }
+ ? Task.Run(() => WithoutMetadata(step, progress, cancellationToken), cancellationToken)
: step.Preset.Pdf.Compression == PdfCompression.None ? Task.Run(() => SplitOrExtract(step, progress, cancellationToken), cancellationToken)
: Task.Run(() => CompressAsync(step, progress, cancellationToken), cancellationToken);
@@ -105,6 +107,42 @@ public sealed class PdfSharpConverter : IConverter, IPdfMerger, IImageTransforme
return [path];
}
+ /// <summary>
+ /// "Remove metadata": the whole PDF, opened for changes so links, bookmarks and form fields stay, without its
+ /// document information (title, author, subject, keywords, creator, dates) and XMP packets.
+ /// </summary>
+ private static IReadOnlyList<string> WithoutMetadata(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
+ {
+ using var document = OpenForChanges(step.InputPath);
+ ct.ThrowIfCancellationRequested();
+ StripMetadata(document);
+ progress?.Report(0.5);
+ var output = step.Output.Allocate("pdf");
+ if (output is null)
+ return [];
+ document.Save(output);
+ return [output];
+ }
+
+ /// <summary>
+ /// Drops the document information and every XMP packet (document, pages, pictures, forms) and the private data of
+ /// the apps that made the file. PDFsharp writes a new XMP packet with only its own name and the save date.
+ /// </summary>
+ internal static void StripMetadata(PdfDocument document)
+ {
+ foreach (var key in document.Info.Elements.Keys.ToList())
+ document.Info.Elements.Remove(key);
+ document.Internals.Catalog.Elements.Remove("/Metadata");
+ document.Internals.Catalog.Elements.Remove("/PieceInfo");
+ foreach (var page in document.Pages)
+ page.Elements.Remove("/PieceInfo");
+ foreach (var item in document.Internals.GetAllObjects())
+ {
+ if (item is PdfDictionary dictionary && dictionary.Elements.ContainsKey("/Metadata"))
+ dictionary.Elements.Remove("/Metadata");
+ }
+ }
+
/// <summary>PDF → PDF: split into single pages, or extract the configured page range.</summary>
private static IReadOnlyList<string> SplitOrExtract(ConversionStep step, IProgress<double>? progress, CancellationToken ct)
{
diff --git a/tests/Filee.App.Tests/DonutFlipTests.cs b/tests/Filee.App.Tests/DonutFlipTests.cs
index d98555a2..01d11cec 100644
--- a/tests/Filee.App.Tests/DonutFlipTests.cs
+++ b/tests/Filee.App.Tests/DonutFlipTests.cs
@@ -681,9 +681,10 @@ public class DonutFlipTests
RenderTests.Save(window, $"toolbar-back-face-{language}{(dark ? "-dark" : "")}.png");
var back = ImageBack;
+ // The built-in back face is full (settings schema 33): a slice goes before another comes in.
+ page.RemoveAt(page.SliceCount - 1);
Assert.True(page.Insert("to-psd", 0));
page.Move(0, 2);
- page.RemoveAt(page.SliceCount - 1);
List<string> edited = [.. back[..2], "to-psd", .. back[2..^1]];
Assert.Equal(edited, Images.BackPresetIds);
Assert.Equal(front, Images.PresetIds); // the front as it was
diff --git a/tests/Filee.Core.Tests/FakeConverter.cs b/tests/Filee.Core.Tests/FakeConverter.cs
index c0706262..d500fddf 100644
--- a/tests/Filee.Core.Tests/FakeConverter.cs
+++ b/tests/Filee.Core.Tests/FakeConverter.cs
@@ -158,6 +158,26 @@ internal sealed class FakeCombiner : IFileCombiner
}
}
+/// <summary>Test double for the FFmpeg engine's joining: records what it was given and writes their names.</summary>
+internal sealed class FakeJoiner : IMediaJoiner
+{
+ public List<string> Inputs { get; } = [];
+
+ public bool Throw { get; set; }
+
+ public bool CanJoinInto(string format) => true;
+
+ public Task JoinAsync(IReadOnlyList<string> inputPaths, string outputPath, string format, Filee.Core.Presets.Preset preset,
+ string workDirectory, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ if (Throw)
+ throw new InvalidOperationException("boom");
+ Inputs.AddRange(inputPaths);
+ File.WriteAllText(outputPath, string.Join("|", inputPaths.Select(Path.GetFileName)));
+ return Task.CompletedTask;
+ }
+}
+
/// <summary>Creates and removes a unique temp directory.</summary>
internal sealed class TempDir : IDisposable
{
diff --git a/tests/Filee.Core.Tests/MediaToolTests.cs b/tests/Filee.Core.Tests/MediaToolTests.cs
new file mode 100644
index 00000000..6fb8d43f
--- /dev/null
+++ b/tests/Filee.Core.Tests/MediaToolTests.cs
@@ -0,0 +1,183 @@
+// The everyday media tools of settings schema 33: their presets, how existing libraries get them, and the queue
+// joining videos, audio files and pictures into one file.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Core.Profiles;
+using Filee.Core.Settings;
+
+namespace Filee.Core.Tests;
+
+public class MediaToolTests
+{
+ private static readonly string[] ToolIds =
+ ["compress-image", "compress-video", "video-from-images", "extract-audio", "merge-videos", "compress-audio", "merge-audio", "remove-metadata"];
+
+ private static Preset BuiltIn(string id) => BuiltInData.CreatePresets().Single(p => p.Id == id);
+
+ private static async Task<ConversionJob> Run(JobQueue queue, IReadOnlyList<string> sources, Preset preset)
+ {
+ var job = new ConversionJob(sources, preset, "Test");
+ await queue.RunAsync(job);
+ return job;
+ }
+
+ [Fact]
+ public void A_new_library_has_every_tool_with_a_name_to_show()
+ {
+ var presets = BuiltInData.CreatePresets();
+ foreach (var id in ToolIds)
+ Assert.StartsWith("preset.", Assert.Single(presets, p => p.Id == id).NameKey);
+ }
+
+ [Fact]
+ public void Only_the_merge_and_slideshow_tools_join_files()
+ {
+ Assert.Equal(["video-from-images", "merge-videos", "merge-audio"],
+ BuiltInData.CreatePresets().Where(p => p.JoinsIntoOneMedia).Select(p => p.Id));
+ // A join option on a target that can't hold it converts file by file, as before.
+ Assert.False(new Preset { TargetFormat = "webm", Media = { JoinIntoOne = true } }.JoinsIntoOneMedia);
+ }
+
+ [Fact]
+ public void Remove_metadata_takes_everything_and_keeps_the_format()
+ {
+ var clean = BuiltIn("remove-metadata");
+ Assert.Equal(BuiltInData.SameAsSource, clean.TargetFormat);
+ Assert.False(clean.Image.KeepMetadata);
+ Assert.False(clean.Image.KeepColorProfile);
+ Assert.True(clean.Image.KeepSourceQuality);
+ Assert.True(clean.Pdf.RemoveMetadata);
+ Assert.True(clean.Media.RemoveMetadata);
+ Assert.False(clean.Output.KeepDates);
+ }
+
+ [Fact]
+ public void Slides_and_fades_stay_within_their_limits()
+ {
+ var media = new MediaOptions { SlideSeconds = 2, CrossfadeSeconds = 5 };
+ Assert.Equal(1, media.FadeDuration); // at most half of the time a picture is shown
+ media.Crossfade = false;
+ Assert.Equal(0, media.FadeDuration);
+ Assert.Equal(MediaOptions.MaxSlideSeconds, new MediaOptions { SlideSeconds = 1e9 }.SlideDuration);
+ Assert.Equal(3, new MediaOptions { SlideSeconds = double.NaN }.SlideDuration);
+ }
+
+ [Fact]
+ public void Options_survive_a_copy()
+ {
+ var copy = BuiltIn("video-from-images").Clone();
+ Assert.True(copy.Media.Slideshow);
+ Assert.True(copy.Media.Crossfade);
+ Assert.True(BuiltIn("compress-image").Clone().Image.MaxCompression);
+ }
+
+ [Fact]
+ public void Version_32_libraries_get_the_tools_and_back_faces_with_room_offer_them()
+ {
+ var presets = BuiltInData.CreatePresets().Where(p => !ToolIds.Contains(p.Id)).ToList();
+ var profiles = BuiltInData.CreateProfiles();
+ foreach (var profile in profiles)
+ profile.BackPresetIds!.RemoveAll(ToolIds.Contains);
+ // A back face the user filled up stays as it is.
+ var pdf = profiles.Single(p => p.Id == "pdf");
+ while (pdf.BackPresetIds!.Count < ToolbarProfile.MaxSlices)
+ pdf.BackPresetIds.Insert(0, presets.First(p => !pdf.BackPresetIds.Contains(p.Id) && !pdf.PresetIds.Contains(p.Id)).Id);
+ var full = pdf.BackPresetIds.ToList();
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(32, presets, profiles));
+
+ Assert.All(ToolIds, id => Assert.Single(presets, p => p.Id == id));
+ var audio = profiles.Single(p => p.Id == "audio").BackPresetIds!;
+ Assert.Equal(["to-alac", "compress-audio", "merge-audio", "remove-metadata", "zip-all"], audio);
+ var video = profiles.Single(p => p.Id == "video").BackPresetIds!;
+ Assert.Equal(["compress-video", "merge-videos", "zip-all"], video.TakeLast(3));
+ Assert.Equal(full, pdf.BackPresetIds);
+ Assert.False(SettingsMigrations.ApplyToLibrary(32, presets, profiles)); // once only
+ Assert.False(SettingsMigrations.ApplyToLibrary(AppSettings.CurrentSchemaVersion, presets, profiles));
+ }
+
+ [Fact]
+ public async Task Merge_videos_joins_the_clips_in_order_into_one_file_named_after_the_first()
+ {
+ using var dir = new TempDir();
+ var second = dir.File("b.mp4");
+ var first = dir.File("a.mov");
+ var joiner = new FakeJoiner();
+ await using var queue = new JobQueue(new ConverterCatalog([]), mediaJoiner: joiner);
+
+ var job = await Run(queue, [first, second], BuiltIn("merge-videos"));
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal([first, second], joiner.Inputs);
+ Assert.Equal(Path.Combine(dir.Path, "a_merged.mp4"), job.Outputs.Single());
+ }
+
+ [Fact]
+ public async Task A_file_that_is_no_video_fails_and_the_other_clips_still_join()
+ {
+ using var dir = new TempDir();
+ var clip = dir.File("a.mp4");
+ var song = dir.File("b.mp3");
+ var joiner = new FakeJoiner();
+ await using var queue = new JobQueue(new ConverterCatalog([]), mediaJoiner: joiner);
+
+ var job = await Run(queue, [clip, song], BuiltIn("merge-videos"));
+
+ Assert.Equal(JobState.CompletedWithErrors, job.State);
+ Assert.Equal([clip], joiner.Inputs);
+ Assert.Equal("error.no_route", job.Files[1].ErrorKey);
+ }
+
+ [Fact]
+ public async Task Merge_audio_takes_audio_files_and_the_sound_of_videos()
+ {
+ using var dir = new TempDir();
+ var song = dir.File("a.mp3");
+ var clip = dir.File("b.mp4");
+ var joiner = new FakeJoiner();
+ await using var queue = new JobQueue(new ConverterCatalog([]), mediaJoiner: joiner);
+
+ var job = await Run(queue, [song, clip], BuiltIn("merge-audio"));
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal([song, clip], joiner.Inputs);
+ Assert.Equal(Path.Combine(dir.Path, "a_merged.m4a"), job.Outputs.Single());
+ }
+
+ [Fact]
+ public async Task Video_from_images_makes_pngs_first_and_takes_a_png_as_it_is()
+ {
+ using var dir = new TempDir();
+ var photo = dir.File("a.jpg");
+ var drawing = dir.File("b.png");
+ var joiner = new FakeJoiner();
+ await using var queue = new JobQueue(new ConverterCatalog([new FakeConverter("magick", new ConversionEdge("jpg", "png"))]),
+ mediaJoiner: joiner);
+
+ var job = await Run(queue, [photo, drawing], BuiltIn("video-from-images"));
+
+ Assert.Equal(JobState.Completed, job.State);
+ Assert.Equal(2, joiner.Inputs.Count);
+ Assert.EndsWith(".png", joiner.Inputs[0]);
+ Assert.NotEqual(photo, joiner.Inputs[0]); // converted in the work directory
+ Assert.Equal(drawing, joiner.Inputs[1]);
+ Assert.Equal(Path.Combine(dir.Path, "a_video.mp4"), job.Outputs.Single());
+ Assert.False(File.Exists(Path.Combine(dir.Path, "a.png"))); // no picture left beside the source
+ }
+
+ [Fact]
+ public async Task A_failed_join_fails_every_file_and_leaves_no_output()
+ {
+ using var dir = new TempDir();
+ var a = dir.File("a.mp4");
+ var b = dir.File("b.mp4");
+ await using var queue = new JobQueue(new ConverterCatalog([]), mediaJoiner: new FakeJoiner { Throw = true });
+
+ var job = await Run(queue, [a, b], BuiltIn("merge-videos"));
+
+ Assert.Equal(JobState.Failed, job.State);
+ Assert.All(job.Files, f => Assert.Equal("error.conversion_failed", f.ErrorKey));
+ Assert.Empty(job.Outputs);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/EngineFixture.cs b/tests/Filee.Engines.Tests/EngineFixture.cs
index 60518af0..75c3ed50 100644
--- a/tests/Filee.Engines.Tests/EngineFixture.cs
+++ b/tests/Filee.Engines.Tests/EngineFixture.cs
@@ -67,7 +67,8 @@ public sealed class EngineFixture : IDisposable
public async Task<ConversionJob> ConvertAsync(IReadOnlyList<string> sources, Preset preset)
{
await using var queue = new JobQueue(Catalog, EngineRegistry.FindPdfMerger(Converters),
- combiner: EngineRegistry.FindFileCombiner(Converters), tiffMerger: EngineRegistry.FindTiffMerger(Converters));
+ combiner: EngineRegistry.FindFileCombiner(Converters), tiffMerger: EngineRegistry.FindTiffMerger(Converters),
+ mediaJoiner: EngineRegistry.FindMediaJoiner(Converters));
var job = new ConversionJob(sources, preset, preset.Name);
await queue.RunAsync(job);
return job;
diff --git a/tests/Filee.Engines.Tests/MediaJoiningTests.cs b/tests/Filee.Engines.Tests/MediaJoiningTests.cs
new file mode 100644
index 00000000..03ba9efe
--- /dev/null
+++ b/tests/Filee.Engines.Tests/MediaJoiningTests.cs
@@ -0,0 +1,211 @@
+// Command lines of the everyday media tools (no FFmpeg needed): videos and audio files joined into one, pictures as a
+// slideshow, a video's sound copied into M4A, and a copy of a file without its tags.
+
+using Filee.Core.Presets;
+using Filee.Engines.Media;
+
+namespace Filee.Engines.Tests;
+
+public class MediaJoiningTests
+{
+ private static readonly VideoStreamInfo PhoneVideo = new(1920, 1080, 1, 0, 30, "h264", "yuv420p");
+
+ private static MediaInfo Clip(VideoStreamInfo? video = null, AudioStreamInfo? audio = null, double seconds = 10) =>
+ new(TimeSpan.FromSeconds(seconds), video, audio, null);
+
+ private static string After(IReadOnlyList<string> args, string option) => args[args.ToList().IndexOf(option) + 1];
+
+ [Fact]
+ public void Clips_from_one_phone_are_copied()
+ {
+ var clip = Clip(PhoneVideo, new AudioStreamInfo(2, 48000, "aac"));
+ Assert.True(MediaJoining.CanCopyVideos([clip, clip], new MediaOptions()));
+
+ var args = MediaJoining.CopyVideos("clips.txt", "out.mp4", clip);
+ Assert.Equal("concat", After(args, "-f"));
+ Assert.Equal("copy", After(args, "-c"));
+ Assert.Contains("0:a:0", args);
+ }
+
+ [Fact]
+ public void Clips_of_another_size_codec_or_sound_are_encoded()
+ {
+ var clip = Clip(PhoneVideo, new AudioStreamInfo(2, 48000, "aac"));
+ var options = new MediaOptions();
+ Assert.False(MediaJoining.CanCopyVideos([clip, clip with { Video = PhoneVideo with { Width = 1280, Height = 720 } }], options));
+ Assert.False(MediaJoining.CanCopyVideos([clip, clip with { Video = PhoneVideo with { Codec = "hevc" } }], options));
+ Assert.False(MediaJoining.CanCopyVideos([clip, clip with { Audio = new AudioStreamInfo(2, 44100, "aac") }], options));
+ Assert.False(MediaJoining.CanCopyVideos([clip, clip with { Audio = null }], options));
+ Assert.False(MediaJoining.CanCopyVideos([clip, clip], new MediaOptions { Quality = MediaQuality.Small }));
+ }
+
+ [Fact]
+ public void Encoded_clips_fit_the_first_ones_frame_and_a_silent_one_gets_silence()
+ {
+ var portrait = PhoneVideo with { Rotation = -90 };
+ var withSound = Clip(portrait, new AudioStreamInfo(2, 44100, "aac"));
+ var silent = Clip(PhoneVideo, seconds: 4.5);
+
+ var args = MediaJoining.EncodeVideos([("a.mov", withSound), ("b.mp4", silent)], "out.mp4", new MediaOptions(), "libx264", "work");
+
+ var graph = After(args, "-filter_complex");
+ Assert.Contains("[0:V:0]scale=1080:1920:force_original_aspect_ratio=decrease", graph); // the first clip stands upright
+ Assert.Contains("pad=1080:1920", graph);
+ Assert.Contains("aevalsrc=0:c=stereo:s=48000:d=4.5", graph);
+ Assert.Contains("concat=n=2:v=1:a=1[v][a]", graph);
+ Assert.Equal("libx264", After(args, "-c:v"));
+ Assert.Equal("aac", After(args, "-c:a"));
+ Assert.Equal("out.mp4", args[^1]);
+ }
+
+ [Fact]
+ public void Clips_without_any_sound_join_without_an_audio_track()
+ {
+ var args = MediaJoining.EncodeVideos([("a.mp4", Clip(PhoneVideo)), ("b.mp4", Clip(PhoneVideo))], "out.mp4", new MediaOptions(),
+ "libx264", "work");
+
+ Assert.Contains("concat=n=2:v=1:a=0[v]", After(args, "-filter_complex"));
+ Assert.Contains("-an", args);
+ }
+
+ [Fact]
+ public void A_frame_never_gets_taller_than_the_preset_allows()
+ {
+ var uhd = PhoneVideo with { Width = 3840, Height = 2160 };
+ Assert.Equal((1920, 1080), MediaJoining.JoinFrame(uhd, 1080));
+ Assert.Equal((3840, 2160), MediaJoining.JoinFrame(uhd, 0));
+ }
+
+ [Fact]
+ public void Audio_is_decoded_and_joined_without_gaps()
+ {
+ var song = Clip(audio: new AudioStreamInfo(2, 44100, "mp3"));
+ var memo = Clip(audio: new AudioStreamInfo(1, 16000, "aac"));
+
+ var args = MediaJoining.EncodeAudio([("a.mp3", song), ("b.m4a", memo)], "out.m4a", new MediaOptions(), "work");
+
+ var graph = After(args, "-filter_complex");
+ Assert.Contains("[0:a:0]aresample=48000", graph);
+ Assert.Contains("channel_layouts=stereo", graph);
+ Assert.Contains("concat=n=2:v=0:a=1[a]", graph);
+ Assert.Equal("aac", After(args, "-c:a"));
+ Assert.Equal("192k", After(args, "-b:a"));
+ Assert.Equal("ipod", After(args, "-f"));
+ }
+
+ [Fact]
+ public void Mono_recordings_stay_mono_and_apple_lossless_is_kept()
+ {
+ var memo = Clip(audio: new AudioStreamInfo(1, 16000, "aac"));
+ var mono = MediaJoining.EncodeAudio([("a.m4a", memo), ("b.m4a", memo)], "out.m4a", new MediaOptions(), "work");
+ Assert.Contains("channel_layouts=mono", After(mono, "-filter_complex"));
+ Assert.Equal("96k", After(mono, "-b:a"));
+
+ var alac = MediaJoining.EncodeAudio([("a.m4a", memo)], "out.m4a", new MediaOptions { AudioCodec = AudioCodec.Alac }, "work");
+ Assert.Equal("alac", After(alac, "-c:a"));
+ }
+
+ [Fact]
+ public void Slides_fade_into_each_other_at_the_right_times()
+ {
+ var options = new MediaOptions { Slideshow = true, SlideSeconds = 3, CrossfadeSeconds = 1 };
+
+ var args = MediaJoining.Slideshow(["1.jpg", "2.jpg", "3.jpg"], "out.mp4", options, "libx264", "work");
+
+ var graph = After(args, "-filter_complex");
+ Assert.Contains("tpad=stop_mode=clone:stop_duration=3,trim=duration=3", graph);
+ Assert.Contains("[s0][s1]xfade=transition=fade:duration=1:offset=2[x1]", graph);
+ Assert.Contains("[x1][s2]xfade=transition=fade:duration=1:offset=4[out]", graph);
+ Assert.Equal(TimeSpan.FromSeconds(7), MediaJoining.SlideshowDuration(3, options));
+ Assert.Contains("-an", args);
+ }
+
+ [Fact]
+ public void Without_crossfades_the_slides_are_cut()
+ {
+ var options = new MediaOptions { Slideshow = true, SlideSeconds = 2, Crossfade = false };
+
+ var graph = After(MediaJoining.Slideshow(["1.jpg", "2.jpg"], "out.mp4", options, "libx264", "work"), "-filter_complex");
+
+ Assert.Contains("[s0][s1]concat=n=2:v=1:a=0[out]", graph);
+ Assert.DoesNotContain("xfade", graph);
+ Assert.Equal(TimeSpan.FromSeconds(4), MediaJoining.SlideshowDuration(2, options));
+ }
+
+ [Fact]
+ public void A_picture_is_fitted_into_the_1080p_frame()
+ {
+ var args = MediaJoining.PrepareSlide("photo.png", "slide.jpg", 1920, 1080);
+
+ Assert.Contains("scale=1920:1080:force_original_aspect_ratio=decrease:force_divisible_by=2:flags=lanczos,pad=1920:1080",
+ After(args, "-vf"));
+ Assert.Equal("mjpeg", After(args, "-c:v"));
+ Assert.Equal((1920, 1080), MediaJoining.SlideshowFrame(new MediaOptions()));
+ }
+
+ [Fact]
+ public void A_long_graph_goes_into_a_file()
+ {
+ var work = Path.Combine(Path.GetTempPath(), "filee-tests", Guid.NewGuid().ToString("N")[..8]);
+ try
+ {
+ var slides = Enumerable.Range(1, 100).Select(i => $"{i}.jpg").ToList();
+ var args = MediaJoining.Slideshow(slides, "out.mp4", new MediaOptions { Slideshow = true }, "libx264", work);
+
+ Assert.DoesNotContain("-filter_complex", args);
+ var file = After(args, "-/filter_complex");
+ Assert.Contains("[x98][s99]xfade", File.ReadAllText(file));
+ }
+ finally
+ {
+ if (Directory.Exists(work))
+ Directory.Delete(work, recursive: true);
+ }
+ }
+
+ [Fact]
+ public void Concat_lists_quote_every_path()
+ {
+ var list = MediaJoining.ConcatList(["it's.mp4"]);
+ Assert.StartsWith("file '", list);
+ Assert.EndsWith(@"it'\''s.mp4'" + "\n", list);
+ }
+
+ [Fact]
+ public void Extract_audio_copies_aac_into_m4a_and_encodes_what_it_cannot_copy()
+ {
+ var copy = new MediaOptions { CopyAudioWhenPossible = true };
+ var aac = new AudioStreamInfo(2, 48000, "aac");
+ Assert.True(MediaEncoding.CanCopyIntoAudio("m4a", aac, copy));
+ Assert.False(MediaEncoding.CanCopyIntoAudio("m4a", new AudioStreamInfo(2, 48000, "opus"), copy));
+ Assert.False(MediaEncoding.CanCopyIntoAudio("m4a", aac, new MediaOptions())); // only when the preset asks
+ Assert.False(MediaEncoding.CanCopyIntoAudio("m4a", aac, new MediaOptions { CopyAudioWhenPossible = true, AudioBitrateKbps = 96 }));
+ Assert.False(MediaEncoding.CanCopyIntoAudio("m4a", aac, new MediaOptions { CopyAudioWhenPossible = true, AudioCodec = AudioCodec.Alac }));
+
+ var phone = new MediaInfo(TimeSpan.FromSeconds(10), PhoneVideo, aac, null);
+ var args = MediaEncoding.Plan("in.mov", "out.m4a", "m4a", copy, phone, "work").Single().Arguments;
+ Assert.Equal("copy", After(args, "-c:a"));
+ }
+
+ [Fact]
+ public void Remove_metadata_copies_the_streams_without_tags_chapters_or_data_tracks()
+ {
+ var phone = new MediaInfo(TimeSpan.FromSeconds(10), PhoneVideo with { Codec = "hevc" }, new AudioStreamInfo(2, 48000, "aac"), null);
+
+ var args = MediaEncoding.WithoutMetadata("in.mov", "out.mov", "mov", phone);
+
+ Assert.Equal("copy", After(args, "-c"));
+ Assert.Equal("-1", After(args, "-map_metadata"));
+ Assert.Equal("-1", After(args, "-map_metadata:s"));
+ Assert.Equal("-1", After(args, "-map_chapters"));
+ Assert.Contains("0:V?", args);
+ Assert.DoesNotContain("0", args.Where((a, i) => i > 0 && args[i - 1] == "-map")); // never every stream (data tracks)
+ Assert.Equal("hvc1", After(args, "-tag:v"));
+ Assert.Equal("mov", After(args, "-f"));
+
+ var song = new MediaInfo(TimeSpan.FromSeconds(10), null, new AudioStreamInfo(2, 44100, "mp3"), 1);
+ var audio = MediaEncoding.WithoutMetadata("in.mp3", "out.mp3", "mp3", song);
+ Assert.Contains("0:v?", audio); // the album art stays
+ Assert.Equal("mp3", After(audio, "-f"));
+ }
+}
diff --git a/tests/Filee.Engines.Tests/MediaToolRealTests.cs b/tests/Filee.Engines.Tests/MediaToolRealTests.cs
new file mode 100644
index 00000000..44f0c195
--- /dev/null
+++ b/tests/Filee.Engines.Tests/MediaToolRealTests.cs
@@ -0,0 +1,407 @@
+// The everyday media tools run for real: videos and audio files merged, pictures made into a slideshow, a video's
+// sound extracted, and copies without metadata (videos and audio need Filee's FFmpeg, `pwsh build/fetch-engines.ps1
+// -Only ffmpeg`; pictures and PDFs always run). Inputs are generated; every output is checked with ffprobe or by
+// reading it back.
+
+using System.Globalization;
+using System.Text;
+using System.Text.Json;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Infrastructure;
+using Filee.Engines.Media;
+using ImageMagick;
+using PdfSharp.Pdf;
+using PdfSharp.Pdf.IO;
+
+namespace Filee.Engines.Tests;
+
+[Collection(nameof(FfmpegCollection))]
+public class MediaToolRealTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static readonly (string Ffmpeg, string Ffprobe)? Tools = FfmpegConverter.Locate();
+
+ private static void SkipUnlessInstalled() =>
+ Assert.SkipUnless(Tools is not null, "FFmpeg is not installed (pwsh build/fetch-engines.ps1 -Only ffmpeg)");
+
+ private static Preset BuiltIn(string id) => BuiltInData.CreatePresets().Single(p => p.Id == id);
+
+ private async Task<string> RunAsync(IReadOnlyList<string> inputs, Preset preset)
+ {
+ var job = await fx.ConvertAsync(inputs, preset);
+ Assert.True(job.State == JobState.Completed, $"{job.State}: " + string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return Assert.Single(job.Outputs);
+ }
+
+ // ───────────────────────── Inputs ─────────────────────────
+
+ private static string Text(double value) => value.ToString(CultureInfo.InvariantCulture);
+
+ /// <summary>A test pattern clip, with a 440 Hz tone unless <paramref name="audio"/> is false.</summary>
+ private static async Task<string> MakeClipAsync(string folder, string name, double seconds = 2, string size = "320x240",
+ int fps = 25, bool audio = true, params string[] extra)
+ {
+ var path = Path.Combine(folder, name);
+ List<string> args = ["-hide_banner", "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", $"testsrc2=size={size}:rate={fps}:duration={Text(seconds)}"];
+ if (audio)
+ args.AddRange(["-f", "lavfi", "-i", $"sine=frequency=440:sample_rate=48000:duration={Text(seconds)}", "-ac", "2"]);
+ args.AddRange(extra);
+ args.Add(path);
+ await FfmpegAsync(args);
+ return path;
+ }
+
+ /// <summary>A tone of <paramref name="channels"/> channels, in the format the name's extension says.</summary>
+ private static async Task<string> MakeToneAsync(string folder, string name, double seconds, int channels = 2, int rate = 44100,
+ params string[] extra)
+ {
+ var path = Path.Combine(folder, name);
+ await FfmpegAsync(["-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi",
+ "-i", $"sine=frequency=330:sample_rate={rate}:duration={Text(seconds)}", "-ac", channels.ToString(CultureInfo.InvariantCulture),
+ .. extra, path]);
+ return path;
+ }
+
+ private static async Task<ProcessResult> FfmpegAsync(IEnumerable<string> args)
+ {
+ var result = await ProcessRunner.RunAsync(Tools!.Value.Ffmpeg, args, TimeSpan.FromMinutes(2), CancellationToken.None);
+ Assert.True(result.ExitCode == 0, result.StandardError);
+ return result;
+ }
+
+ // ───────────────────────── What ffprobe sees ─────────────────────────
+
+ private sealed record Track(string Type, string Codec, int Width, int Height, int Channels, Dictionary<string, string> Tags);
+
+ private sealed record Probed(double Duration, List<Track> Streams, Dictionary<string, string> Tags, int Chapters)
+ {
+ public Track? Video => Streams.FirstOrDefault(s => s.Type == "video");
+ public Track? Audio => Streams.FirstOrDefault(s => s.Type == "audio");
+ }
+
+ private static async Task<Probed> ProbeAsync(string path)
+ {
+ var result = await ProcessRunner.RunAsync(Tools!.Value.Ffprobe,
+ ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", "-show_chapters", path],
+ TimeSpan.FromMinutes(1), CancellationToken.None);
+ Assert.True(result.ExitCode == 0, $"ffprobe {path}: {result.StandardError}");
+ using var json = JsonDocument.Parse(result.StandardOutput);
+ static string S(JsonElement e, string name) => e.TryGetProperty(name, out var v) ? v.ToString() : "";
+ static int N(JsonElement e, string name) => int.TryParse(S(e, name), out var n) ? n : 0;
+ static Dictionary<string, string> Tags(JsonElement e) => e.TryGetProperty("tags", out var tags)
+ ? tags.EnumerateObject().ToDictionary(t => t.Name.ToLowerInvariant(), t => t.Value.ToString())
+ : [];
+ var root = json.RootElement;
+ var streams = root.GetProperty("streams").EnumerateArray()
+ .Select(s => new Track(S(s, "codec_type"), S(s, "codec_name"), N(s, "width"), N(s, "height"), N(s, "channels"), Tags(s)))
+ .ToList();
+ var format = root.GetProperty("format");
+ var duration = double.Parse(S(format, "duration"), CultureInfo.InvariantCulture);
+ var chapters = root.TryGetProperty("chapters", out var c) ? c.GetArrayLength() : 0;
+ return new Probed(duration, streams, Tags(format), chapters);
+ }
+
+ /// <summary>A hash of the packets of a file's first stream of <paramref name="type"/> ("a" or "v"): equal when copied.</summary>
+ private static async Task<string> StreamHashAsync(string path, string type)
+ {
+ var result = await FfmpegAsync(["-hide_banner", "-nostdin", "-v", "error", "-i", path, "-map", $"0:{type}:0", "-c", "copy",
+ "-f", "streamhash", "-hash", "md5", "-"]);
+ return result.StandardOutput.Split('=', 2)[^1].Trim();
+ }
+
+ // ───────────────────────── Merge videos ─────────────────────────
+
+ [Fact]
+ public async Task Clips_from_one_camera_are_merged_without_an_encode()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ string[] h264 = ["-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac"];
+ var first = await MakeClipAsync(folder, "a.mp4", 2, extra: h264);
+ var second = await MakeClipAsync(folder, "b.mp4", 1.5, extra: h264);
+
+ var output = await RunAsync([first, second], BuiltIn("merge-videos"));
+
+ Assert.Equal(Path.Combine(folder, "a_merged.mp4"), output);
+ var probed = await ProbeAsync(output);
+ Assert.InRange(probed.Duration, 3.3, 3.7);
+ Assert.Equal(("h264", 320, 240), (probed.Video!.Codec, probed.Video.Width, probed.Video.Height));
+ Assert.Equal("aac", probed.Audio!.Codec);
+ }
+
+ [Fact]
+ public async Task Clips_of_other_sizes_and_without_sound_are_fitted_into_the_first_ones_frame()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var first = await MakeClipAsync(folder, "a.mp4", 2, extra: ["-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac"]);
+ var wide = await MakeClipAsync(folder, "b.mkv", 1, size: "640x360", fps: 30, audio: false, extra: ["-c:v", "libx264"]);
+ var webm = await MakeClipAsync(folder, "c.webm", 1, size: "160x120", extra: ["-c:v", "libvpx-vp9", "-c:a", "libopus"]);
+
+ var output = await RunAsync([first, wide, webm], BuiltIn("merge-videos"));
+
+ var probed = await ProbeAsync(output);
+ Assert.InRange(probed.Duration, 3.8, 4.3);
+ Assert.Equal(("h264", 320, 240), (probed.Video!.Codec, probed.Video.Width, probed.Video.Height));
+ Assert.Equal("aac", probed.Audio!.Codec);
+ }
+
+ // ───────────────────────── Merge audio ─────────────────────────
+
+ [Fact]
+ public async Task Audio_files_are_joined_into_one_m4a_with_no_gap()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var wav = await MakeToneAsync(folder, "a.wav", 2);
+ var mp3 = await MakeToneAsync(folder, "b.mp3", 1, channels: 1, rate: 22050);
+ var clip = await MakeClipAsync(folder, "c.mp4", 1, extra: ["-c:v", "libx264", "-c:a", "aac"]);
+
+ var output = await RunAsync([wav, mp3, clip], BuiltIn("merge-audio"));
+
+ Assert.Equal(Path.Combine(folder, "a_merged.m4a"), output);
+ var probed = await ProbeAsync(output);
+ Assert.InRange(probed.Duration, 3.95, 4.08); // 2 + 1 + 1 seconds, nothing in between
+ Assert.Null(probed.Video);
+ Assert.Equal(("aac", 2), (probed.Audio!.Codec, probed.Audio.Channels));
+ }
+
+ // ───────────────────────── Video from images ─────────────────────────
+
+ [Fact]
+ public async Task Pictures_become_a_1080p_video_with_crossfades()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var pictures = new[]
+ {
+ EngineFixture.MakeImage(folder, "1.png", MagickFormat.Png, 320, 200),
+ EngineFixture.MakeImage(folder, "2.jpg", MagickFormat.Jpeg, 200, 320),
+ EngineFixture.MakeImage(folder, "3.webp", MagickFormat.WebP, 1000, 1000),
+ };
+
+ var output = await RunAsync(pictures, BuiltIn("video-from-images"));
+
+ Assert.Equal(Path.Combine(folder, "1_video.mp4"), output);
+ var probed = await ProbeAsync(output);
+ Assert.InRange(probed.Duration, 6.9, 7.1); // 3 × 3 s, minus two 1 s fades
+ Assert.Equal(("h264", 1920, 1080), (probed.Video!.Codec, probed.Video.Width, probed.Video.Height));
+ Assert.Null(probed.Audio);
+ }
+
+ [Fact]
+ public async Task Without_crossfades_each_picture_shows_for_its_whole_time()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var preset = BuiltIn("video-from-images");
+ preset.Media.Crossfade = false;
+ preset.Media.SlideSeconds = 1.5;
+
+ var output = await RunAsync(
+ [EngineFixture.MakeImage(folder, "1.png", MagickFormat.Png), EngineFixture.MakeImage(folder, "2.png", MagickFormat.Png)], preset);
+
+ Assert.InRange((await ProbeAsync(output)).Duration, 2.9, 3.1);
+ }
+
+ // ───────────────────────── Extract audio ─────────────────────────
+
+ [Fact]
+ public async Task A_phone_videos_aac_sound_is_copied_into_m4a()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var clip = await MakeClipAsync(folder, "IMG_0001.mov", 2, extra: ["-c:v", "libx264", "-c:a", "aac", "-b:a", "96k"]);
+
+ var output = await RunAsync([clip], BuiltIn("extract-audio"));
+
+ Assert.Equal(Path.Combine(folder, "IMG_0001.m4a"), output);
+ var probed = await ProbeAsync(output);
+ Assert.Null(probed.Video);
+ Assert.Equal("aac", probed.Audio!.Codec);
+ Assert.Equal(await StreamHashAsync(clip, "a"), await StreamHashAsync(output, "a")); // the same packets
+ }
+
+ [Fact]
+ public async Task Sound_m4a_cannot_hold_is_encoded_to_aac()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var clip = await MakeClipAsync(folder, "clip.webm", 1, extra: ["-c:v", "libvpx-vp9", "-c:a", "libopus"]);
+
+ var probed = await ProbeAsync(await RunAsync([clip], BuiltIn("extract-audio")));
+
+ Assert.Equal("aac", probed.Audio!.Codec);
+ }
+
+ // ───────────────────────── Remove metadata ─────────────────────────
+
+ [Fact]
+ public async Task A_video_loses_its_tags_and_chapters_and_keeps_its_streams()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var chapters = Path.Combine(folder, "chapters.txt");
+ await File.WriteAllTextAsync(chapters, ";FFMETADATA1\ntitle=Secret trip\nartist=Jane Doe\n" +
+ "[CHAPTER]\nTIMEBASE=1/1000\nSTART=0\nEND=1000\ntitle=Arrival\n");
+ var clip = Path.Combine(folder, "trip.mp4");
+ await FfmpegAsync(
+ [
+ "-hide_banner", "-nostdin", "-v", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=25:duration=2",
+ "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=2",
+ "-f", "ffmetadata", "-i", chapters, "-map", "0", "-map", "1", "-map_metadata", "2", "-map_chapters", "2",
+ "-c:v", "libx264", "-c:a", "aac", "-metadata", "creation_time=2020-05-01T10:00:00Z",
+ "-metadata", "location=+37.5665+126.9780/", "-metadata:s:a:0", "handler_name=Jane's phone", clip,
+ ]);
+ var before = await ProbeAsync(clip);
+ Assert.Equal("Secret trip", before.Tags["title"]);
+ Assert.Equal(1, before.Chapters);
+
+ var output = await RunAsync([clip], BuiltIn("remove-metadata"));
+
+ Assert.Equal(Path.Combine(folder, "trip_clean.mp4"), output);
+ var after = await ProbeAsync(output);
+ foreach (var tag in new[] { "title", "artist", "creation_time", "location", "comment" })
+ Assert.False(after.Tags.ContainsKey(tag), tag);
+ Assert.DoesNotContain(after.Streams, s => s.Tags.Values.Any(v => v.Contains("Jane", StringComparison.Ordinal)));
+ Assert.Equal(0, after.Chapters);
+ var bytes = Encoding.Latin1.GetString(await File.ReadAllBytesAsync(output));
+ Assert.DoesNotContain("Secret trip", bytes);
+ Assert.DoesNotContain("+37.5665", bytes);
+ Assert.Equal(await StreamHashAsync(clip, "v"), await StreamHashAsync(output, "v"));
+ Assert.Equal(await StreamHashAsync(clip, "a"), await StreamHashAsync(output, "a"));
+ }
+
+ [Fact]
+ public async Task A_song_loses_its_tags_and_stays_an_mp3()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var song = await MakeToneAsync(folder, "song.mp3", 2, extra:
+ ["-metadata", "title=Private song", "-metadata", "artist=Jane Doe", "-metadata", "date=2019"]);
+
+ var output = await RunAsync([song], BuiltIn("remove-metadata"));
+
+ Assert.Equal(".mp3", Path.GetExtension(output));
+ var after = await ProbeAsync(output);
+ Assert.Equal("mp3", after.Audio!.Codec);
+ Assert.False(after.Tags.ContainsKey("title"));
+ Assert.False(after.Tags.ContainsKey("artist"));
+ Assert.DoesNotContain("Jane Doe", Encoding.Latin1.GetString(await File.ReadAllBytesAsync(output)));
+ Assert.Equal(await StreamHashAsync(song, "a"), await StreamHashAsync(output, "a"));
+ }
+
+ [Fact]
+ public async Task A_photo_loses_its_exif_and_keeps_its_pixels_and_quality()
+ {
+ var folder = fx.NewFolder();
+ var photo = Path.Combine(folder, "IMG_0002.jpg");
+ using (var image = new MagickImage("gradient:#7F77DD-#1D9E75", 400, 300))
+ {
+ var exif = new ExifProfile();
+ exif.SetValue(ExifTag.Make, "Filee Camera");
+ exif.SetValue(ExifTag.DateTimeOriginal, "2020:05:01 10:00:00");
+ exif.SetValue(ExifTag.GPSLatitudeRef, "N");
+ image.SetProfile(exif);
+ image.Comment = "Jane's holiday";
+ image.Quality = 80;
+ image.Write(photo, MagickFormat.Jpeg);
+ }
+
+ var output = await RunAsync([photo], BuiltIn("remove-metadata"));
+
+ Assert.Equal(Path.Combine(folder, "IMG_0002_clean.jpg"), output);
+ using var clean = new MagickImage(output);
+ Assert.Null(clean.GetExifProfile());
+ Assert.Null(clean.GetXmpProfile());
+ Assert.True(string.IsNullOrEmpty(clean.Comment));
+ Assert.Equal((400u, 300u), (clean.Width, clean.Height));
+ Assert.InRange(clean.Quality, 78u, 82u); // saved at the photo's own quality, not above it
+ var bytes = Encoding.Latin1.GetString(await File.ReadAllBytesAsync(output));
+ Assert.DoesNotContain("Filee Camera", bytes);
+ Assert.DoesNotContain("Jane", bytes);
+ }
+
+ [Fact]
+ public async Task A_pdf_loses_its_author_and_title_and_keeps_its_pages()
+ {
+ var folder = fx.NewFolder();
+ var path = Path.Combine(folder, "contract.pdf");
+ using (var document = new PdfDocument())
+ {
+ document.Info.Author = "Jane Doe";
+ document.Info.Title = "Secret contract";
+ document.Info.Keywords = "confidential";
+ document.AddPage();
+ document.AddPage();
+ document.Save(path);
+ }
+
+ var output = await RunAsync([path], BuiltIn("remove-metadata"));
+
+ Assert.Equal(Path.Combine(folder, "contract_clean.pdf"), output);
+ using (var clean = PdfReader.Open(output, PdfDocumentOpenMode.Import))
+ {
+ Assert.Equal(2, clean.PageCount);
+ Assert.True(string.IsNullOrEmpty(clean.Info.Author));
+ Assert.True(string.IsNullOrEmpty(clean.Info.Title));
+ }
+ var bytes = Encoding.Latin1.GetString(await File.ReadAllBytesAsync(output));
+ Assert.DoesNotContain("Jane Doe", bytes);
+ Assert.DoesNotContain("Secret contract", bytes);
+ Assert.DoesNotContain("confidential", bytes);
+ }
+
+ // ───────────────────────── Compress ─────────────────────────
+
+ [Fact]
+ public async Task Compress_audio_saves_a_smaller_aac_copy()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var wav = await MakeToneAsync(folder, "talk.wav", 5);
+
+ var output = await RunAsync([wav], BuiltIn("compress-audio"));
+
+ Assert.Equal(Path.Combine(folder, "talk_compressed.m4a"), output);
+ Assert.Equal("aac", (await ProbeAsync(output)).Audio!.Codec);
+ Assert.True(new FileInfo(output).Length < new FileInfo(wav).Length / 5);
+ }
+
+ [Fact]
+ public async Task Compress_video_saves_a_1080p_h264_mp4()
+ {
+ SkipUnlessInstalled();
+ var folder = fx.NewFolder();
+ var clip = await MakeClipAsync(folder, "big.mov", 1, size: "2560x1440", extra: ["-c:v", "libx264", "-crf", "10", "-c:a", "aac"]);
+
+ var output = await RunAsync([clip], BuiltIn("compress-video"));
+
+ Assert.Equal(Path.Combine(folder, "big_compressed.mp4"), output);
+ var probed = await ProbeAsync(output);
+ Assert.Equal(("h264", 1920, 1080), (probed.Video!.Codec, probed.Video.Width, probed.Video.Height));
+ Assert.True(new FileInfo(output).Length < new FileInfo(clip).Length);
+ }
+
+ [Fact]
+ public async Task Compress_image_saves_a_smaller_png_with_the_same_pixels()
+ {
+ var folder = fx.NewFolder();
+ var png = Path.Combine(folder, "screen.png");
+ using (var image = new MagickImage("plasma:fractal", 300, 200))
+ {
+ image.Settings.SetDefine(MagickFormat.Png, "compression-level", "1");
+ image.Write(png, MagickFormat.Png);
+ }
+
+ var output = await RunAsync([png], BuiltIn("compress-image"));
+
+ Assert.Equal(Path.Combine(folder, "screen_compressed.png"), output);
+ Assert.True(new FileInfo(output).Length < new FileInfo(png).Length);
+ using var original = new MagickImage(png);
+ using var compressed = new MagickImage(output);
+ Assert.Equal(0, original.Compare(compressed, ErrorMetric.Absolute));
+ }
+}