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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Add bidirectional Apple Live Photo and Android Motion Photo conversion
sunpinenuts26b56876594d
diff --git a/README.md b/README.mdindex 80df1e70..4ae1967b 100644--- a/README.md+++ b/README.md@@ -108,6 +108,9 @@ Unmarked formats work out of the box, without Office, Hancom Office or LibreOffiMarked ones need an optional engine, downloaded only when needed: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre,⁵ FFmpeg ([details](docs/ENGINES.md)).+Experimental [Live/Motion Photo conversion](docs/LIVE-PHOTOS.md): short videos → Apple LIVP or Android Motion Photo,+and supported camera photos → MP4/MOV. FFmpeg required; phone-gallery compatibility still needs device validation.+## Command lineThe `filee` command uses the same engines and presets as the app (Setup or `install.sh` adds it).diff --git a/README.zh-CN.md b/README.zh-CN.mdindex d0d077aa..58d5c23b 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -107,6 +107,9 @@标注的格式需要可选引擎,只在需要时下载,分别是 ¹ Ghostscript、² LibreOffice、³ Pandoc、⁴ calibre、⁵ FFmpeg([详情](docs/ENGINES.md))。+实验性[实况/动态照片转换](docs/LIVE-PHOTOS.md):短视频转苹果 LIVP 或安卓 Motion Photo,以及支持的实况照片转 MP4/MOV。+需要 FFmpeg,手机相册的兼容性仍需实机验证。+## 命令行`filee` 命令使用与应用相同的引擎和预设(安装程序或 `install.sh` 会添加它)。diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 0c41f275..21bb53bd 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -933,6 +933,10 @@ Filee (with the GPL source offer), then an `engines.json` component and an optio## FFmpeg+Short SDR videos can also become Apple LIVP packages or Android JPEG Motion Photos. Camera-image motion is exported+through an explicit extraction preset; ordinary still-image routes are unchanged. See [Live and Motion Photos](LIVE-PHOTOS.md)+for clip options, supported input layouts, import instructions and the device compatibility checks still required.+`Media/FfmpegConverter.cs` converts every video format to every video format, to animated GIF or APNG, to a still PNGframe or a folder of every frame, to every audio format (the sound track) and to SRT, ASS and WebVTT (the subtitles);every audio format to every audio format; and GIF, APNG and PNG to MP4, WEBM and MOV.diff --git a/docs/LIVE-PHOTOS.md b/docs/LIVE-PHOTOS.mdnew file mode 100644index 00000000..df1c2b57--- /dev/null+++ b/docs/LIVE-PHOTOS.md@@ -0,0 +1,41 @@+# Live and Motion Photos++Filee can convert short SDR videos into Apple Live Photos or standard Android Motion Photos, and export the motion from supported camera photos as MP4/MOV. Install **FFmpeg** in Settings → Engines first.++## Create a photo from a video++In Settings → Presets, choose **Live Photo (iPhone · LIVP)** or **Motion Photo (Android)**. Set the clip start, length (0.1–10 seconds, default 3), and cover time relative to the clip start. A cover beyond the clip is limited to its last frame. The clip is shortened at the end of the source. Audio is kept unless **Remove audio** is selected. Video is encoded as H.264 at 30 fps, with AAC audio when present; surround sound is mixed to stereo. The usual quality and maximum-height options apply. HDR creation is refused rather than silently producing an incorrectly rendered cover; export an SDR clip first.++The new presets are added to the preset library when upgrading. Add them to a toolbar in Settings → Donut toolbar; existing donut assignments are preserved.++### iPhone++The output is a `.livp` ZIP containing a same-named JPEG/MOV pair with one shared Apple content identifier. The JPEG contains Apple maker-note tag 17; the movie has movie-level pairing metadata and a boxed timed metadata track marking the selected cover frame.++**A LIVP is a transport package, not an Apple Photos import API.** Unpack it and use an importer that submits the JPEG and paired MOV as one Live Photo (for example, an application using `PHAssetCreationRequest` with photo and paired-video resources). Sending the ZIP to Files, or importing the two assets independently, does not ensure that Photos creates a Live Photo. This implementation has generated-fixture and ffprobe validation, but has **not been verified by importing into Apple Photos on an iPhone or Mac**. On-device import remains a required compatibility check.++### Android++The output is a `.motion.jpg` JPEG with Google Motion Photo 1.0 XMP container metadata and an appended MP4. Copy it without recompressing to a gallery that supports standard Motion Photos. Renaming it to `.jpg` preserves the data; an editor or messaging service that re-encodes only the still will discard the motion.++This targets the **published Motion Photo format**, not every manufacturer's private variant. Google Photos / Pixel and compatible Samsung galleries are intended targets, but **no phone-gallery import has been verified yet**. Xiaomi, OPPO, vivo, Huawei, and older Samsung SEF-only photos require representative files and device testing before claiming compatibility. No private vendor-specific writer is included.++## Export the motion as video++- Drop a `.livp` or `.motion.jpg` onto MP4/MOV, or use the **Extract live video** preset.+- For a camera `.jpg`, `.heic`, or `.avif`, use **Extract live video**, or enable **Extract Live/Motion Photo video** in an MP4/MOV preset. This is explicit so ordinary image-to-video conversions keep their existing still-picture behavior.+- Android input supports JPEG Motion Photo 1.0 container-length metadata, legacy Google Microvideo offset metadata, and HEIC/AVIF top-level `mpvd` video boxes. XMP namespace prefixes may differ. A disabled or stale motion flag does not authorize guessing a video by scanning image bytes.+- Apple input supports LIVP packages and adjacent same-basename JPEG/HEIC + MOV exports. Both content identifiers must match; same names alone are insufficient. Keep both original assets together. The ZIP may contain one pair only; assets are copied into private scratch paths, never extracted using archive-supplied paths.++The image and source video are never modified. A normal still, missing companion, invalid offset, mismatched identifier, or unsupported vendor layout reports an error instead of silently returning a static clip. Extracted embedded videos are limited to 512 MiB; LIVP still entries are limited to 64 MiB. Exported MP4/MOV files follow the existing FFmpeg preset's encoding/remux rules, including optional audio removal.++## Verification and references++Tests generate their own videos and covers. They exercise both output types with/without audio, round trips, trimming, cover timing, ordinary-photo behavior, namespace variants, invalid offsets, pairing mismatches, and malformed boxes. ffprobe independently checks that the Apple timed marker is a `mebx` stream at the selected presentation time.++- [Android Motion Photo 1.0 specification](https://developer.android.com/media/platform/motion-photo-format)+- [Apple timed metadata sample descriptions](https://developer.apple.com/documentation/quicktime-file-format/timed_metadata_sample_descriptions)+- [Apple paired video resource](https://developer.apple.com/documentation/photos/phassetresourcetype/pairedvideo)+- [ExifTool's Apple maker-note tag documentation](https://exiftool.org/TagNames/Apple.html)++Related request: [#174](https://github.com/KnifeLemon/Filee/issues/174). Vendor compatibility and device validation remain open work.diff --git a/docs/screenshots/preset-livephoto-livp-en.png b/docs/screenshots/preset-livephoto-livp-en.pngnew file mode 100644index 00000000..38e69c7cBinary files /dev/null and b/docs/screenshots/preset-livephoto-livp-en.png differdiff --git a/docs/screenshots/preset-livephoto-motionphoto-en.png b/docs/screenshots/preset-livephoto-motionphoto-en.pngnew file mode 100644index 00000000..0d7aa384Binary files /dev/null and b/docs/screenshots/preset-livephoto-motionphoto-en.png differdiff --git a/docs/screenshots/preset-livephoto-mp4-zh-CN.png b/docs/screenshots/preset-livephoto-mp4-zh-CN.pngnew file mode 100644index 00000000..0f0929cdBinary files /dev/null and b/docs/screenshots/preset-livephoto-mp4-zh-CN.png differdiff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 8c78c7ea..4dd4b8ab 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -1,4 +1,18 @@{+ "error.live_photo_hdr": "HDR video is not supported for Live/Motion Photo creation yet. Export an SDR clip first.",+ "format.livp": "Live Photo (iPhone · LIVP)",+ "format.motionphoto": "Motion Photo (Android)",+ "preset.extract_motion": "Extract live video",+ "presets.live_photo_start": "Clip start (s)",+ "presets.live_photo_duration": "Clip length (s)",+ "presets.live_photo_cover": "Cover in clip (s)",+ "presets.live_photo_cover_hint": "The cover time is relative to the selected clip and is limited to a frame inside it.",+ "presets.extract_motion_photo": "Extract Live/Motion Photo video",+ "presets.extract_motion_photo_hint": "Read embedded motion or a matching Apple photo/MOV pair. An ordinary still photo is reported as having no motion.",+ "notice.live_photo_import": "Unpack the LIVP and import its photo and MOV together with a Live Photo-aware importer. Phone import compatibility still needs device testing.",+ "notice.motion_photo_compatibility": "For galleries supporting standard Motion Photos. Vendor compatibility varies and still needs device testing.",+ "error.no_motion_photo": "No supported motion video or matching Live Photo pair was found.",+ "error.live_photo_clip": "Choose a valid start, a clip length of 0.1–10 seconds, and a non-negative cover time.","app.name": "Filee","app.tagline": "Drag, drop, converted.",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex f2961be3..48cd58f4 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -1,4 +1,18 @@{+ "error.live_photo_hdr": "La creación de Live/Motion Photo desde HDR aún no es compatible. Exporta primero un clip SDR.",+ "format.livp": "Live Photo (iPhone · LIVP)",+ "format.motionphoto": "Foto en movimiento (Android)",+ "preset.extract_motion": "Extraer vídeo de la foto",+ "presets.live_photo_start": "Inicio del clip (s)",+ "presets.live_photo_duration": "Duración del clip (s)",+ "presets.live_photo_cover": "Portada en el clip (s)",+ "presets.live_photo_cover_hint": "El tiempo de portada es relativo al clip seleccionado y se limita a un fotograma dentro de él.",+ "presets.extract_motion_photo": "Extraer vídeo de Live/Motion Photo",+ "presets.extract_motion_photo_hint": "Lee el vídeo incrustado o una pareja de foto/MOV de Apple. Las fotos estáticas indican que no tienen movimiento.",+ "notice.live_photo_import": "Descomprime el LIVP e importa la foto y el MOV juntos con una herramienta compatible con Live Photo. La compatibilidad con teléfonos requiere pruebas en dispositivos.",+ "notice.motion_photo_compatibility": "Para galerías compatibles con Motion Photo estándar. La compatibilidad varía según el fabricante y requiere pruebas en dispositivos.",+ "error.no_motion_photo": "No se encontró un vídeo de movimiento compatible ni una pareja Live Photo coincidente.",+ "error.live_photo_clip": "Elige un inicio válido, una duración de 0,1–10 segundos y un tiempo de portada no negativo.","app.name": "Filee","app.tagline": "Arrastra, suelta y convierte.","nav.home": "Inicio",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 2abedad4..7363cb4c 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -1,4 +1,18 @@{+ "error.live_photo_hdr": "HDR 동영상으로 Live/Motion Photo를 만들 수 없습니다. 먼저 SDR 클립으로 내보내세요.",+ "format.livp": "Live Photo (iPhone · LIVP)",+ "format.motionphoto": "모션 포토 (Android)",+ "preset.extract_motion": "실황 동영상 추출",+ "presets.live_photo_start": "클립 시작 (초)",+ "presets.live_photo_duration": "클립 길이 (초)",+ "presets.live_photo_cover": "클립 내 표지 (초)",+ "presets.live_photo_cover_hint": "표지 시간은 선택한 클립 기준이며 클립 안의 프레임으로 제한됩니다.",+ "presets.extract_motion_photo": "Live/Motion Photo 동영상 추출",+ "presets.extract_motion_photo_hint": "내장 동영상 또는 짝이 맞는 Apple 사진/MOV를 읽습니다. 일반 사진은 움직임이 없다고 표시됩니다.",+ "notice.live_photo_import": "LIVP의 압축을 풀고 Live Photo를 지원하는 가져오기 도구로 사진과 MOV를 함께 가져오세요. 휴대폰 호환성은 기기 테스트가 필요합니다.",+ "notice.motion_photo_compatibility": "표준 모션 포토를 지원하는 갤러리용입니다. 제조사별 호환성은 다르며 기기 테스트가 필요합니다.",+ "error.no_motion_photo": "지원되는 모션 동영상이나 일치하는 Live Photo 쌍을 찾지 못했습니다.",+ "error.live_photo_clip": "유효한 시작 시간, 0.1–10초 길이, 0 이상의 표지 시간을 선택하세요.","app.name": "Filee","app.tagline": "끌어서 놓으면, 변환 끝.",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 44222600..43e7f5b3 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -1,4 +1,18 @@{+ "error.live_photo_hdr": "Tworzenie Live/Motion Photo z HDR nie jest jeszcze obsługiwane. Najpierw wyeksportuj klip SDR.",+ "format.livp": "Live Photo (iPhone · LIVP)",+ "format.motionphoto": "Motion Photo (Android)",+ "preset.extract_motion": "Wyodrębnij wideo ze zdjęcia",+ "presets.live_photo_start": "Początek klipu (s)",+ "presets.live_photo_duration": "Długość klipu (s)",+ "presets.live_photo_cover": "Okładka w klipie (s)",+ "presets.live_photo_cover_hint": "Czas okładki liczy się od początku klipu i jest ograniczony do klatki w jego obrębie.",+ "presets.extract_motion_photo": "Wyodrębnij wideo Live/Motion Photo",+ "presets.extract_motion_photo_hint": "Odczytuje osadzone wideo lub pasującą parę zdjęcie/MOV Apple. Zwykłe zdjęcia zgłaszają brak ruchu.",+ "notice.live_photo_import": "Rozpakuj LIVP i zaimportuj zdjęcie oraz MOV razem narzędziem obsługującym Live Photo. Zgodność z telefonami wymaga testów na urządzeniach.",+ "notice.motion_photo_compatibility": "Dla galerii obsługujących standard Motion Photo. Zgodność zależy od producenta i wymaga testów na urządzeniach.",+ "error.no_motion_photo": "Nie znaleziono obsługiwanego wideo ruchu ani pasującej pary Live Photo.",+ "error.live_photo_clip": "Wybierz prawidłowy początek, długość 0,1–10 sekund i nieujemny czas okładki.","app.name": "Filee","app.tagline": "Przeciągnij, upuść, gotowe.",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex 40ded6da..49000c7d 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -1,4 +1,18 @@{+ "error.live_photo_hdr": "暂不支持用 HDR 视频生成实况/动态照片,请先导出 SDR 视频片段。",+ "format.livp": "苹果实况图(LIVP)",+ "format.motionphoto": "安卓动态照片(Motion Photo)",+ "preset.extract_motion": "提取实况视频",+ "presets.live_photo_start": "片段起点(秒)",+ "presets.live_photo_duration": "片段时长(秒)",+ "presets.live_photo_cover": "片段内封面(秒)",+ "presets.live_photo_cover_hint": "封面时间相对于所选片段,超出时会限制到片段内的有效帧。",+ "presets.extract_motion_photo": "提取实况/动态照片中的视频",+ "presets.extract_motion_photo_hint": "读取内嵌视频或配对的苹果照片与 MOV;普通静态照片会提示没有动态内容。",+ "notice.live_photo_import": "请解包 LIVP,用支持实况的导入工具将照片和 MOV 一起导入。手机相册兼容性仍需实机验证。",+ "notice.motion_photo_compatibility": "适用于支持标准 Motion Photo 的相册。各品牌兼容性不同,仍需实机验证。",+ "error.no_motion_photo": "未找到支持的动态视频或匹配的苹果实况照片配对。",+ "error.live_photo_clip": "请选择有效的起点、0.1–10 秒的时长,以及不小于零的封面时间。","app.name": "Filee","app.tagline": "拖一拖,放一放,转换完成。",diff --git a/src/Filee.App/Services/PresetAvailability.cs b/src/Filee.App/Services/PresetAvailability.csindex 742786eb..d8b130f1 100644--- a/src/Filee.App/Services/PresetAvailability.cs+++ b/src/Filee.App/Services/PresetAvailability.cs@@ -36,10 +36,11 @@ public sealed class PresetAvailability(ConverterCatalog catalog, ILocalizer loc,if (merge && f.Id == "pdf" && !turns)return true; // merged as it isvar frames = preset.SavesFramesOf(f.Id);+ var motion = preset.ExtractsMotionOf(f.Id);if (!turns)- return planner.CanConvert(f.Id, target, frames);+ return planner.CanConvert(f.Id, target, frames, motion);// Rotate / flip: a route only counts when an engine on it turns images (not a PDF or a video copied).- if (planner.Plan(f.Id, target, frames) is not { } route)+ if (planner.Plan(f.Id, target, frames, motion) is not { } route)return false;if (route.FirstTransformStep() >= 0)return true;diff --git a/src/Filee.App/ViewModels/FormatLabels.cs b/src/Filee.App/ViewModels/FormatLabels.csindex 61f3b5c9..64a2963b 100644--- a/src/Filee.App/ViewModels/FormatLabels.cs+++ b/src/Filee.App/ViewModels/FormatLabels.cs@@ -13,7 +13,13 @@ public static class FormatLabels/// <summary>The format's short name; the "folder" pseudo format (Extract) is translated.</summary>public static string Name(ILocalizer loc, FileFormat format) =>- format.Id == FormatRegistry.Folder ? loc["format.folder"] : format.DisplayName;+ format.Id switch+ {+ FormatRegistry.Folder => loc["format.folder"],+ "livp" => loc["format.livp"],+ "motionphoto" => loc["format.motionphoto"],+ _ => format.DisplayName,+ };/// <summary>Name of the format with id <paramref name="formatId"/>, or null when it is unknown.</summary>public static string? NameOf(ILocalizer loc, string formatId) =>diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.csindex 38bfca6c..2dbb9ca7 100644--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs@@ -73,7 +73,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject.Where(f => f.Writable).Select(f => new Choice<string>(f.Id,- f.Id == FormatRegistry.Folder ? loc["presets.target_folder"] : f.DisplayName,+ f.Id == FormatRegistry.Folder ? loc["presets.target_folder"] : FormatLabels.Name(loc, f),FormatLabels.Category(loc, f.Category))),];ResizeModes = Enum.GetValues<ResizeMode>().Select(v => new Choice<ResizeMode>(v, loc[$"presets.resize.{v}"])).ToList();@@ -122,6 +122,10 @@ public sealed partial class PresetEditorViewModel : ObservableObject_combineIntoOne = _edit.Archive.CombineIntoOne;_saveEveryFrame = _edit.Media.SaveEveryFrame;_frameInterval = _edit.Media.FrameInterval > 0 ? _edit.Media.FrameInterval : 1;+ _extractMotionPhoto = _edit.Media.ExtractMotionPhoto;+ _livePhotoStart = _edit.Media.LivePhotoStart;+ _livePhotoDuration = _edit.Media.LivePhotoDuration;+ _livePhotoCover = _edit.Media.LivePhotoCover;_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);@@ -196,7 +200,8 @@ public sealed partial class PresetEditorViewModel : ObservableObjectnameof(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(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace),+ nameof(ShowLivePhoto), nameof(ShowExtractMotionPhoto), nameof(LivePhotoNotice))]private Choice<string> _target;private VideoCodec _videoCodecValue;@@ -343,6 +348,10 @@ public sealed partial class PresetEditorViewModel : ObservableObject[ObservableProperty] private Choice<ArchiveLevel> _archiveLevel;[ObservableProperty] private bool _combineIntoOne;[ObservableProperty] private bool _saveEveryFrame;+ [ObservableProperty] private bool _extractMotionPhoto;+ [ObservableProperty] private double _livePhotoStart;+ [ObservableProperty] private double _livePhotoDuration;+ [ObservableProperty] private double _livePhotoCover;[ObservableProperty, NotifyPropertyChangedFor(nameof(FrameEstimate))]private int _frameInterval = 1;@@ -389,9 +398,9 @@ public sealed partial class PresetEditorViewModel : ObservableObjectprivate bool TargetIsLossyMedia => TargetIsVideo|| (TargetIsAudio && !LosslessAudioTargets.Contains(TargetId) && MediaCodecs.Effective(TargetId, _audioCodecValue) != AudioCodec.Alac);- public bool ShowImage => TargetIsImage;+ public bool ShowImage => TargetIsImage && !ShowLivePhoto;/// <summary>Images and PDFs (pictures placed on pages) can be turned and flipped.</summary>- private bool CanTurn => TargetIsImage || TargetId == "pdf";+ private bool CanTurn => (TargetIsImage && !ShowLivePhoto) || TargetId == "pdf";/// <summary>Rotate and flip for a PDF target, which has no image card to show them in.</summary>public bool ShowTurnForPdf => TargetId == "pdf";public bool ShowQuality => TargetId == BuiltInData.SameAsSource || LossyTargets.Contains(TargetId);@@ -400,7 +409,7 @@ public sealed partial class PresetEditorViewModel : ObservableObjectpublic bool ShowMultiPageTiff => TargetId is "tiff";public bool ShowIco => TargetId == "ico";/// <summary>PDF options (also used when a PDF source becomes images) mean nothing for media, archive, font, subtitle, data, e-mail and 3D targets.</summary>- public bool ShowPdf => TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font+ public bool ShowPdf => !ShowLivePhoto && TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Fontor FormatCategory.Subtitle or FormatCategory.Data or FormatCategory.Model3D) && TargetId != "eml";public bool ShowPdfBuild => TargetId == "pdf";public bool ShowPdfSplit => TargetId == "pdf";@@ -415,7 +424,11 @@ public sealed partial class PresetEditorViewModel : ObservableObjectpublic bool ShowDocument => TargetId == "pdf";/// <summary>Markdown can't hold pictures: they go into a folder next to it, or are left out.</summary>public bool ShowLeaveOutPictures => TargetId == "md";- public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels || ShowVideoCodec || ShowAudioCodec;+ public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels || ShowVideoCodec || ShowAudioCodec || ShowLivePhoto;+ /// <summary>Video clip options for Apple's LIVP or the Android Motion Photo target.</summary>+ public bool ShowLivePhoto => TargetId is "livp" or "motionphoto";+ public bool ShowExtractMotionPhoto => TargetId is "mp4" or "mov";+ public string LivePhotoNotice => _loc[TargetId == "livp" ? "notice.live_photo_import" : "notice.motion_photo_compatibility"];/// <summary>Mono / stereo for every audio target but AMR, which is mono by definition.</summary>public bool ShowAudioChannels => TargetIsAudio && TargetId != "amr";/// <summary>Sample rate and sample format: the PCM of WAV and W64 takes any.</summary>@@ -426,10 +439,10 @@ public sealed partial class PresetEditorViewModel : ObservableObjectpublic bool ShowHardwareEncoding => TargetIsVideo && MediaCodecs.TakesHardwareEncoding(TargetId, _videoCodecValue);/// <summary>M4A / M4B can hold Apple Lossless besides AAC.</summary>public bool ShowAudioCodec => AudioCodecs.Count > 1;- public bool ShowMediaQuality => TargetIsLossyMedia;- public bool ShowMaxHeight => TargetIsVideo;- public bool ShowAudioBitrate => TargetIsLossyMedia;- public bool ShowRemoveAudio => TargetIsVideo;+ public bool ShowMediaQuality => TargetIsLossyMedia || ShowLivePhoto;+ public bool ShowMaxHeight => TargetIsVideo || ShowLivePhoto;+ public bool ShowAudioBitrate => TargetIsLossyMedia || ShowLivePhoto;+ public bool ShowRemoveAudio => TargetIsVideo || ShowLivePhoto;public bool ShowArchive => TargetCategory == FormatCategory.Archive;public bool ShowArchiveOptions => ShowArchive && TargetId != FormatRegistry.Folder;/// <summary>"Extract" has nothing to set; a line says what it does instead.</summary>@@ -529,6 +542,10 @@ public sealed partial class PresetEditorViewModel : ObservableObject// Only where the option is shown: a box ticked for PNG and left behind by another target saves nothing.media.SaveEveryFrame = ShowSaveEveryFrame && SaveEveryFrame;media.FrameInterval = media.SaveEveryFrame ? Math.Clamp(FrameInterval, 1, 1000) : 1;+ media.ExtractMotionPhoto = ShowExtractMotionPhoto && ExtractMotionPhoto;+ media.LivePhotoStart = double.IsFinite(LivePhotoStart) ? Math.Max(0, LivePhotoStart) : 0;+ media.LivePhotoDuration = double.IsFinite(LivePhotoDuration) ? Math.Clamp(LivePhotoDuration, 0.1, 10) : 3;+ media.LivePhotoCover = double.IsFinite(LivePhotoCover) ? Math.Max(0, LivePhotoCover) : 1.5;_original.Archive.Level = ArchiveLevel.Value;_original.Archive.CombineIntoOne = CombineIntoOne;_original.Trace.Mode = TraceMode.Value;diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axamlindex f09800a2..bc3015c6 100644--- a/src/Filee.App/Views/PresetEditorView.axaml+++ b/src/Filee.App/Views/PresetEditorView.axaml@@ -140,6 +140,28 @@<Border x:Name="MediaCard" Classes="card" IsVisible="{Binding ShowMedia}" Padding="14"><StackPanel Spacing="10"><TextBlock Classes="h2" Text="{DynamicResource presets.group.media}" />+ <StackPanel Spacing="8" IsVisible="{Binding ShowLivePhoto}">+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding LivePhotoNotice}" />+ <Grid ColumnDefinitions="*,12,*,12,*">+ <StackPanel>+ <TextBlock Classes="label" Text="{DynamicResource presets.live_photo_start}" />+ <NumericUpDown Value="{Binding LivePhotoStart}" Minimum="0" Increment="0.1" FormatString="0.##" />+ </StackPanel>+ <StackPanel Grid.Column="2">+ <TextBlock Classes="label" Text="{DynamicResource presets.live_photo_duration}" />+ <NumericUpDown Value="{Binding LivePhotoDuration}" Minimum="0.1" Maximum="10" Increment="0.1" FormatString="0.##" />+ </StackPanel>+ <StackPanel Grid.Column="4">+ <TextBlock Classes="label" Text="{DynamicResource presets.live_photo_cover}" />+ <NumericUpDown Value="{Binding LivePhotoCover}" Minimum="0" Maximum="10" Increment="0.1" FormatString="0.##" />+ </StackPanel>+ </Grid>+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{DynamicResource presets.live_photo_cover_hint}" />+ </StackPanel>+ <StackPanel Spacing="2" IsVisible="{Binding ShowExtractMotionPhoto}">+ <CheckBox Content="{DynamicResource presets.extract_motion_photo}" IsChecked="{Binding ExtractMotionPhoto}" />+ <TextBlock Classes="caption" TextWrapping="Wrap" Margin="28,0,0,0" Text="{DynamicResource presets.extract_motion_photo_hint}" />+ </StackPanel><Grid ColumnDefinitions="*,12,*" IsVisible="{Binding ShowMediaQuality}"><StackPanel><TextBlock Classes="label" Text="{DynamicResource presets.media_quality}" />diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.csindex fbaee33f..9ddf6a04 100644--- a/src/Filee.Core/Conversion/IConverter.cs+++ b/src/Filee.Core/Conversion/IConverter.cs@@ -30,11 +30,12 @@ namespace Filee.Core.Conversion;/// <param name="FrameSequence">/// The edge writes every frame of a video as numbered pictures into a folder (<see cref="Presets.MediaOptions.SaveEveryFrame"/>)./// It is never part of an ordinary route (a video → JPG stays one still frame), and with-/// <see cref="RoutePlanner.Plan(string, string, bool)"/> asking for frames it is the whole route.+/// <see cref="RoutePlanner.Plan"/> asking for frames it is the whole route./// </param>+/// <param name="MotionPhoto">Only taken when explicitly extracting a camera image's motion; never a still-image route.</param>public readonly record struct ConversionEdge(string From, string To, int Cost = 10, bool ImageSourcesOnly = false, bool NotForImageSources = false,- bool DirectOnly = false, bool FrameSequence = false);+ bool DirectOnly = false, bool FrameSequence = false, bool MotionPhoto = false);/// <summary>/// A conversion an engine refuses with a reason the user can act on, shown in their language (the file's@@ -86,6 +87,7 @@ public interface IOutputAllocator/// <param name="FrameSequence">/// The step takes a <see cref="ConversionEdge.FrameSequence"/> edge: every frame of the video becomes a picture of/// format <paramref name="To"/> in one output folder.+/// </param>/// <param name="Notice">/// Records a note on a step that worked, as a localization key (e.g. <c>notice.pdf_not_smaller</c>): shown with the/// file's result. Null when nobody listens.diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.csindex 2ecb659a..15d1706a 100644--- a/src/Filee.Core/Conversion/JobQueue.cs+++ b/src/Filee.Core/Conversion/JobQueue.cs@@ -351,7 +351,8 @@ public sealed class JobQueue : IAsyncDisposable// "Save every frame": a video becomes a folder of pictures in one step of its own. Never for an intermediate// file, and never on the way to another format (video → JPG is otherwise one still frame).- var route = planner.Plan(source.Id, target, frames: finalOutput && job.Preset.SavesFramesOf(source.Id));+ var route = planner.Plan(source.Id, target, frames: finalOutput && job.Preset.SavesFramesOf(source.Id),+ motionPhoto: finalOutput && job.Preset.ExtractsMotionOf(source.Id));if (route is null)return Fail(file, "error.no_route", $"{source.Id} → {target}");diff --git a/src/Filee.Core/Conversion/RoutePlanner.cs b/src/Filee.Core/Conversion/RoutePlanner.csindex c9c6a7f4..e23083d1 100644--- a/src/Filee.Core/Conversion/RoutePlanner.cs+++ b/src/Filee.Core/Conversion/RoutePlanner.cs@@ -57,27 +57,28 @@ public sealed class RoutePlanner/// <see cref="ConversionEdge.FrameSequence"/> edge from <paramref name="from"/> to <paramref name="to"/>, or none./// Without it those edges are never taken./// </param>- public Route? Plan(string from, string to, bool frames = false)+ /// <param name="motionPhoto">Extract motion from a camera image through a dedicated direct edge.</param>+ public Route? Plan(string from, string to, bool frames = false, bool motionPhoto = false){from = from.ToLowerInvariant();to = to.ToLowerInvariant();- if (frames)+ if (frames || motionPhoto){var sequence = EdgesFrom(from)- .Where(e => e.Edge.FrameSequence && e.Edge.To == to)+ .Where(e => e.Edge.FrameSequence == frames && e.Edge.MotionPhoto == motionPhoto && e.Edge.To == to).OrderBy(e => e.Cost).FirstOrDefault();return sequence.Converter is null? null- : new Route([new RouteStep(sequence.Converter, from, to, FrameSequence: true)], sequence.Cost);+ : new Route([new RouteStep(sequence.Converter, from, to, FrameSequence: frames)], sequence.Cost);}// Same-format "conversions" (re-encode, split, compress) must use an explicit self edge.if (from == to){var best = EdgesFrom(from)- .Where(e => e.Edge.To == to && !e.Edge.FrameSequence)+ .Where(e => e.Edge.To == to && !e.Edge.FrameSequence && !e.Edge.MotionPhoto).OrderBy(e => e.Cost).FirstOrDefault();return best.Converter is null@@ -106,7 +107,7 @@ public sealed class RoutePlannerforeach (var (converter, edge, edgeCost) in EdgesFrom(node)){- if (edge.To == edge.From || edge.FrameSequence+ if (edge.To == edge.From || edge.FrameSequence || edge.MotionPhoto|| (edge.ImageSourcesOnly && !imageSource) || (edge.NotForImageSources && imageSource)|| (edge.DirectOnly && (node != from || edge.To != to)))continue;@@ -133,7 +134,7 @@ public sealed class RoutePlanner/// <summary>True if <paramref name="from"/> can be converted to <paramref name="to"/>.</summary>/// <param name="frames">Every frame of a video as pictures (see <see cref="Plan"/>).</param>- public bool CanConvert(string from, string to, bool frames = false) => Plan(from, to, frames) is not null;+ public bool CanConvert(string from, string to, bool frames = false, bool motionPhoto = false) => Plan(from, to, frames, motionPhoto) is not null;private IReadOnlyList<(IConverter Converter, ConversionEdge Edge, int Cost)> EdgesFrom(string format) =>_edgesFrom.TryGetValue(format, out var edges) ? edges : [];diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.csindex de25f16c..82881a0b 100644--- a/src/Filee.Core/Formats/FormatRegistry.cs+++ b/src/Filee.Core/Formats/FormatRegistry.cs@@ -22,6 +22,8 @@ public static class FormatRegistrynew("ico", "ICO", FormatCategory.Image, ["ico"]),new("avif", "AVIF", FormatCategory.Image, ["avif"]),new("heic", "HEIC", FormatCategory.Image, ["heic", "heif", "hif"]),+ new("livp", "Live Photo (iPhone)", FormatCategory.Image, ["livp"]),+ new("motionphoto", "Motion Photo (Android)", FormatCategory.Image, ["motion.jpg"]),new("jxl", "JPEG XL", FormatCategory.Image, ["jxl"]),new("jp2", "JPEG 2000", FormatCategory.Image, ["jp2", "j2k", "jpf", "jpx"]),new("psd", "PSD", FormatCategory.Image, ["psd"]),diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.csindex 7ec96870..8b8203f8 100644--- a/src/Filee.Core/Presets/BuiltInData.cs+++ b/src/Filee.Core/Presets/BuiltInData.cs@@ -68,6 +68,7 @@ public static class BuiltInData.. PdfCompressionPresets(),.. PdfSlidesPresets(),.. FramePresets(),+ .. LivePhotoPresets(),new() { Id = "to-docx", Name = "DOCX", TargetFormat = "docx" },new() { Id = "to-hwpx", Name = "HWPX", TargetFormat = "hwpx" },.. HwpPresets(),@@ -84,6 +85,16 @@ public static class BuiltInData.. TracePresets(),];+ /// <summary>+ /// Live/Motion Photo conversions, added to the library but not to a user's existing donut.+ /// </summary>+ public static List<Preset> LivePhotoPresets() =>+ [+ new() { Id = "to-livp", NameKey = "format.livp", TargetFormat = "livp" },+ new() { Id = "to-motionphoto", NameKey = "format.motionphoto", TargetFormat = "motionphoto" },+ new() { Id = "extract-motion", NameKey = "preset.extract_motion", TargetFormat = "mp4", Media = { ExtractMotionPhoto = true } },+ ];+/// <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.diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.csindex 1c2feb27..2017d09c 100644--- a/src/Filee.Core/Presets/Preset.cs+++ b/src/Filee.Core/Presets/Preset.cs@@ -130,6 +130,11 @@ public sealed class Preset&& MediaOptions.FrameTargets.Contains(TargetFormat)&& Formats.FormatRegistry.FindById(sourceFormat)?.Category == Formats.FormatCategory.Video;+ /// <summary>Explicitly extract motion from a camera image instead of making a video of its still image.</summary>+ public bool ExtractsMotionOf(string sourceFormat) => Media.ExtractMotionPhoto+ && TargetFormat is "mp4" or "mov"+ && Formats.FormatRegistry.FindById(sourceFormat)?.Category == Formats.FormatCategory.Image;+/// <summary>Creates a new random preset id.</summary>public static string NewId() => Guid.NewGuid().ToString("N")[..12];@@ -448,6 +453,18 @@ public sealed class MediaOptions/// </summary>public bool SaveEveryFrame { get; set; }+ /// <summary>MP4/MOV targets: read an image's embedded motion or its paired Live Photo video.</summary>+ public bool ExtractMotionPhoto { get; set; }++ /// <summary>Start of the clip, in seconds, when creating a Live/Motion Photo.</summary>+ public double LivePhotoStart { get; set; }++ /// <summary>Maximum clip length in seconds (0.1–10); short clips keep phone imports manageable.</summary>+ public double LivePhotoDuration { get; set; } = 3;++ /// <summary>Still frame time relative to the clip, in seconds; clamped to an actual frame in the clip.</summary>+ public double LivePhotoCover { get; set; } = 1.5;+/// <summary>With <see cref="SaveEveryFrame"/>: extract every Nth frame (1 = every frame).</summary>public int FrameInterval { get; set; } = 1;diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex f1fde541..f55d3200 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -64,7 +64,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 20;+ public const int CurrentSchemaVersion = 21;public int SchemaVersion { get; set; } = CurrentSchemaVersion;diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex 44dd6d23..10edf98c 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -549,6 +549,16 @@ internal static class SettingsMigrationschanged = true;}}+ // v21: Live/Motion Photo presets, on no existing donut. Preserve custom toolbar assignments.+ if (from < 21)+ {+ foreach (var preset in BuiltInData.LivePhotoPresets().Where(p => presets.All(existing => existing.Id != p.Id)))+ {+ presets.Add(preset);+ changed = true;+ }+ changed |= LearnExtensions(profiles, out _);+ }return changed;}diff --git a/src/Filee.Engines/Media/AppleLivePhoto.cs b/src/Filee.Engines/Media/AppleLivePhoto.csnew file mode 100644index 00000000..9cec3fdd--- /dev/null+++ b/src/Filee.Engines/Media/AppleLivePhoto.cs@@ -0,0 +1,177 @@+// Apple Live Photo pairing and a timed still-image marker. Only private FFmpeg scratch movies are rewritten.++using System.Buffers.Binary;+using System.Text;+using ImageMagick;+using static Filee.Engines.Media.MovieBoxes;++namespace Filee.Engines.Media;++internal static class AppleLivePhoto+{+ internal const string ContentIdentifier = "com.apple.quicktime.content.identifier";+ internal const string StillImageTime = "com.apple.quicktime.still-image-time";+ private const int MaxMovieHeader = 16 * 1024 * 1024;++ public static void WriteCover(string png, string jpeg, string identifier)+ {+ using var image = new MagickImage(png);+ var profile = new ExifProfile();+ profile.SetValue(ExifTag.MakerNote, MakerNote(identifier));+ image.SetProfile(profile);+ image.Quality = 90;+ image.Write(jpeg, MagickFormat.Jpeg);+ }++ internal static byte[] MakerNote(string identifier)+ {+ var id = Utf8(Guid.Parse(identifier).ToString("D").ToUpperInvariant() + "\0");+ // Apple maker-note offsets are relative to the note, whose IFD starts at byte 14.+ return Join(Utf8("Apple iOS\0"), U16(1), Utf8("MM"), U16(1),+ U16(17), U16(2), U32((uint)id.Length), U32(32), U32(0), id);+ }++ public static string? ImageIdentifier(string imagePath)+ {+ using var image = new MagickImage();+ image.Ping(imagePath);+ return ReadMakerNote(image.GetExifProfile()?.GetValue(ExifTag.MakerNote)?.Value);+ }++ internal static string? ReadMakerNote(byte[]? data)+ {+ if (data is null || data.Length < 16 || !data.AsSpan().StartsWith("Apple iOS\0"u8))+ return null;+ var little = data.AsSpan(12, 2).SequenceEqual("II"u8);+ if (!little && !data.AsSpan(12, 2).SequenceEqual("MM"u8))+ return null;+ ushort Read16(int at) => little ? BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(at)) : BinaryPrimitives.ReadUInt16BigEndian(data.AsSpan(at));+ uint Read32(int at) => little ? BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(at)) : BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(at));+ var count = Read16(14);+ if (16L + count * 12L > data.Length)+ return null;+ for (var i = 0; i < count; i++)+ {+ var at = 16 + i * 12;+ if (Read16(at) != 17 || Read16(at + 2) != 2)+ continue;+ var length = Read32(at + 4);+ var offset = Read32(at + 8);+ if (length < 36 || length > 128 || offset > data.Length || length > data.Length - offset)+ return null;+ var id = Encoding.ASCII.GetString(data, (int)offset, (int)length).TrimEnd('\0');+ return Guid.TryParse(id, out var guid) ? guid.ToString("D") : null;+ }+ return null;+ }++ private static (MovieBox Box, byte[] Payload) ReadMovie(Stream file)+ {+ file.Position = 0;+ while (file.Position < file.Length)+ {+ var box = ReadHeader(file);+ if (box.Type == "moov")+ {+ if (box.Length > MaxMovieHeader)+ throw new InvalidDataException("Live Photo movie metadata is too large.");+ var data = new byte[checked((int)(box.Length - box.HeaderLength))];+ file.ReadExactly(data);+ return (box, data);+ }+ file.Position = box.End;+ }+ throw new InvalidDataException("Live Photo has no movie metadata.");+ }++ public static string? MovieIdentifier(string path)+ {+ using var file = File.OpenRead(path);+ var (_, movie) = ReadMovie(file);+ var children = Children(movie);+ // Apple's movie-level meta is a plain container; FFmpeg also encounters a full-box meta under udta.+ var metadata = children.Where(c => c.Type == "meta").Select(c => c.Payload).ToList();+ foreach (var udta in children.Where(c => c.Type == "udta"))+ metadata.AddRange(Children(udta.Payload).Where(c => c.Type == "meta").Select(c => c.Payload));+ foreach (var data in metadata)+ {+ var atoms = Children(data, data.Length >= 4 && data.AsSpan(0, 4).SequenceEqual(new byte[4]) ? 4 : 0);+ var keys = atoms.FirstOrDefault(c => c.Type == "keys").Payload;+ var values = atoms.FirstOrDefault(c => c.Type == "ilst").Payload;+ if (keys is null || values is null || keys.Length < 8)+ continue;+ var keyList = Children(keys, 8);+ var index = keyList.FindIndex(k => k.Type == "mdta" && Encoding.UTF8.GetString(k.Payload) == ContentIdentifier) + 1;+ if (index == 0)+ continue;+ foreach (var value in Children(values).Where(v => v.Type == Encoding.Latin1.GetString(U32((uint)index))))+ {+ var item = Children(value.Payload).FirstOrDefault(c => c.Type == "data").Payload;+ if (item is { Length: > 8 } && Guid.TryParse(Encoding.UTF8.GetString(item, 8, item.Length - 8), out var id))+ return id.ToString("D");+ }+ }+ return null;+ }++ /// <summary>Adds movie-level pairing keys and one signed-byte timed metadata sample at the still frame.</summary>+ public static void TagMovie(string path, string identifier, double coverSeconds)+ {+ using var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);+ var (box, movie) = ReadMovie(file);+ if (box.End != file.Length)+ throw new InvalidDataException("Expected FFmpeg's trailing movie header.");+ var children = Children(movie);+ var mvhd = children.Single(c => c.Type == "mvhd").Payload;+ var scaleAt = mvhd[0] == 1 ? 20 : 12;+ var scale = BinaryPrimitives.ReadUInt32BigEndian(mvhd.AsSpan(scaleAt));+ var nextId = BinaryPrimitives.ReadUInt32BigEndian(mvhd.AsSpan(mvhd.Length - 4));+ if (scale == 0 || nextId == uint.MaxValue)+ throw new InvalidDataException("Invalid movie timescale or track id.");+ BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(mvhd.Length - 4), nextId + 1);+ var videoTrack = children.First(c => c.Type == "trak");+ var tkhd = Children(videoTrack.Payload).Single(c => c.Type == "tkhd").Payload;+ var videoId = BinaryPrimitives.ReadUInt32BigEndian(tkhd.AsSpan(tkhd[0] == 1 ? 20 : 12));+ var sample = Box("\0\0\0\u0001", [0xff]); // signed int8 marker, one local key+ var sampleOffset = checked((ulong)(box.Start + 8));+ var track = StillTrack(nextId, videoId, scale, coverSeconds, sampleOffset, (uint)sample.Length);+ var metadata = PairingMetadata(identifier);+ // No media data moves: existing stco/co64 entries still point at the same bytes.+ file.SetLength(box.Start);+ file.Position = box.Start;+ file.Write(Box("mdat", sample));+ file.Write(Box("moov", [.. children.Where(c => c.Type != "meta").Select(c => Box(c.Type, c.Payload)), track, metadata]));+ }++ private static byte[] PairingMetadata(string identifier)+ {+ var keys = new[] { ContentIdentifier, "com.apple.quicktime.live-photo.auto", "com.apple.quicktime.full-frame-rate-playback-intent" };+ var values = new[] { Box("data", U32(1), U32(0), Utf8(identifier)), Box("data", U32(21), U32(0), [1]), Box("data", U32(21), U32(0), U64(1)) };+ return Box("meta", Full("hdlr", Join(U32(0), Utf8("mdta"), new byte[13])),+ Full("keys", Join(U32((uint)keys.Length), Join([.. keys.Select(k => Box("mdta", Utf8(k)))]))),+ Box("ilst", [.. values.Select((v, i) => Box(Encoding.Latin1.GetString(U32((uint)i + 1)), v))]));+ }++ private static byte[] StillTrack(uint id, uint videoId, uint movieScale, double cover, ulong offset, uint sampleSize)+ {+ const uint timeScale = 1000;+ var start = checked((uint)Math.Round(cover * movieScale));+ var tick = Math.Max(1, movieScale / timeScale);+ var matrix = Join(U32(0x10000), U32(0), U32(0), U32(0), U32(0x10000), U32(0), U32(0), U32(0), U32(0x40000000));+ var tkhd = Full("tkhd", Join(U32(0), U32(0), U32(id), U32(0), U32(start + tick), new byte[16], matrix, new byte[8]), 3);+ var edits = new List<byte[]>();+ if (start > 0)+ edits.Add(Join(U32(start), U32(uint.MaxValue), U16(1), U16(0)));+ edits.Add(Join(U32(tick), U32(0), U16(1), U16(0)));+ var mebx = Box("mebx", new byte[6], U16(1), Box("keys", Box("\0\0\0\u0001",+ Box("keyd", Utf8("mdta" + StillImageTime)), Box("dtyp", U32(1), Utf8("com.apple.metadata.datatype.int8")))));+ var table = Box("stbl", Full("stsd", Join(U32(1), mebx)), Full("stts", Join(U32(1), U32(1), U32(1))),+ Full("stsc", Join(U32(1), U32(1), U32(1), U32(1))), Full("stsz", Join(U32(sampleSize), U32(1))),+ Full("co64", Join(U32(1), U64(offset))));+ var minf = Box("minf", Full("nmhd", []), Box("dinf", Full("dref", Join(U32(1), Full("url ", [], 1)))), table);+ var mdia = Box("mdia", Full("mdhd", Join(U32(0), U32(0), U32(timeScale), U32(1), U16(0x55c4), U16(0))),+ Full("hdlr", Join(U32(0), Utf8("mdta"), new byte[12], Utf8("Core Media Metadata\0"))), minf);+ return Box("trak", tkhd, Box("edts", Full("elst", Join(U32((uint)edits.Count), Join([.. edits])))),+ Box("tref", Box("cdsc", U32(videoId))), mdia);+ }+}diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.csindex 4a51d87f..8fed9554 100644--- a/src/Filee.Engines/Media/FfmpegConverter.cs+++ b/src/Filee.Engines/Media/FfmpegConverter.cs@@ -4,6 +4,7 @@// audio and GIF, APNG or a still picture → video, and images → HEIC (FFmpeg's HEVC encoder, Filee's own container// writer). Container and codec choices live in MediaEncoding, the process handling in FfmpegRunner, hardware encoders// in HardwareVideo (options) and HardwareProbe (which one works here).+// LivePhotoConversion writes Apple LIVP and Android Motion Photos; LivePhotoSource extracts their videos explicitly.using System.Collections.Concurrent;using System.Text.RegularExpressions;@@ -85,6 +86,13 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter.. MediaEncoding.PictureToVideoTargets.Select(target => new ConversionEdge("png", target, 11)),// HEIC: ImageMagick reads, x265 encodes, Filee writes the container (see Heic/HeicWriter)... ImageEncoder.Sources.Select(source => new ConversionEdge(source, "heic")),+ .. from source in videos from target in new[] { "livp", "motionphoto" }+ select new ConversionEdge(source, target, DirectOnly: true),+ .. from source in new[] { "jpg", "heic", "avif", "motionphoto", "livp" }+ from target in new[] { "mp4", "mov" }+ select new ConversionEdge(source, target, MotionPhoto: true),+ .. from source in new[] { "livp", "motionphoto" } from target in new[] { "mp4", "mov" }+ select new ConversionEdge(source, target, DirectOnly: true),];}@@ -107,6 +115,13 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverterpublic async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken){var (ffmpeg, ffprobe) = _tools ?? Locate() ?? throw new InvalidOperationException("FFmpeg was not found.");+ if (step.To is "livp" or "motionphoto")+ return await LivePhotoConversion.CreateAsync(ffmpeg, ffprobe, step, progress, cancellationToken);+ if (step.From is "livp" or "motionphoto" || step.Preset.ExtractsMotionOf(step.From))+ {+ var video = await LivePhotoSource.ExtractAsync(step.InputPath, step.WorkDirectory, cancellationToken);+ return await ConvertAsync(step with { InputPath = video, From = "mov" }, progress, cancellationToken);+ }if (step.To == "heic")return await HeicWriter.ConvertAsync(ffmpeg, step, progress, cancellationToken);var input = Path.GetFullPath(step.InputPath);diff --git a/src/Filee.Engines/Media/LivePhotoConversion.cs b/src/Filee.Engines/Media/LivePhotoConversion.csnew file mode 100644index 00000000..89bfb44e--- /dev/null+++ b/src/Filee.Engines/Media/LivePhotoConversion.cs@@ -0,0 +1,112 @@+// Video → Apple LIVP or standard Android JPEG Motion Photo, using the existing FFmpeg installation and options.++using System.Globalization;+using System.IO.Compression;+using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Core.Presets;+using ImageMagick;++namespace Filee.Engines.Media;++internal static class LivePhotoConversion+{+ public static async Task<IReadOnlyList<string>> CreateAsync(string ffmpeg, string ffprobe, ConversionStep step,+ IProgress<double>? progress, CancellationToken ct)+ {+ var info = await MediaInfo.ProbeAsync(ffprobe, step.InputPath, ct);+ if (info.Video is null || info.Duration is not { TotalSeconds: > 0 } duration)+ throw new ConversionRefusedException("error.live_photo_clip");+ if (info.Video.IsHdr)+ throw new ConversionRefusedException("error.live_photo_hdr");+ var (start, length, cover) = Clip(step.Preset.Media, duration.TotalSeconds);+ var output = step.Output.Allocate(FormatRegistry.Get(step.To).PrimaryExtension);+ if (output is null)+ return [];+ var token = Guid.NewGuid().ToString("N");+ var movie = Path.Combine(step.WorkDirectory, token + (step.To == "livp" ? ".mov" : ".mp4"));+ var png = Path.Combine(step.WorkDirectory, token + ".png");+ var jpeg = Path.Combine(step.WorkDirectory, token + ".jpg");+ var media = step.Preset.Media.Clone();+ media.VideoCodec = VideoCodec.Default;+ media.HardwareEncoding = false;+ if (info.Audio is { Channels: > 2 })+ media.AudioChannels = 2;+ // A new clip must be decoded even if an ordinary container conversion could copy its codec. Otherwise+ // stream-copy seeking starts on an earlier keyframe and -r cannot normalize variable frame rates.+ var encodedInfo = info with { Video = info.Video with { Codec = null }, Audio = info.Audio is { } audio ? audio with { Codec = null } : null };+ var pass = MediaEncoding.Plan(step.InputPath, movie, step.To == "livp" ? "mov" : "mp4", media, encodedInfo, step.WorkDirectory).Single();+ var args = pass.Arguments.ToList();+ var inputAt = args.IndexOf("-i");+ args.InsertRange(inputAt, ["-ss", Number(start)]);+ var movFlagsAt = args.IndexOf("-movflags");+ if (movFlagsAt >= 0)+ args.RemoveRange(movFlagsAt, 2); // Keep moov at EOF so adding the Apple marker never moves media samples.+ args.InsertRange(args.Count - 1, ["-t", Number(length), "-r", "30"]);+ if (info.Audio is not null && !media.RemoveAudio)+ args.InsertRange(args.Count - 1, ["-ar", "48000"]);+ await FfmpegConverter.RunPassAsync(ffmpeg, new FfmpegPass(args, 0.8), TimeSpan.FromSeconds(length), progress, 0, ct);+ // Select by frame number: rounding a fractional seek to microseconds could choose the following frame.+ await FfmpegConverter.RunPassAsync(ffmpeg, new FfmpegPass([+ .. MediaEncoding.Common, "-i", movie, "-map", "0:v:0", "-vf",+ "select=eq(n\\," + ((int)Math.Round(cover * 30)).ToString(CultureInfo.InvariantCulture) + ")",+ "-fps_mode", "vfr", "-frames:v", "1", "-update", "1", "-f", "image2", png,+ ], 0.1), null, progress, 0.8, ct);+ ct.ThrowIfCancellationRequested();+ try+ {+ if (step.To == "livp")+ {+ var id = Guid.NewGuid().ToString("D").ToUpperInvariant();+ AppleLivePhoto.WriteCover(png, jpeg, id);+ AppleLivePhoto.TagMovie(movie, id, cover);+ await using var archiveFile = File.Create(output);+ using var zip = new ZipArchive(archiveFile, ZipArchiveMode.Create, leaveOpen: true);+ await AddEntryAsync(zip, jpeg, id + ".jpg", ct);+ await AddEntryAsync(zip, movie, id + ".mov", ct);+ }+ else+ {+ using (var image = new MagickImage(png))+ {+ image.Quality = 90;+ image.Write(jpeg, MagickFormat.Jpeg);+ }+ await MotionPhoto.WriteAsync(jpeg, movie, output, (long)Math.Round(cover * 1_000_000), ct);+ }+ step.Notice?.Invoke(step.To == "livp" ? "notice.live_photo_import" : "notice.motion_photo_compatibility");+ progress?.Report(1);+ return [output];+ }+ catch+ {+ // Encoding only writes private scratch files. Remove an incomplete final archive/photo on failure.+ File.Delete(output);+ throw;+ }+ }++ internal static (double Start, double Duration, double Cover) Clip(MediaOptions options, double duration)+ {+ var start = options.LivePhotoStart;+ var length = options.LivePhotoDuration;+ var cover = options.LivePhotoCover;+ if (!double.IsFinite(start) || !double.IsFinite(length) || !double.IsFinite(cover) || start < 0+ || length < 0.1 || length > 10 || cover < 0 || start >= duration)+ throw new ConversionRefusedException("error.live_photo_clip");+ length = Math.Min(length, duration - start);+ if (length < 1.0 / 30)+ throw new ConversionRefusedException("error.live_photo_clip");+ cover = Math.Floor(Math.Min(cover, Math.Max(0, length - 1.0 / 30)) * 30) / 30;+ return (start, length, cover);+ }++ private static string Number(double value) => value.ToString("0.######", CultureInfo.InvariantCulture);++ private static async Task AddEntryAsync(ZipArchive zip, string path, string name, CancellationToken ct)+ {+ await using var source = File.OpenRead(path);+ await using var target = zip.CreateEntry(name, CompressionLevel.NoCompression).Open();+ await source.CopyToAsync(target, ct);+ }+}diff --git a/src/Filee.Engines/Media/LivePhotoSource.cs b/src/Filee.Engines/Media/LivePhotoSource.csnew file mode 100644index 00000000..910d9e53--- /dev/null+++ b/src/Filee.Engines/Media/LivePhotoSource.cs@@ -0,0 +1,76 @@+// Reads LIVP pairs and embedded Android motion videos without unpacking archive paths or changing camera files.++using System.IO.Compression;+using Filee.Core.Conversion;+using Filee.Core.Formats;++namespace Filee.Engines.Media;++internal static class LivePhotoSource+{+ private const long MaxVideoBytes = 512L * 1024 * 1024;+ private const long MaxImageBytes = 64L * 1024 * 1024;++ public static async Task<string> ExtractAsync(string input, string workDirectory, CancellationToken ct)+ {+ ct.ThrowIfCancellationRequested();+ var format = FormatRegistry.Detect(input)?.Id;+ if (format == "livp")+ return await ExtractPackageAsync(input, workDirectory, ct);+ await using var file = File.OpenRead(input);+ if (MotionPhoto.FindVideo(file) is { } video)+ {+ if (video.Length > MaxVideoBytes)+ throw new InvalidDataException("Motion Photo video exceeds 512 MiB.");+ MotionPhoto.ValidateVideo(file, video.Offset, video.Length);+ var output = Path.Combine(workDirectory, Guid.NewGuid().ToString("N") + ".mp4");+ await using var target = File.Create(output);+ file.Position = video.Offset;+ await MovieBoxes.CopyRangeAsync(file, target, video.Length, ct);+ return output;+ }+ if (format is "jpg" or "heic")+ {+ var id = AppleLivePhoto.ImageIdentifier(input);+ if (id is not null)+ {+ var name = Path.GetFileNameWithoutExtension(input);+ var siblings = Directory.EnumerateFiles(Path.GetDirectoryName(Path.GetFullPath(input))!)+ .Where(p => Path.GetExtension(p).Equals(".mov", StringComparison.OrdinalIgnoreCase)+ && Path.GetFileNameWithoutExtension(p).Equals(name, StringComparison.OrdinalIgnoreCase)).ToList();+ if (siblings.Count == 1 && id.Equals(AppleLivePhoto.MovieIdentifier(siblings[0]), StringComparison.OrdinalIgnoreCase))+ return siblings[0];+ }+ }+ throw new ConversionRefusedException("error.no_motion_photo");+ }++ private static async Task<string> ExtractPackageAsync(string path, string workDirectory, CancellationToken ct)+ {+ using var zip = ZipFile.OpenRead(path);+ var movies = zip.Entries.Where(e => Path.GetExtension(e.Name).Equals(".mov", StringComparison.OrdinalIgnoreCase)).ToList();+ var images = zip.Entries.Where(e => Path.GetExtension(e.Name).ToLowerInvariant() is ".jpg" or ".jpeg" or ".heic").ToList();+ if (movies.Count != 1 || images.Count != 1+ || !Path.GetFileNameWithoutExtension(movies[0].Name).Equals(Path.GetFileNameWithoutExtension(images[0].Name), StringComparison.OrdinalIgnoreCase))+ throw new InvalidDataException("A LIVP must contain exactly one matching photo/video pair.");+ var token = Guid.NewGuid().ToString("N");+ var movie = Path.Combine(workDirectory, token + ".mov");+ var image = Path.Combine(workDirectory, token + Path.GetExtension(images[0].Name).ToLowerInvariant());+ await CopyEntryAsync(movies[0], movie, MaxVideoBytes, ct);+ await CopyEntryAsync(images[0], image, MaxImageBytes, ct);+ var id = AppleLivePhoto.ImageIdentifier(image);+ if (id is null || !id.Equals(AppleLivePhoto.MovieIdentifier(movie), StringComparison.OrdinalIgnoreCase))+ throw new InvalidDataException("The Live Photo image and movie identifiers do not match.");+ return movie;+ }++ private static async Task CopyEntryAsync(ZipArchiveEntry entry, string target, long limit, CancellationToken ct)+ {+ if (entry.Length <= 0 || entry.Length > limit)+ throw new InvalidDataException("Live Photo archive entry is empty or too large.");+ // Never use an entry name as an output path; even a traversal entry stays in the job's scratch directory.+ await using var source = entry.Open();+ await using var output = File.Create(target);+ await MovieBoxes.CopyRangeAsync(source, output, entry.Length, ct);+ }+}diff --git a/src/Filee.Engines/Media/MotionPhoto.cs b/src/Filee.Engines/Media/MotionPhoto.csnew file mode 100644index 00000000..97c127d2--- /dev/null+++ b/src/Filee.Engines/Media/MotionPhoto.cs@@ -0,0 +1,141 @@+// Android JPEG Motion Photo metadata and bounded extraction of the video at the end of a camera image.++using System.Buffers.Binary;+using System.Globalization;+using System.Text;+using System.Xml;+using System.Xml.Linq;++namespace Filee.Engines.Media;++/// <summary>Google Motion Photo 1.0 JPEGs and legacy Microvideo JPEGs.</summary>+internal static class MotionPhoto+{+ private static readonly byte[] XmpHeader = "http://ns.adobe.com/xap/1.0/\0"u8.ToArray();+ private const string Camera = "http://ns.google.com/photos/1.0/camera/";+ private const string Container = "http://ns.google.com/photos/1.0/container/";+ private const string Item = "http://ns.google.com/photos/1.0/container/item/";++ /// <summary>Writes one standard JPEG Motion Photo, preserving the encoded picture and video bytes.</summary>+ public static async Task WriteAsync(string jpeg, string video, string output, long coverMicroseconds, CancellationToken ct)+ {+ var length = new FileInfo(video).Length;+ var xml = $"""+ <x:xmpmeta xmlns:x="adobe:ns:meta/">+ <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">+ <rdf:Description xmlns:Camera="{Camera}" xmlns:Container="{Container}" xmlns:Item="{Item}"+ Camera:MotionPhoto="1" Camera:MotionPhotoVersion="1" Camera:MotionPhotoPresentationTimestampUs="{coverMicroseconds.ToString(CultureInfo.InvariantCulture)}">+ <Container:Directory><rdf:Seq>+ <rdf:li rdf:parseType="Resource"><Container:Item Item:Mime="image/jpeg" Item:Semantic="Primary" Item:Length="0" Item:Padding="0" /></rdf:li>+ <rdf:li rdf:parseType="Resource"><Container:Item Item:Mime="video/mp4" Item:Semantic="MotionPhoto" Item:Length="{length.ToString(CultureInfo.InvariantCulture)}" /></rdf:li>+ </rdf:Seq></Container:Directory>+ </rdf:Description>+ </rdf:RDF>+ </x:xmpmeta>+ """;+ var payload = XmpHeader.Concat(Encoding.UTF8.GetBytes(xml)).ToArray();+ await using var image = File.OpenRead(jpeg);+ if (image.ReadByte() != 0xff || image.ReadByte() != 0xd8)+ throw new InvalidDataException("The Motion Photo cover is not a JPEG.");+ await using var dest = File.Create(output);+ dest.Write([0xff, 0xd8, 0xff, 0xe1]);+ var size = new byte[2];+ BinaryPrimitives.WriteUInt16BigEndian(size, checked((ushort)(payload.Length + 2)));+ dest.Write(size);+ await dest.WriteAsync(payload, ct);+ await image.CopyToAsync(dest, ct);+ await using var movie = File.OpenRead(video);+ await movie.CopyToAsync(dest, ct);+ }++ /// <summary>Finds the declared video, never by searching arbitrary image bytes for an MP4 signature.</summary>+ public static (long Offset, long Length)? FindVideo(Stream file)+ {+ file.Position = 0;+ if (file.ReadByte() == 0xff && file.ReadByte() == 0xd8)+ return FindJpegVideo(file);+ file.Position = 0;+ while (file.Position < file.Length)+ {+ var box = MovieBoxes.ReadHeader(file);+ if (box.Type == "mpvd")+ {+ if (box.End != file.Length || box.Length <= box.HeaderLength)+ throw new InvalidDataException("Invalid Motion Photo video box.");+ return (box.Start + box.HeaderLength, box.Length - box.HeaderLength);+ }+ file.Position = box.End;+ }+ return null;+ }++ private static (long Offset, long Length)? FindJpegVideo(Stream file)+ {+ // Metadata must precede JPEG scan data. Bound the walk even for a file made of thousands of segments.+ while (file.Position < Math.Min(file.Length, 8 * 1024 * 1024))+ {+ if (file.ReadByte() != 0xff)+ throw new InvalidDataException("Invalid JPEG marker.");+ int marker;+ do { marker = file.ReadByte(); } while (marker == 0xff);+ if (marker is 0xda or 0xd9)+ return null;+ if (marker < 0)+ throw new EndOfStreamException();+ var size = new byte[2];+ file.ReadExactly(size);+ var length = BinaryPrimitives.ReadUInt16BigEndian(size) - 2;+ if (length < 0 || length > file.Length - file.Position)+ throw new InvalidDataException("Invalid JPEG segment length.");+ if (marker == 0xe1)+ {+ var data = new byte[length];+ file.ReadExactly(data);+ if (data.AsSpan().StartsWith(XmpHeader))+ {+ using var reader = XmlReader.Create(new MemoryStream(data, XmpHeader.Length, data.Length - XmpHeader.Length),+ new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 65535 });+ var xml = XDocument.Load(reader);+ var attrs = xml.Descendants().Attributes().ToList();+ string? Value(string name) => attrs.FirstOrDefault(a => a.Name == XName.Get(name, Camera))?.Value;+ long videoLength;+ if (Value("MotionPhoto") is { } motion)+ {+ if (motion != "1")+ return null;+ var items = xml.Descendants(XName.Get("Item", Container)).ToList();+ var last = items.LastOrDefault();+ if (last?.Attribute(XName.Get("Semantic", Item))?.Value != "MotionPhoto"+ || last.Attribute(XName.Get("Mime", Item))?.Value is not ("video/mp4" or "video/quicktime")+ || !long.TryParse(last.Attribute(XName.Get("Length", Item))?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out videoLength))+ throw new InvalidDataException("Motion Photo has no valid video directory entry.");+ }+ else if (Value("MicroVideo") == "1"+ && long.TryParse(Value("MicroVideoOffset"), NumberStyles.None, CultureInfo.InvariantCulture, out videoLength))+ {+ // Microvideo v1 measured backwards from EOF; Motion Photo 1.0 replaced this property.+ }+ else+ continue;+ var start = file.Length - videoLength;+ if (videoLength < 12 || start < file.Position)+ throw new InvalidDataException("Motion Photo video length is outside the file.");+ ValidateVideo(file, start, videoLength);+ return (start, videoLength);+ }+ }+ else+ file.Position += length;+ }+ return null;+ }++ /// <summary>Requires a real ISO media header at the declared boundary, not stale XMP left by an image editor.</summary>+ public static void ValidateVideo(Stream file, long start, long length)+ {+ file.Position = start;+ var box = MovieBoxes.ReadHeader(file);+ if (box.Type != "ftyp" || box.Length < 16 || box.Length > length)+ throw new InvalidDataException("The image no longer contains its declared Motion Photo video.");+ }+}diff --git a/src/Filee.Engines/Media/MovieBoxes.cs b/src/Filee.Engines/Media/MovieBoxes.csnew file mode 100644index 00000000..891f457a--- /dev/null+++ b/src/Filee.Engines/Media/MovieBoxes.cs@@ -0,0 +1,83 @@+// Small, bounds-checked ISO BMFF box helpers for photo metadata; media payloads are streamed, never loaded whole.++using System.Buffers.Binary;+using System.Text;++namespace Filee.Engines.Media;++internal readonly record struct MovieBox(string Type, long Start, long Length, int HeaderLength)+{+ public long End => checked(Start + Length);+}++internal static class MovieBoxes+{+ public static MovieBox ReadHeader(Stream file)+ {+ var start = file.Position;+ Span<byte> header = stackalloc byte[8];+ file.ReadExactly(header);+ long size = BinaryPrimitives.ReadUInt32BigEndian(header);+ var type = Encoding.Latin1.GetString(header[4..]);+ var headerLength = 8;+ if (size == 1)+ {+ file.ReadExactly(header);+ var extended = BinaryPrimitives.ReadUInt64BigEndian(header);+ if (extended > long.MaxValue)+ throw new InvalidDataException("Media box is too large.");+ size = (long)extended;+ headerLength = 16;+ }+ else if (size == 0)+ size = file.Length - start;+ if (size < headerLength || size > file.Length - start)+ throw new InvalidDataException("Media box extends outside its container.");+ return new(type, start, size, headerLength);+ }++ public static List<(string Type, byte[] Payload)> Children(byte[] data, int skip = 0)+ {+ using var stream = new MemoryStream(data);+ stream.Position = skip;+ var result = new List<(string, byte[])>();+ while (stream.Position < stream.Length)+ {+ var box = ReadHeader(stream);+ var payload = new byte[checked((int)(box.Length - box.HeaderLength))];+ stream.ReadExactly(payload);+ result.Add((box.Type, payload));+ }+ return result;+ }++ public static byte[] Box(string type, params byte[][] parts)+ {+ using var file = new MemoryStream();+ file.Write(U32(checked((uint)(8L + parts.Sum(p => (long)p.Length)))));+ file.Write(Encoding.Latin1.GetBytes(type));+ foreach (var part in parts)+ file.Write(part);+ return file.ToArray();+ }++ public static byte[] Full(string type, byte[] payload, uint flags = 0) => Box(type, U32(flags), payload);+ public static byte[] U16(ushort value) { var data = new byte[2]; BinaryPrimitives.WriteUInt16BigEndian(data, value); return data; }+ public static byte[] U32(uint value) { var data = new byte[4]; BinaryPrimitives.WriteUInt32BigEndian(data, value); return data; }+ public static byte[] U64(ulong value) { var data = new byte[8]; BinaryPrimitives.WriteUInt64BigEndian(data, value); return data; }+ public static byte[] Utf8(string text) => Encoding.UTF8.GetBytes(text);+ public static byte[] Join(params byte[][] parts) => parts.SelectMany(p => p).ToArray();++ public static async Task CopyRangeAsync(Stream source, Stream target, long count, CancellationToken ct)+ {+ var buffer = new byte[81920];+ while (count > 0)+ {+ var read = await source.ReadAsync(buffer.AsMemory(0, (int)Math.Min(count, buffer.Length)), ct);+ if (read == 0)+ throw new EndOfStreamException();+ await target.WriteAsync(buffer.AsMemory(0, read), ct);+ count -= read;+ }+ }+}diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.csindex ee9ed7db..c22725b4 100644--- a/tests/Filee.App.Tests/RenderTests.cs+++ b/tests/Filee.App.Tests/RenderTests.cs@@ -1305,6 +1305,47 @@ public class RenderTestsnotice.Close();}+ [AvaloniaTheory]+ [InlineData("en", "livp")]+ [InlineData("en", "motionphoto")]+ [InlineData("zh-CN", "livp")]+ [InlineData("zh-CN", "motionphoto")]+ [InlineData("en", "mp4")]+ [InlineData("zh-CN", "mp4")]+ public void Live_photo_editor_renders_and_saves_clip_and_extraction_options(string language, string target)+ {+ TestServices.EnsureInitialized(language);+ var preset = Filee.Core.Presets.BuiltInData.LivePhotoPresets().Single(p => p.TargetFormat == target);+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());+ Assert.True(vm.ShowMedia);+ Assert.Equal(target != "mp4", vm.ShowLivePhoto);+ Assert.Equal(target == "mp4", vm.ShowExtractMotionPhoto);+ if (vm.ShowLivePhoto)+ {+ Assert.False(vm.ShowImage);+ Assert.False(vm.ShowPdf);+ }+ vm.LivePhotoStart = 2;+ vm.LivePhotoDuration = 2.5;+ vm.LivePhotoCover = 0.8;+ vm.ExtractMotionPhoto = true;+ var window = new PresetEditorWindow { DataContext = vm, Height = 980 };+ window.Show();+ Pump();+ Save(window, $"preset-livephoto-{target}-{language}.png");+ window.Close();+ Assert.True(vm.Apply());+ Assert.Equal(2, preset.Media.LivePhotoStart);+ Assert.Equal(2.5, preset.Media.LivePhotoDuration);+ Assert.Equal(0.8, preset.Media.LivePhotoCover);+ Assert.Equal(target == "mp4", preset.Media.ExtractMotionPhoto);+ var restored = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());+ Assert.Equal(2.5, restored.LivePhotoDuration);+ restored.Target = restored.Targets.Single(t => t.Value == "png");+ Assert.True(restored.Apply());+ Assert.False(preset.Media.ExtractMotionPhoto);+ }+private static void Pump(){// Let layout, bindings and a few animation frames run.diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex 8939d56b..04aa078b 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -6,6 +6,33 @@ namespace Filee.Core.Tests;public class UserDataStoreTests{+ [Fact]+ public void Version_20_library_gains_live_photo_presets_once_and_keeps_customizations()+ {+ using var dir = new TempDir();+ var store = new UserDataStore(dir.Path);+ store.Load();+ var ids = BuiltInData.LivePhotoPresets().Select(p => p.Id).ToHashSet();+ store.Presets.RemoveAll(p => ids.Contains(p.Id));+ store.Presets.Add(new Preset { Id = "to-livp", Name = "My live photo", TargetFormat = "livp", Media = { LivePhotoDuration = 2.4 } });+ store.FindPreset("to-mp4")!.Media.LivePhotoStart = 7;+ store.Settings.SchemaVersion = 20;+ store.SaveSettings();+ store.SaveLibrary();+ var reloaded = new UserDataStore(dir.Path);+ reloaded.Load();+ foreach (var id in ids)+ Assert.Single(reloaded.Presets, p => p.Id == id);+ Assert.Equal("My live photo", reloaded.FindPreset("to-livp")!.Name);+ Assert.Equal(2.4, reloaded.FindPreset("to-livp")!.Media.LivePhotoDuration);+ Assert.Equal(7, reloaded.FindPreset("to-mp4")!.Media.LivePhotoStart);+ Assert.True(reloaded.FindPreset("extract-motion")!.Media.ExtractMotionPhoto);+ Assert.DoesNotContain(reloaded.Profiles, p => p.PresetIds.Any(ids.Contains));+ reloaded.Load();+ foreach (var id in ids)+ Assert.Single(reloaded.Presets, p => p.Id == id);+ }+[Fact]public void Groups_keep_only_conversions_once_and_at_most_six(){diff --git a/tests/Filee.Engines.Tests/LivePhotoTests.cs b/tests/Filee.Engines.Tests/LivePhotoTests.csnew file mode 100644index 00000000..7d5f8b29--- /dev/null+++ b/tests/Filee.Engines.Tests/LivePhotoTests.cs@@ -0,0 +1,262 @@+// Generated video/photo fixtures: real bidirectional conversions and independent ffprobe checks of Apple timing.++using System.Globalization;+using System.IO.Compression;+using System.Text;+using System.Text.Json;+using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Core.Presets;+using Filee.Engines.Infrastructure;+using Filee.Engines.Media;+using ImageMagick;++namespace Filee.Engines.Tests;++[Collection(nameof(FfmpegCollection))]+public class LivePhotoTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ private static (string Ffmpeg, string Ffprobe) Tools()+ {+ var tools = FfmpegConverter.Locate();+ Assert.SkipUnless(tools is not null, "FFmpeg is not installed.");+ return tools.Value;+ }++ private async Task<string> VideoAsync(bool audio = true)+ {+ var tools = Tools();+ var input = Path.Combine(fx.NewFolder(), "clip ü 中文.mp4");+ var result = await FfmpegRunner.RunAsync(tools.Ffmpeg, [+ .. MediaEncoding.Common, "-f", "lavfi", "-i", "testsrc2=size=160x120:rate=30",+ .. (audio ? new[] { "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000" } : []),+ "-t", "2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", input,+ ], null, TestContext.Current.CancellationToken);+ Assert.True(result.ExitCode == 0, result.StandardError);+ return input;+ }++ private static string Output(ConversionJob job)+ {+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey}: {f.ErrorDetail}")));+ return Assert.Single(job.Outputs);+ }++ [Theory]+ [InlineData("livp", true)]+ [InlineData("livp", false)]+ [InlineData("motionphoto", true)]+ [InlineData("motionphoto", false)]+ public async Task Video_to_photo_and_back_preserves_motion_audio_and_source(string format, bool audio)+ {+ var tools = Tools();+ var input = await VideoAsync(audio);+ var original = await File.ReadAllBytesAsync(input, TestContext.Current.CancellationToken);+ var photoJob = await fx.ConvertAsync([input], new Preset+ {+ TargetFormat = format,+ Media = { LivePhotoStart = 0.2, LivePhotoDuration = 1.2, LivePhotoCover = 0.4 },+ });+ var photo = Output(photoJob);+ Assert.Equal(format, FormatRegistry.Detect(photo)!.Id);+ Assert.NotNull(photoJob.Files.Single().NoticeKey);+ var movie = Output(await fx.ConvertAsync([photo], new Preset { TargetFormat = "mp4" }));+ var info = await MediaInfo.ProbeAsync(tools.Ffprobe, movie, TestContext.Current.CancellationToken);+ Assert.NotNull(info.Video);+ Assert.Equal(audio, info.Audio is not null);+ Assert.InRange(info.Duration!.Value.TotalSeconds, 1.1, 1.35);+ Assert.Equal(original, await File.ReadAllBytesAsync(input, TestContext.Current.CancellationToken));++ if (format == "motionphoto")+ {+ using var still = new MagickImage(photo);+ Assert.Equal(160u, still.Width);+ var xmp = Encoding.UTF8.GetString(still.GetXmpProfile()!.ToByteArray());+ Assert.Contains("MotionPhotoPresentationTimestampUs=\"400000\"", xmp);+ }+ else+ {+ var folder = fx.NewFolder();+ ZipFile.ExtractToDirectory(photo, folder);+ var jpg = Directory.GetFiles(folder, "*.jpg").Single();+ var mov = Directory.GetFiles(folder, "*.mov").Single();+ var id = AppleLivePhoto.ImageIdentifier(jpg);+ Assert.NotNull(id);+ Assert.Equal(id, AppleLivePhoto.MovieIdentifier(mov));+ // The extractor must also accept camera-style adjacent files, without requiring a LIVP archive.+ Output(await fx.ConvertAsync([jpg], new Preset { TargetFormat = "mov", Media = { ExtractMotionPhoto = true } }));+ var probe = await ProcessRunner.RunAsync(tools.Ffprobe,+ ["-v", "error", "-select_streams", "d", "-show_streams", "-show_packets", "-of", "json", mov],+ TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken);+ Assert.True(probe.ExitCode == 0, probe.StandardError);+ using var json = JsonDocument.Parse(probe.StandardOutput);+ var stream = Assert.Single(json.RootElement.GetProperty("streams").EnumerateArray());+ Assert.Equal("mebx", stream.GetProperty("codec_tag_string").GetString());+ var packet = Assert.Single(json.RootElement.GetProperty("packets").EnumerateArray());+ Assert.InRange(double.Parse(packet.GetProperty("pts_time").GetString()!, CultureInfo.InvariantCulture), 0.399, 0.401);+ // Same names are insufficient: an unrelated movie must not be paired with the still.+ File.Copy(input, mov, overwrite: true);+ var badPair = await fx.ConvertAsync([jpg], new Preset { TargetFormat = "mp4", Media = { ExtractMotionPhoto = true } });+ Assert.NotEqual(JobState.Completed, badPair.State);+ }+ }++ [Fact]+ public async Task A_renamed_android_photo_still_extracts_and_plain_jpg_does_not_silently_become_motion()+ {+ var input = await VideoAsync();+ var photo = Output(await fx.ConvertAsync([input], new Preset { TargetFormat = "motionphoto" }));+ var renamed = Path.Combine(fx.NewFolder(), "camera.JPG");+ File.Copy(photo, renamed);+ Output(await fx.ConvertAsync([renamed], new Preset { TargetFormat = "mp4", Media = { ExtractMotionPhoto = true } }));+ var plain = EngineFixture.MakeImage(fx.NewFolder(), "plain.jpg", MagickFormat.Jpeg);+ var failed = await fx.ConvertAsync([plain], new Preset { TargetFormat = "mp4", Media = { ExtractMotionPhoto = true } });+ Assert.Equal("error.no_motion_photo", failed.Files.Single().ErrorKey);+ var png = EngineFixture.MakeImage(fx.NewFolder(), "plain.png", MagickFormat.Png);+ var unsupported = await fx.ConvertAsync([png], new Preset { TargetFormat = "mp4", Media = { ExtractMotionPhoto = true } });+ Assert.Equal("error.no_route", unsupported.Files.Single().ErrorKey);+ Output(await fx.ConvertAsync([plain], new Preset { TargetFormat = "mp4" }));+ }++ [Theory]+ [InlineData("livp")]+ [InlineData("motionphoto")]+ public async Task Silent_output_and_end_of_source_cover_are_valid(string format)+ {+ var input = await VideoAsync();+ var photo = Output(await fx.ConvertAsync([input], new Preset+ {+ TargetFormat = format,+ Media = { LivePhotoStart = 1.7, LivePhotoDuration = 3, LivePhotoCover = 9, RemoveAudio = true },+ }));+ var movie = Output(await fx.ConvertAsync([photo], new Preset { TargetFormat = "mp4" }));+ var info = await MediaInfo.ProbeAsync(Tools().Ffprobe, movie, TestContext.Current.CancellationToken);+ Assert.Null(info.Audio);+ Assert.InRange(info.Duration!.Value.TotalSeconds, 0.25, 0.4);+ }++ [Fact]+ public void Photo_edges_are_direct_and_existing_routes_stay_still_images()+ {+ var planner = fx.Catalog.CreatePlanner(["ffmpeg"]);+ Assert.Single(planner.Plan("mp4", "livp")!.Steps);+ Assert.Single(planner.Plan("mov", "motionphoto")!.Steps);+ Assert.Null(planner.Plan("jpg", "livp"));+ Assert.Null(planner.Plan("livp", "gif"));+ Assert.Null(planner.Plan("wav", "motionphoto"));+ Assert.Null(planner.Plan("png", "mp4", motionPhoto: true));+ Assert.Equal(2, planner.Plan("jpg", "mp4")!.Steps.Count);+ Assert.Single(planner.Plan("jpg", "mp4", motionPhoto: true)!.Steps);+ Assert.Equal("camera", FormatRegistry.NameWithoutExtension("camera.motion.jpg"));+ }++ [Theory]+ [InlineData("livp")]+ [InlineData("motionphoto")]+ public async Task Existing_outputs_obey_overwrite_and_skip(string format)+ {+ var input = await VideoAsync();+ var preset = new Preset { TargetFormat = format, Output = { Conflict = ConflictPolicy.Overwrite } };+ var first = Output(await fx.ConvertAsync([input], preset));+ var second = Output(await fx.ConvertAsync([input], preset));+ Assert.Equal(first, second);+ if (format == "livp")+ {+ using var zip = ZipFile.OpenRead(second);+ Assert.Equal(2, zip.Entries.Count);+ }+ preset.Output.Conflict = ConflictPolicy.Skip;+ var skipped = await fx.ConvertAsync([input], preset);+ Assert.Empty(skipped.Outputs);+ Assert.Equal(FileState.Skipped, skipped.Files.Single().State);+ }++ [Fact]+ public async Task Archive_names_never_escape_the_private_work_directory()+ {+ var input = await VideoAsync();+ var original = Output(await fx.ConvertAsync([input], new Preset { TargetFormat = "livp" }));+ var malicious = Path.Combine(fx.NewFolder(), "traversal.livp");+ using (var source = ZipFile.OpenRead(original))+ using (var target = ZipFile.Open(malicious, ZipArchiveMode.Create))+ {+ foreach (var item in source.Entries)+ {+ await using var reader = item.Open();+ await using var writer = target.CreateEntry("../../outside/" + item.Name).Open();+ await reader.CopyToAsync(writer, TestContext.Current.CancellationToken);+ }+ }+ var work = fx.NewFolder();+ var extracted = await LivePhotoSource.ExtractAsync(malicious, work, TestContext.Current.CancellationToken);+ Assert.Equal(work, Path.GetDirectoryName(extracted));+ Assert.Equal(2, Directory.GetFiles(work).Length);+ Assert.False(Directory.Exists(Path.Combine(fx.Root, "outside")));+ }++ [Theory]+ [InlineData(-1, 3, 1)]+ [InlineData(0, 0, 1)]+ [InlineData(0, 11, 1)]+ [InlineData(9, 3, 1)]+ [InlineData(0, 3, -1)]+ [InlineData(double.NaN, 3, 1)]+ public void Invalid_clips_fail_before_writing(double start, double duration, double cover) =>+ Assert.Throws<ConversionRefusedException>(() => LivePhotoConversion.Clip(new MediaOptions+ {+ LivePhotoStart = start,+ LivePhotoDuration = duration,+ LivePhotoCover = cover,+ }, 5));++ [Fact]+ public async Task Missing_mismatched_and_multiple_archive_pairs_are_rejected()+ {+ var input = await VideoAsync();+ var photo = Output(await fx.ConvertAsync([input], new Preset { TargetFormat = "livp" }));+ using (var zip = ZipFile.Open(photo, ZipArchiveMode.Update))+ zip.CreateEntry("other.mov");+ await Assert.ThrowsAsync<InvalidDataException>(() => LivePhotoSource.ExtractAsync(photo, fx.NewFolder(), TestContext.Current.CancellationToken));+ var empty = Path.Combine(fx.NewFolder(), "empty.livp");+ using (var zip = ZipFile.Open(empty, ZipArchiveMode.Create))+ zip.CreateEntry("../../escape.mov");+ await Assert.ThrowsAsync<InvalidDataException>(() => LivePhotoSource.ExtractAsync(empty, fx.NewFolder(), TestContext.Current.CancellationToken));+ }++ [Fact]+ public async Task Xmp_is_namespace_aware_and_stale_or_hostile_metadata_is_rejected()+ {+ var jpeg = EngineFixture.MakeImage(fx.NewFolder(), "still.jpg", MagickFormat.Jpeg);+ var video = MovieBoxes.Box("ftyp", "isom\0\0\0\0isom"u8.ToArray());+ var length = video.Length;+ var xmp = $"<x:xmpmeta xmlns:x='adobe:ns:meta/' xmlns:c='http://ns.google.com/photos/1.0/camera/' c:MicroVideo='1' c:MicroVideoOffset='{length}'/>";+ using var legacy = new MemoryStream(JpegWithXmp(await File.ReadAllBytesAsync(jpeg, TestContext.Current.CancellationToken), xmp).Concat(video).ToArray());+ var found = MotionPhoto.FindVideo(legacy);+ Assert.Equal(length, found!.Value.Length);+ using var stale = new MemoryStream(JpegWithXmp(await File.ReadAllBytesAsync(jpeg, TestContext.Current.CancellationToken), xmp));+ Assert.Throws<InvalidDataException>(() => MotionPhoto.FindVideo(stale));+ using var disabled = new MemoryStream(JpegWithXmp(await File.ReadAllBytesAsync(jpeg, TestContext.Current.CancellationToken), xmp.Replace("c:MicroVideo='1'", "c:MotionPhoto='0' c:MicroVideo='1'")).Concat(video).ToArray());+ Assert.Null(MotionPhoto.FindVideo(disabled));+ using var hostile = new MemoryStream(JpegWithXmp(await File.ReadAllBytesAsync(jpeg, TestContext.Current.CancellationToken), "<!DOCTYPE x [<!ENTITY leak SYSTEM 'file:///secret'>]><x>&leak;</x>"));+ Assert.Throws<System.Xml.XmlException>(() => MotionPhoto.FindVideo(hostile));+ }++ private static byte[] JpegWithXmp(byte[] jpeg, string xml)+ {+ var payload = Encoding.UTF8.GetBytes("http://ns.adobe.com/xap/1.0/\0" + xml);+ return [0xff, 0xd8, 0xff, 0xe1, .. MovieBoxes.U16((ushort)(payload.Length + 2)), .. payload, .. jpeg.Skip(2)];+ }++ [Fact]+ public void Invalid_and_extended_media_boxes_are_bounded()+ {+ using var beyond = new MemoryStream([.. MovieBoxes.U32(100), .. "mpvd"u8.ToArray()]);+ Assert.Throws<InvalidDataException>(() => MotionPhoto.FindVideo(beyond));+ using var huge = new MemoryStream([.. MovieBoxes.U32(1), .. "mpvd"u8.ToArray(), .. MovieBoxes.U64(ulong.MaxValue)]);+ Assert.Throws<InvalidDataException>(() => MotionPhoto.FindVideo(huge));+ using var heic = new MemoryStream([.. MovieBoxes.Box("ftyp", "heic\0\0\0\0heic"u8.ToArray()), .. MovieBoxes.Box("mpvd", MovieBoxes.Box("ftyp", "isom\0\0\0\0isom"u8.ToArray()))]);+ var video = MotionPhoto.FindVideo(heic);+ Assert.NotNull(video);+ MotionPhoto.ValidateVideo(heic, video.Value.Offset, video.Value.Length);+ }+}