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.

Live/Motion Photos: keep only the video extraction for 2.0.0

KnifeLemonc50c7e1c5922
diff --git a/README.ko.md b/README.ko.md
index 43f3f9d5..b4c09f8e 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -34,7 +34,7 @@
<table>
<tr>
<td width="33%" valign="top"><b>커서 바로 옆에서</b><br>앱 창을 열 필요가 없어요. 끌고 있는 파일에 맞는 형식만 지금 있는 자리에 나타나요.</td>
- <td width="33%" valign="top"><b>248가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td>
+ <td width="33%" valign="top"><b>249가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td>
<td width="33%" valign="top"><b>내 컴퓨터 안에서만</b><br>아무것도 업로드하지 않아요. 오프라인으로 동작하고 결과는 원본 옆에 저장해요.</td>
</tr>
</table>
@@ -86,7 +86,7 @@
| 원본 | 변환 대상 |
|---|---|
-| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR 등; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등), DICOM, OpenEXR, HDR, JPEG XR(Windows)은 읽기 | 위 형식끼리(HEIC⁵), PDF, SVG(벡터화), 크기 조정, 흑백 |
+| **이미지**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR 등; GIMP XCF, 카메라 RAW(CR2, CR3, NEF, ARW, DNG 등), DICOM, OpenEXR, HDR, JPEG XR(Windows), 아이폰 라이브 포토(LIVP)는 읽기 | 위 형식끼리(HEIC⁵), PDF, SVG(벡터화), 크기 조정, 흑백; 라이브/모션 포토(아이폰, 안드로이드) → 그 동영상(MP4, MOV⁵) |
| **벡터**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG, FODG² | PDF(벡터), PNG 등 이미지, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS¹, SVG → EMF, WMF, ODG² |
| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX(페이지마다 그림 한 장), SVG²; 합치기, 나누기, 페이지 범위, 압축 (더 작은 PDF) |
| **문서**: DOCX, DOCM, DOTX, EML, Outlook MSG · DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602 등² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML · ODT, FODT, OTT² |
diff --git a/README.md b/README.md
index cb6e454d..0c85b11d 100644
--- a/README.md
+++ b/README.md
@@ -34,7 +34,7 @@
<table>
<tr>
<td width="33%" valign="top"><b>Right at your cursor</b><br>No app window to open. The formats appear where you already are, only the ones that make sense for the files you drag.</td>
- <td width="33%" valign="top"><b>248 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td>
+ <td width="33%" valign="top"><b>249 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td>
<td width="33%" valign="top"><b>Stays on your computer</b><br>Nothing is uploaded. Filee works offline and saves the result next to the original.</td>
</tr>
</table>
@@ -86,7 +86,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a
| From | To |
|---|---|
-| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR, JPEG XR (Windows) read | any of these (HEIC⁵), PDF, SVG (traced), resized, grayscale |
+| **Images**: JPG, PNG, WEBP, AVIF, TIFF, BMP, GIF, APNG, ICO, ICNS, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, HEIC, QOI, DDS, PCX, MNG, CUR, …; GIMP XCF, camera RAW (CR2, CR3, NEF, ARW, DNG, …), DICOM, OpenEXR, HDR, JPEG XR (Windows), iPhone Live Photo (LIVP) read | any of these (HEIC⁵), PDF, SVG (traced), resized, grayscale; Live/Motion Photos (iPhone, Android) → their video (MP4, MOV⁵) |
| **Vector**: SVG, SVGZ, EMF, WMF, AI · EPS, PS¹ · CDR, VSD, CGM, ODG, FODG² | PDF (vector), PNG and other images, SVG ↔ SVGZ, SVG → DXF/DWG, PDF → EPS/PS¹, SVG → EMF, WMF, ODG² |
| **PDF** | DOCX, HWPX, TXT, PNG, JPG, TIFF, CBZ, PPTX (a picture of each page), SVG²; merge, split, page ranges, compress (smaller PDFs) |
| **Documents**: DOCX, DOCM, DOTX, EML, Outlook MSG · DOC, ODT, FODT, OTT, RTF, WPS, WPD, Pages, ClarisWorks, MacWrite, T602, …² | PDF, DOCX, HWPX, EPUB, TXT, HTML; MSG → EML · ODT, FODT, OTT² |
@@ -108,9 +108,6 @@ Unmarked formats work out of the box, without Office, Hancom Office or LibreOffi
Marked 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 line
The `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.md
index f016191b..98dfbb65 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -34,7 +34,7 @@
<table>
<tr>
<td width="33%" valign="top"><b>就在光标旁</b><br>无需打开应用窗口。只显示适合当前拖动文件的格式,就在你所在的位置。</td>
- <td width="33%" valign="top"><b>248 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td>
+ <td width="33%" valign="top"><b>249 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td>
<td width="33%" valign="top"><b>只在你的电脑上</b><br>不上传任何文件。Filee 离线工作,结果保存在原文件旁边。</td>
</tr>
</table>
@@ -85,7 +85,7 @@
| 源格式 | 目标格式 |
|---|---|
-| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、APNG、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC、QOI、DDS、PCX、MNG、CUR 等;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)、DICOM、OpenEXR、HDR、JPEG XR(Windows)仅读取 | 上述格式互转(HEIC⁵)、PDF、SVG(描摹)、缩放、灰度 |
+| **图片**:JPG、PNG、WEBP、AVIF、TIFF、BMP、GIF、APNG、ICO、ICNS、JPEG XL、JPEG 2000、PSD/PSB、TGA、PPM、HEIC、QOI、DDS、PCX、MNG、CUR 等;GIMP XCF、相机 RAW(CR2、CR3、NEF、ARW、DNG 等)、DICOM、OpenEXR、HDR、JPEG XR(Windows)、iPhone 实况照片(LIVP)仅读取 | 上述格式互转(HEIC⁵)、PDF、SVG(描摹)、缩放、灰度;实况/动态照片(iPhone、安卓)→ 其中的视频(MP4、MOV⁵) |
| **矢量图**:SVG、SVGZ、EMF、WMF、AI · EPS、PS¹ · CDR、VSD、CGM、ODG、FODG² | PDF(矢量)、PNG 等图片、SVG ↔ SVGZ、SVG → DXF/DWG、PDF → EPS/PS¹、SVG → EMF、WMF、ODG² |
| **PDF** | DOCX、HWPX、TXT、PNG、JPG、TIFF、CBZ、PPTX(每页一张图片)、SVG²;合并、拆分、页码范围、压缩(更小的 PDF) |
| **文档**:DOCX、DOCM、DOTX、EML、Outlook MSG · DOC、ODT、FODT、OTT、RTF、WPS、WPD、Pages、ClarisWorks、MacWrite、T602 等² | PDF、DOCX、HWPX、EPUB、TXT、HTML、MSG → EML · ODT、FODT、OTT² |
@@ -107,9 +107,6 @@
标注的格式需要可选引擎,只在需要时下载,分别是 ¹ 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.md
index 80f850c5..7fe59a1b 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -5,7 +5,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| Engine | How it gets there | Handles |
|---|---|---|
-| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, MNG, QOI, DDS, PCX, CUR, XPM, XBM, WBMP, PAM, PFM, SGI, Sun Raster, MIFF ↔ each other, and **APNG** (Filee's own reader and writer); HEIC (written with FFmpeg), XCF, camera RAW (LibRaw), DICOM (uncompressed ones by Filee's own reader), Photo CD, OpenEXR, Radiance HDR and EMF/WMF (Windows) read |
+| ImageMagick (Magick.NET) | built in (library) | JPG, PNG, WEBP, TIFF, BMP, GIF, ICO, AVIF, JPEG XL, JPEG 2000, PSD/PSB, TGA, PPM, MNG, QOI, DDS, PCX, CUR, XPM, XBM, WBMP, PAM, PFM, SGI, Sun Raster, MIFF ↔ each other, and **APNG** (Filee's own reader and writer); HEIC (written with FFmpeg), XCF, camera RAW (LibRaw), DICOM (uncompressed ones by Filee's own reader), Photo CD, OpenEXR, Radiance HDR, EMF/WMF (Windows) and the photo of an iPhone LIVP read |
| Windows Imaging Component | part of Windows (Windows only) | **JPEG XR** (JXR, WDP, HDP; HDR screenshots of Windows) → the images ImageMagick writes, and PDF, ICNS, HEIC and SVG through PNG; HDR tone-mapped to SDR |
| Vector graphics | built in (Svg.Skia, SkiaSharp, ACadSharp) | **SVG/SVGZ → PDF (vector) and images**, SVG ↔ SVGZ, **SVG → DXF** (→ DWG with the CAD engine), **raster images → SVG (tracing)**, PDF-compatible AI → PDF |
| ICNS | built in | images → ICNS (16–1024 px), ICNS → images |
@@ -31,7 +31,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,
| LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG |
| Pandoc | **optional download** (~42 MB, 240 MB on disk) | Markdown ↔ DOCX/ODT/RTF, DOCX/ODT/HTML/RTF → Markdown, HTML ↔ DOCX/ODT, markup languages (reStructuredText, LaTeX, Org, AsciiDoc, Typst, MediaWiki, DocBook, Jupyter, Textile, man, OPML) ↔ Markdown/HTML/DOCX/ODT and each other (and → RTF, EPUB, TXT), Markdown and markup → PPTX slides |
| Ghostscript | **optional download** (~20 MB, 31 MB on disk) | EPS/PS → PDF, PDF → EPS/PS, PostScript-based AI → PDF (images through PDF and PDFium); smaller PDFs when a preset asks for it |
-| FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video (H.264, HEVC, AV1), video → animated GIF / APNG, a still frame or every frame, audio and subtitle extraction, audio ↔ audio (also APE, WavPack, TTA, DSD, DTS, ALAC, …), GIF, APNG and photos → MP4/WEBM/MOV, images → HEIC |
+| FFmpeg | **optional download** (~100 MB, 272 MB on disk) | **all video and audio**: video ↔ video (H.264, HEVC, AV1), video → animated GIF / APNG, a still frame or every frame, audio and subtitle extraction, audio ↔ audio (also APE, WavPack, TTA, DSD, DTS, ALAC, …), GIF, APNG and photos → MP4/WEBM/MOV, Live / Motion Photos → their video, images → HEIC |
| Calibre | **optional download** (~216 MB, 660 MB on disk) | rare e-book formats: LIT, LRF, CHM, PDB, PML, RB, SNB, TCR, OEB → EPUB; EPUB → MOBI, AZW3, LIT, LRF, PDB, PML, RB, SNB, TCR; e-books → PDF (ranked above the HWPX writer, see below) |
DOCX, XLSX, XLS, ODS and PPTX → PDF need neither Microsoft Office nor LibreOffice: they are read in-process, written as HWPX
@@ -187,6 +187,9 @@ pinned source in `build/build-linux-native.py` like rhwp (PR #113 did this for S
without "maximize compatibility"). GIMP XCF layers are composited at their offsets with their blend modes; hidden
layers are left out. ImageMagick reads 8-bit XCF without zlib tile compression (GIMP 2.10+ "better but slower
compression" files give a clear error).
+- **LIVP** (an iPhone Live Photo as iCloud downloads it: a ZIP of the photo, HEIC or JPEG, and its MOV) is read as its
+ photo, taken out of the package in memory (`LivePhotoSource.ReadStill`, at most 64 MB); its video is FFmpeg's (see
+ Live / Motion Photos there).
- **Camera RAW** (DNG, CR2, CR3, NEF, ARW, …, and `.raw`) is decoded by LibRaw with the camera's white balance,
sRGB output and AHD demosaicing, then turned upright from the EXIF orientation.
- **EMF/WMF** are rendered through GDI+ (Windows only) at the preset's render DPI (at least 150), keeping their
@@ -1022,10 +1025,6 @@ 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 PNG
frame 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.
@@ -1144,6 +1143,29 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on
how many pictures a minute of 30 fps video gives at the chosen interval.
- The frames go into a hidden folder next to the output and are moved into place when FFmpeg has finished, so a
cancelled or failed run leaves no half-filled folder.
+- **Live / Motion Photos** (*Extract Live/Motion Photo video* on an MP4 or MOV preset, `MediaOptions.ExtractMotionPhoto`;
+ the preset "Extract Live Photo video", on no donut): the video saved with a phone photo becomes the output, with its
+ sound, instead of a video of the still picture.
+ - Routes: the motion edges (`ConversionEdge.MotionPhoto`, JPG, HEIC, AVIF and LIVP → MP4 and MOV,
+ `MediaOptions.MotionPhotoSources`) are taken only when `Preset.ExtractsMotionOf` the file, and then as the whole
+ route (`RoutePlanner.Plan(from, to, motionPhoto: true)`). A LIVP always gives its video; GIF, PNG, WebP and other
+ pictures ignore the option and become a video of the picture as below.
+ - Where the video is (`Media/MotionPhoto.cs`, `Media/LivePhotoSource.cs`), always from the photo's own metadata,
+ never by searching its bytes for an MP4 signature: Motion Photo 1.0 JPEGs (Pixel, Samsung, …) give the length of
+ the appended video in the XMP container directory (`GCamera:MotionPhoto`, the last `Container:Item`, attributes or
+ elements); older Google "MicroVideo" JPEGs an offset back from the end (`GCamera:MicroVideoOffset`); HEIC and AVIF
+ hold the video in a top-level `mpvd` box. The video must start with `ftyp` and hold a `moov`, else the metadata is
+ stale (an editor rewrote the picture) and nothing is guessed; it ends with its last whole box, which leaves
+ Samsung's SEF trailer out. An iPhone photo (JPG or HEIC) takes the MOV next to it with the same name, only when
+ both carry the same content identifier (tag 17 of Apple's maker note, `com.apple.quicktime.content.identifier`);
+ a LIVP (the ZIP iCloud downloads give) takes its one MOV, whose identifier is only checked for the log.
+ - The video is copied into the work directory (at most 512 MB; JPEG metadata is read only from the first 8 MB, XMP
+ without DTDs; LIVP entries are copied to names of Filee's own, never extracted by their names), converted there
+ like any video (copied as it is into MP4/MOV when its codecs fit) and moved into place when finished: a failed or
+ cancelled run never touches a file "overwrite" would replace, and the output never replaces the iPhone MOV it was
+ read from (IMG_0001.HEIC → `IMG_0001 (2).mov`). A photo without a video fails with "This photo has no video
+ Filee can read"; why goes to the log.
+ - Not read: vendor formats without this metadata (Huawei's "LIVE_" trailer, for one).
- Pictures → MP4/WEBM/MOV go through a full-size PNG from the image engines (HEIC → PNG → MOV): a 5-second still at
30 fps, one quality step above the preset (identical frames cost almost nothing; x264 `-tune stillimage`). The
PNG's ICC profile is read (`-flags2 +icc_profiles`), so primaries and transfer are tagged as the photo's (Display
diff --git a/docs/LIVE-PHOTOS.md b/docs/LIVE-PHOTOS.md
deleted file mode 100644
index df1c2b57..00000000
--- a/docs/LIVE-PHOTOS.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# 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.png
deleted file mode 100644
index 38e69c7c..00000000
Binary files a/docs/screenshots/preset-livephoto-livp-en.png and /dev/null differ
diff --git a/docs/screenshots/preset-livephoto-motionphoto-en.png b/docs/screenshots/preset-livephoto-motionphoto-en.png
deleted file mode 100644
index 0d7aa384..00000000
Binary files a/docs/screenshots/preset-livephoto-motionphoto-en.png and /dev/null differ
diff --git a/docs/screenshots/preset-livephoto-mp4-zh-CN.png b/docs/screenshots/preset-livephoto-mp4-zh-CN.png
deleted file mode 100644
index 0f0929cd..00000000
Binary files a/docs/screenshots/preset-livephoto-mp4-zh-CN.png and /dev/null differ
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 97371f35..9aabc372 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -1,18 +1,4 @@
{
- "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.",
@@ -91,6 +77,7 @@
"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.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.rhwp_timeout": "rhwp couldn't finish this long document in time",
"error.rhwp_timeout_calibre": "rhwp couldn't finish this long document in time. For an e-book, move Calibre above the HWPX writer in Settings → Engines, and Calibre makes the PDF much faster",
"error.needs_shaping": "This script needs LibreOffice to convert correctly. Install it in Settings → Engines",
@@ -185,6 +172,7 @@
"preset.trace_line_art": "Line art to SVG",
"preset.extract_frames_png": "Extract frames (PNG)",
"preset.extract_frames_jpg": "Extract frames (JPG)",
+ "preset.extract_motion": "Extract Live Photo video",
"format.folder": "Folder",
"format.category.Image": "Image",
@@ -432,6 +420,8 @@
"presets.save_every_frame_hint": "A video becomes a folder with a picture of each frame instead of one still frame.\nA long video gives many files.",
"presets.frame_interval": "Every Nth frame",
"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.ico_sizes": "Icon sizes",
"presets.group.pdf": "PDF",
"presets.merge": "Merge all files into one PDF",
diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.json
index 29ffe144..0723fe70 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -1,18 +1,4 @@
{
- "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",
@@ -85,6 +71,7 @@
"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.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.rhwp_timeout": "rhwp no pudo terminar este documento largo a tiempo",
"error.rhwp_timeout_calibre": "rhwp no pudo terminar este documento largo a tiempo. Para un libro electrónico, mueve Calibre por encima del escritor HWPX en Ajustes → Motores; Calibre genera el PDF mucho más rápido",
"error.needs_shaping": "Este sistema de escritura necesita LibreOffice para convertirse bien. Instálalo en Ajustes → Motores",
@@ -175,6 +162,7 @@
"preset.trace_line_art": "Líneas a SVG",
"preset.extract_frames_png": "Extraer fotogramas (PNG)",
"preset.extract_frames_jpg": "Extraer fotogramas (JPG)",
+ "preset.extract_motion": "Extraer vídeo de Live Photo",
"format.folder": "Carpeta",
"format.category.Image": "Imagen",
"format.category.Pdf": "PDF",
@@ -417,6 +405,8 @@
"presets.save_every_frame_hint": "El vídeo se convierte en una carpeta con una imagen por cada fotograma en lugar de una única imagen fija.\nUn vídeo largo generará muchos archivos.",
"presets.frame_interval": "Cada N fotogramas",
"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.ico_sizes": "Tamaños de icono",
"presets.group.pdf": "PDF",
"presets.merge": "Combinar todos los archivos en un PDF",
diff --git a/src/Filee.App/Assets/i18n/hi.json b/src/Filee.App/Assets/i18n/hi.json
index ff2b8f74..3093fce7 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -71,6 +71,7 @@
"error.cannot_turn": "घुमाना और पलटना केवल इमेज पर काम करता है",
"error.too_many_frames": "तस्वीरों के रूप में सहेजने के लिए बहुत ज़्यादा फ़्रेम हैं, \"हर Nवाँ फ़्रेम\" बढ़ाएँ",
"error.not_enough_space": "तस्वीरों के लिए डिस्क पर पर्याप्त खाली जगह नहीं है",
+ "error.no_motion_photo": "इस फ़ोटो में ऐसा कोई वीडियो नहीं है जिसे Filee पढ़ सके (Android मोशन फ़ोटो, या पास में अपनी MOV फ़ाइल वाली iPhone लाइव फ़ोटो)",
"error.rhwp_timeout": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका",
"error.rhwp_timeout_calibre": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका। ई-बुक के लिए, सेटिंग्स → इंजन में Calibre को HWPX writer के ऊपर ले जाएँ, तब Calibre PDF बहुत तेज़ी से बनाएगा",
"error.needs_shaping": "इस लिपि को सही ढंग से कन्वर्ट करने के लिए LibreOffice चाहिए। इसे सेटिंग्स → इंजन में इंस्टॉल करें",
@@ -161,6 +162,7 @@
"preset.trace_line_art": "लाइन आर्ट को SVG में",
"preset.extract_frames_png": "फ़्रेम निकालें (PNG)",
"preset.extract_frames_jpg": "फ़्रेम निकालें (JPG)",
+ "preset.extract_motion": "लाइव फ़ोटो वीडियो निकालें",
"format.folder": "फ़ोल्डर",
"format.category.Image": "इमेज",
"format.category.Pdf": "PDF",
@@ -403,6 +405,8 @@
"presets.save_every_frame_hint": "एक स्टिल फ़्रेम की जगह वीडियो एक फ़ोल्डर बन जाता है जिसमें हर फ़्रेम की तस्वीर होती है।\nलंबे वीडियो से बहुत सारी फ़ाइलें बनती हैं।",
"presets.frame_interval": "हर Nवाँ फ़्रेम",
"presets.frame_estimate": "30 fps के एक मिनट के वीडियो से {0} तस्वीरें बनती हैं, प्रति वीडियो अधिकतम {1}।",
+ "presets.extract_motion_photo": "लाइव/मोशन फ़ोटो का वीडियो निकालें",
+ "presets.extract_motion_photo_hint": "फ़ोटो उसके साथ सहेजा गया वीडियो बन जाती है: Android मोशन फ़ोटो के अंदर वाला वीडियो, या iPhone लाइव फ़ोटो के पास रखी उसी नाम की MOV फ़ाइल।\nबाकी तस्वीरें स्थिर तस्वीर का वीडियो बनती हैं।",
"presets.ico_sizes": "आइकन आकार",
"presets.group.pdf": "PDF",
"presets.merge": "सभी फ़ाइलों को एक PDF में मर्ज करें",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 214825e1..d6ab51db 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -1,18 +1,4 @@
{
- "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": "끌어서 놓으면, 변환 끝.",
@@ -91,6 +77,7 @@
"error.cannot_turn": "회전·반전은 이미지에만 할 수 있어요",
"error.too_many_frames": "프레임이 너무 많아요. 'N번째 프레임마다' 값을 늘려 주세요",
"error.not_enough_space": "이미지를 저장할 디스크 공간이 부족해요",
+ "error.no_motion_photo": "이 사진에서 읽을 수 있는 동영상을 찾지 못했어요 (안드로이드 모션 포토, 또는 옆에 MOV가 있는 아이폰 라이브 포토)",
"error.rhwp_timeout": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요",
"error.rhwp_timeout_calibre": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요. 전자책이라면 설정 → 변환 엔진에서 Calibre를 HWPX writer보다 위로 옮겨 주세요. Calibre가 PDF를 훨씬 빨리 만들어요",
"error.needs_shaping": "이 문자는 LibreOffice가 있어야 제대로 변환돼요. 설정 → 변환 엔진에서 설치해 주세요",
@@ -185,6 +172,7 @@
"preset.trace_line_art": "흑백 선화",
"preset.extract_frames_png": "프레임 추출 (PNG)",
"preset.extract_frames_jpg": "프레임 추출 (JPG)",
+ "preset.extract_motion": "라이브 포토 동영상 추출",
"format.folder": "폴더",
"format.category.Image": "이미지",
@@ -432,6 +420,8 @@
"presets.save_every_frame_hint": "동영상에서 정지 이미지 한 장 대신 프레임마다 이미지를 만들어 폴더 하나에 담아요.\n긴 동영상은 파일이 아주 많이 생겨요.",
"presets.frame_interval": "N번째 프레임마다",
"presets.frame_estimate": "30fps 동영상 1분이면 이미지 {0}장이 생겨요. 동영상 하나에 최대 {1}장까지예요.",
+ "presets.extract_motion_photo": "라이브/모션 포토 동영상 추출",
+ "presets.extract_motion_photo_hint": "사진과 함께 저장된 동영상을 꺼내요. 안드로이드 모션 포토는 사진 안의 동영상을, 아이폰 라이브 포토는 옆에 있는 같은 이름의 MOV를 써요.\n다른 이미지는 정지 화면 동영상이 돼요.",
"presets.ico_sizes": "아이콘 크기",
"presets.group.pdf": "PDF",
"presets.merge": "모든 파일을 하나의 PDF로 합치기",
diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.json
index f593356d..7098bbd8 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -1,18 +1,4 @@
{
- "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.",
@@ -91,6 +77,7 @@
"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.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.rhwp_timeout": "rhwp nie zdążył przetworzyć tego długiego dokumentu",
"error.rhwp_timeout_calibre": "rhwp nie zdążył przetworzyć tego długiego dokumentu. Dla e-booka przenieś Calibre nad HWPX writer w Ustawienia → Silniki, a Calibre zrobi PDF znacznie szybciej",
"error.needs_shaping": "To pismo wymaga LibreOffice do poprawnej konwersji. Zainstaluj go w Ustawienia → Silniki",
@@ -185,6 +172,7 @@
"preset.trace_line_art": "Rysunek do SVG",
"preset.extract_frames_png": "Wyodrębnij klatki (PNG)",
"preset.extract_frames_jpg": "Wyodrębnij klatki (JPG)",
+ "preset.extract_motion": "Wyodrębnij wideo z Live Photo",
"format.folder": "Folder",
"format.category.Image": "Obraz",
@@ -432,6 +420,8 @@
"presets.save_every_frame_hint": "Wideo staje się folderem z obrazem każdej klatki zamiast jednej klatki.\nDługie wideo daje wiele plików.",
"presets.frame_interval": "Co N-ta klatka",
"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.ico_sizes": "Rozmiary ikon",
"presets.group.pdf": "PDF",
"presets.merge": "Połącz wszystkie pliki w jeden PDF",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index e90b9971..d2979223 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -1,18 +1,4 @@
{
- "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": "拖一拖,放一放,转换完成。",
@@ -91,6 +77,7 @@
"error.cannot_turn": "只能旋转和翻转图片",
"error.too_many_frames": "帧数太多,请调大“每 N 帧”",
"error.not_enough_space": "磁盘空间不足,无法保存这些图片",
+ "error.no_motion_photo": "这张照片中没有可读取的视频(安卓动态照片,或旁边有 MOV 的 iPhone 实况照片)",
"error.rhwp_timeout": "文档太长,rhwp 未能在时限内完成",
"error.rhwp_timeout_calibre": "文档太长,rhwp 未能在时限内完成。如果是电子书,请在“设置 → 转换引擎”中把 Calibre 移到 HWPX writer 之上,Calibre 生成 PDF 要快得多",
"error.needs_shaping": "这种文字需要 LibreOffice 才能正确转换,请在“设置 → 转换引擎”中安装",
@@ -185,6 +172,7 @@
"preset.trace_line_art": "黑白描摹",
"preset.extract_frames_png": "提取帧 (PNG)",
"preset.extract_frames_jpg": "提取帧 (JPG)",
+ "preset.extract_motion": "提取实况/动态照片视频",
"format.folder": "文件夹",
"format.category.Image": "图片",
@@ -432,6 +420,8 @@
"presets.save_every_frame_hint": "视频的每一帧各保存为一张图片,放在一个文件夹中,而不是只保存一张静态图片。\n长视频会生成大量文件。",
"presets.frame_interval": "每 N 帧",
"presets.frame_estimate": "30 fps 的视频每分钟生成 {0} 张图片,每个视频最多 {1} 张。",
+ "presets.extract_motion_photo": "提取实况/动态照片中的视频",
+ "presets.extract_motion_photo_hint": "取出与照片一起保存的视频。安卓动态照片取其中内嵌的视频,iPhone 实况照片取旁边同名的 MOV。\n其他图片仍转换为静态画面的视频。",
"presets.ico_sizes": "图标尺寸",
"presets.group.pdf": "PDF",
"presets.merge": "将所有文件合并为一个 PDF",
diff --git a/src/Filee.App/ViewModels/FormatLabels.cs b/src/Filee.App/ViewModels/FormatLabels.cs
index 64a2963b..61f3b5c9 100644
--- a/src/Filee.App/ViewModels/FormatLabels.cs
+++ b/src/Filee.App/ViewModels/FormatLabels.cs
@@ -13,13 +13,7 @@ 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 switch
- {
- FormatRegistry.Folder => loc["format.folder"],
- "livp" => loc["format.livp"],
- "motionphoto" => loc["format.motionphoto"],
- _ => format.DisplayName,
- };
+ format.Id == FormatRegistry.Folder ? loc["format.folder"] : 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.cs
index 90aac1ec..16422018 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"] : FormatLabels.Name(loc, f),
+ f.Id == FormatRegistry.Folder ? loc["presets.target_folder"] : f.DisplayName,
FormatLabels.Category(loc, f.Category))),
];
ResizeModes = Enum.GetValues<ResizeMode>().Select(v => new Choice<ResizeMode>(v, loc[$"presets.resize.{v}"])).ToList();
@@ -121,11 +121,8 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_archiveLevel = ArchiveLevels.First(l => l.Value == _edit.Archive.Level);
_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;
+ _frameInterval = _edit.Media.FrameInterval > 0 ? _edit.Media.FrameInterval : 1;
_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);
@@ -202,8 +199,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(ShowLivePhoto), nameof(ShowExtractMotionPhoto), nameof(LivePhotoNotice))]
+ nameof(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace), nameof(ShowExtractMotionPhoto))]
private Choice<string> _target;
private VideoCodec _videoCodecValue;
@@ -351,9 +347,6 @@ public sealed partial class PresetEditorViewModel : ObservableObject
[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;
@@ -401,9 +394,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
|| (TargetIsAudio && !LosslessAudioTargets.Contains(TargetId) && MediaCodecs.Effective(TargetId, _audioCodecValue) != AudioCodec.Alac);
/// <summary>A tool (Crop) keeps the source as it is: none of the image options apply.</summary>
- public bool ShowImage => !IsTool && TargetIsImage && !ShowLivePhoto;
+ public bool ShowImage => !IsTool && TargetIsImage;
/// <summary>Images and PDFs (pictures placed on pages) can be turned and flipped.</summary>
- private bool CanTurn => (TargetIsImage && !ShowLivePhoto) || TargetId == "pdf";
+ private bool CanTurn => TargetIsImage || 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 => !IsTool && (TargetId == BuiltInData.SameAsSource || LossyTargets.Contains(TargetId));
@@ -412,7 +405,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public 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 => !IsTool && !ShowLivePhoto && TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font
+ public bool ShowPdf => !IsTool && TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font
or FormatCategory.Subtitle or FormatCategory.Data or FormatCategory.Model3D) && TargetId != "eml";
public bool ShowPdfBuild => TargetId == "pdf";
public bool ShowPdfSplit => TargetId == "pdf";
@@ -427,11 +420,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public 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 || 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"];
+ public bool ShowMedia => ShowMediaQuality || ShowMaxHeight || ShowRemoveAudio || ShowAudioChannels || ShowVideoCodec || ShowAudioCodec;
/// <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>
@@ -442,16 +431,18 @@ public sealed partial class PresetEditorViewModel : ObservableObject
public 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 || ShowLivePhoto;
- public bool ShowMaxHeight => TargetIsVideo || ShowLivePhoto;
- public bool ShowAudioBitrate => TargetIsLossyMedia || ShowLivePhoto;
- public bool ShowRemoveAudio => TargetIsVideo || ShowLivePhoto;
+ public bool ShowMediaQuality => TargetIsLossyMedia;
+ public bool ShowMaxHeight => TargetIsVideo;
+ public bool ShowAudioBitrate => TargetIsLossyMedia;
+ public bool ShowRemoveAudio => TargetIsVideo;
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>
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 && MediaOptions.FrameTargets.Contains(TargetId);
+ /// <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>
/// Playback speed: for the formats an animation stays animated in (an animated GIF, WebP, APNG or MNG, or a video
/// made into a GIF or APNG). Other targets get one frame.
@@ -546,9 +537,6 @@ public sealed partial class PresetEditorViewModel : ObservableObject
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.axaml
index b3013082..85a9589f 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -141,28 +141,8 @@
<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>
+ <CheckBox Content="{DynamicResource presets.extract_motion_photo}" IsChecked="{Binding ExtractMotionPhoto}"
+ IsVisible="{Binding ShowExtractMotionPhoto}" ToolTip.Tip="{DynamicResource presets.extract_motion_photo_hint}" />
<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.cs
index 009f728e..cbf34edc 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -38,7 +38,11 @@ namespace Filee.Core.Conversion;
/// needs shaping is never routed through the edge: <see cref="JobQueue"/> asks the engine
/// (<see cref="ITextShapingCheck"/>) and plans again without it.
/// </param>
-/// <param name="MotionPhoto">Only taken when explicitly extracting a camera image's motion; never a still-image route.</param>
+/// <param name="MotionPhoto">
+/// The edge takes the video out of a Live / Motion Photo (<see cref="Presets.MediaOptions.ExtractMotionPhoto"/>). It is
+/// never part of an ordinary route (a photo → MP4 is otherwise a video of the still picture), and with
+/// <see cref="RoutePlanner.Plan(string, string, bool, bool, bool)"/> asking for it it is the whole 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 Unshaped = false, bool MotionPhoto = false);
@@ -98,6 +102,10 @@ public interface IOutputAllocator
/// 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.
/// </param>
+/// <param name="MotionPhoto">
+/// The step takes a <see cref="ConversionEdge.MotionPhoto"/> edge: the video of the Live / Motion Photo becomes the
+/// output, not its still picture.
+/// </param>
public sealed record ConversionStep(
string InputPath,
string From,
@@ -106,7 +114,8 @@ public sealed record ConversionStep(
IOutputAllocator Output,
string WorkDirectory,
bool FrameSequence = false,
- Action<string>? Notice = null);
+ Action<string>? Notice = null,
+ bool MotionPhoto = false);
/// <summary>
/// A conversion engine (ImageMagick, LibreOffice, rhwp, ...).
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 247d6e3a..993afd39 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -369,8 +369,9 @@ public sealed class JobQueue : IAsyncDisposable
: job.Preset.TargetFormat == BuiltInData.SameAsSource ? source.Id
: job.Preset.TargetFormat;
- // "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).
+ // "Save every frame": a video becomes a folder of pictures in one step of its own; "Extract Live/Motion Photo
+ // video" likewise takes a photo's video. Never for an intermediate file, and never on the way to another format
+ // (video → JPG is otherwise one still frame, photo → MP4 a video of the still picture).
var frames = finalOutput && job.Preset.SavesFramesOf(source.Id);
var motionPhoto = finalOutput && job.Preset.ExtractsMotionOf(source.Id);
var route = planner.Plan(source.Id, target, frames, motionPhoto: motionPhoto);
@@ -437,7 +438,7 @@ public sealed class JobQueue : IAsyncDisposable
if (preset.Image.ChangesSpeed && !(isLast && finalOutput))
preset = AtOriginalSpeed(preset);
var stepInfo = new ConversionStep(input, step.From, step.To, preset, allocator, workDir, step.FrameSequence,
- key => file.NoticeKey = key);
+ key => file.NoticeKey = key, step.MotionPhoto);
outputs.AddRange(await step.Converter.ConvertAsync(stepInfo, progress, ct));
}
finally
diff --git a/src/Filee.Core/Conversion/RoutePlanner.cs b/src/Filee.Core/Conversion/RoutePlanner.cs
index 35bc8617..050c1a80 100644
--- a/src/Filee.Core/Conversion/RoutePlanner.cs
+++ b/src/Filee.Core/Conversion/RoutePlanner.cs
@@ -11,7 +11,8 @@ namespace Filee.Core.Conversion;
/// <summary>One hop of a route.</summary>
/// <param name="FrameSequence">The hop saves every frame of a video (<see cref="ConversionEdge.FrameSequence"/>).</param>
/// <param name="Unshaped">The hop draws text without complex-script shaping (<see cref="ConversionEdge.Unshaped"/>).</param>
-public sealed record RouteStep(IConverter Converter, string From, string To, bool FrameSequence = false, bool Unshaped = false);
+public sealed record RouteStep(IConverter Converter, string From, string To, bool FrameSequence = false, bool Unshaped = false,
+ bool MotionPhoto = false);
/// <summary>A planned conversion from one format to another.</summary>
public sealed record Route(IReadOnlyList<RouteStep> Steps, int Cost)
@@ -61,7 +62,10 @@ public sealed class RoutePlanner
/// <param name="shaping">
/// The source has text that needs complex-script shaping: <see cref="ConversionEdge.Unshaped"/> edges are left out.
/// </param>
- /// <param name="motionPhoto">Extract motion from a camera image through a dedicated direct edge.</param>
+ /// <param name="motionPhoto">
+ /// Take the video of a Live / Motion Photo (<see cref="Presets.Preset.ExtractsMotionOf"/>): the route is one
+ /// <see cref="ConversionEdge.MotionPhoto"/> edge, or none. Without it those edges are never taken.
+ /// </param>
public Route? Plan(string from, string to, bool frames = false, bool shaping = false, bool motionPhoto = false)
{
from = from.ToLowerInvariant();
@@ -69,13 +73,13 @@ public sealed class RoutePlanner
if (frames || motionPhoto)
{
- var sequence = EdgesFrom(from)
- .Where(e => e.Edge.FrameSequence == frames && e.Edge.MotionPhoto == motionPhoto && e.Edge.To == to)
+ var special = EdgesFrom(from)
+ .Where(e => e.Edge.To == to && (frames ? e.Edge.FrameSequence : e.Edge.MotionPhoto))
.OrderBy(e => e.Cost)
.FirstOrDefault();
- return sequence.Converter is null
+ return special.Converter is null
? null
- : new Route([new RouteStep(sequence.Converter, from, to, FrameSequence: frames)], sequence.Cost);
+ : new Route([new RouteStep(special.Converter, from, to, FrameSequence: frames, MotionPhoto: !frames)], special.Cost);
}
// Same-format "conversions" (re-encode, split, compress) must use an explicit self edge.
@@ -139,6 +143,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>
+ /// <param name="motionPhoto">The video of a Live / Motion Photo (see <see cref="Plan"/>).</param>
public bool CanConvert(string from, string to, bool frames = false, bool motionPhoto = false) =>
Plan(from, to, frames, motionPhoto: motionPhoto) is not null;
diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.cs
index ccd2a1cb..607f0d99 100644
--- a/src/Filee.Core/Formats/FormatRegistry.cs
+++ b/src/Filee.Core/Formats/FormatRegistry.cs
@@ -22,8 +22,6 @@ public static class FormatRegistry
new("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"]),
@@ -52,6 +50,8 @@ public static class FormatRegistry
// Read on Windows only, with its own codec (HDR screenshots of Windows are JPEG XR).
new("jxr", "JPEG XR", FormatCategory.Image, ["jxr", "wdp", "hdp"], Writable: false),
new("xcf", "XCF", FormatCategory.Image, ["xcf"], Writable: false),
+ // iPhone Live Photo as one ZIP (iCloud downloads): the photo, or its video with FFmpeg.
+ new("livp", "Live Photo (LIVP)", FormatCategory.Image, ["livp"], Writable: false),
new("raw", "RAW", FormatCategory.Image,
["dng", "cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "orf", "rw2", "raf", "pef", "dcr", "kdc",
"erf", "mos", "mrw", "x3f", "3fr", "fff", "iiq", "mef", "rwl", "srw", "raw"], Writable: false),
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index c80f9ca8..a341b232 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -73,7 +73,7 @@ public static class BuiltInData
.. PdfCompressionPresets(),
.. PdfSlidesPresets(),
.. FramePresets(),
- .. LivePhotoPresets(),
+ .. MotionPhotoPresets(),
new() { Id = "to-docx", Name = "DOCX", TargetFormat = "docx" },
new() { Id = "to-hwpx", Name = "HWPX", TargetFormat = "hwpx" },
.. HwpPresets(),
@@ -91,12 +91,11 @@ public static class BuiltInData
];
/// <summary>
- /// Live/Motion Photo conversions, added to the library but not to a user's existing donut.
+ /// The video of a Live / Motion Photo as MP4 (added in settings schema 29), on no donut: the images donut is full,
+ /// so users add it in Settings → Toolbar.
/// </summary>
- public static List<Preset> LivePhotoPresets() =>
+ public static List<Preset> MotionPhotoPresets() =>
[
- 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 } },
];
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 1bede141..7b95c13b 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -136,10 +136,16 @@ 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>
+ /// True if converting a <paramref name="sourceFormat"/> file takes the video of a Live / Motion Photo instead of a
+ /// video of the still picture: the target is one of <see cref="MediaOptions.MotionPhotoTargets"/> and the source one
+ /// of <see cref="MediaOptions.MotionPhotoSources"/>, with <see cref="MediaOptions.ExtractMotionPhoto"/> on. A LIVP
+ /// (an iPhone photo and its MOV in one ZIP) always gives its video. Other pictures (GIF, PNG, …) convert as usual.
+ /// </summary>
+ public bool ExtractsMotionOf(string sourceFormat) =>
+ MediaOptions.MotionPhotoTargets.Contains(TargetFormat)
+ && MediaOptions.MotionPhotoSources.Contains(sourceFormat)
+ && (Media.ExtractMotionPhoto || sourceFormat == "livp");
/// <summary>True for a <see cref="PresetKind.Tool"/>.</summary>
[JsonIgnore]
@@ -463,17 +469,22 @@ 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>Formats a Live / Motion Photo video can be taken into (<see cref="ExtractMotionPhoto"/>).</summary>
+ public static readonly IReadOnlyList<string> MotionPhotoTargets = ["mp4", "mov"];
- /// <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>
+ /// Photos that can hold a video (<see cref="ExtractMotionPhoto"/>): Android Motion Photos (JPEG with the video
+ /// appended, HEIC / AVIF with an <c>mpvd</c> box), iPhone Live Photos (a JPEG or HEIC with its MOV next to it) and
+ /// LIVP packages.
+ /// </summary>
+ public static readonly IReadOnlyList<string> MotionPhotoSources = ["jpg", "heic", "avif", "livp"];
- /// <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>
+ /// MP4 / MOV: a Live / Motion Photo becomes its video (with sound) instead of a video of the still picture. Only
+ /// for sources in <see cref="MotionPhotoSources"/> (<see cref="Preset.ExtractsMotionOf"/>); a photo without a video
+ /// fails with <c>error.no_motion_photo</c>.
+ /// </summary>
+ public bool ExtractMotionPhoto { get; set; }
/// <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.cs
index 432ddcf6..147da661 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -65,7 +65,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 = 28;
+ public const int CurrentSchemaVersion = 29;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index c8bd5fb7..91af0881 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -659,6 +659,29 @@ internal static class SettingsMigrations
// the user filled up, or a library without the preset, stays as it is.
if (from < 28)
changed |= Offer(presets, profiles, "archives", "zip-all", "extract");
+ // v29: "Extract live video" (the video of a Live / Motion Photo as MP4), after "Extract frames" as in a new
+ // library, on no donut: the images donut is full. Present already but saved since by a Filee before 29:
+ // that one dropped the option and left a plain MP4 preset, so it is put back. The images donut learns
+ // ".livp" (iPhone Live Photos downloaded from iCloud) unless a donut of the user already takes it.
+ if (from < 29)
+ {
+ foreach (var motion in BuiltInData.MotionPhotoPresets())
+ {
+ if (presets.FirstOrDefault(p => p.Id == motion.Id) is { } existing)
+ {
+ if (!existing.Media.ExtractMotionPhoto && existing.TargetFormat == motion.TargetFormat)
+ {
+ existing.Media.ExtractMotionPhoto = true;
+ changed = true;
+ }
+ continue;
+ }
+ var at = presets.FindIndex(p => p.Id == "extract-frames-jpg");
+ presets.Insert(at < 0 ? presets.Count : at + 1, motion);
+ changed = true;
+ }
+ changed |= LearnExtensions(profiles, out _, ["livp"]);
+ }
return changed;
}
diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.cs
index c73b1ffe..1679e1a9 100644
--- a/src/Filee.Engines/Magick/ImageEncoder.cs
+++ b/src/Filee.Engines/Magick/ImageEncoder.cs
@@ -77,9 +77,15 @@ internal static class ImageEncoder
/// <summary>Formats holding one picture in several sizes (icons) or mipmaps: the largest is converted.</summary>
private static readonly HashSet<string> SizeVariants = ["ico", "cur", "dds"];
- /// <summary>Every format ImageMagick reads as input: the raster formats plus, on Windows, the metafiles.</summary>
+ /// <summary>Packages of a picture and more, of which the picture is read (<see cref="ImageReader"/>): an iPhone LIVP.</summary>
+ public static readonly string[] Packages = ["livp"];
+
+ /// <summary>
+ /// Every format ImageMagick reads as input: the raster formats, the picture of <see cref="Packages"/> and, on
+ /// Windows, the metafiles.
+ /// </summary>
public static IEnumerable<string> Sources =>
- OperatingSystem.IsWindows() ? [.. Readable, .. Metafiles] : Readable;
+ OperatingSystem.IsWindows() ? [.. Readable, .. Packages, .. Metafiles] : [.. Readable, .. Packages];
public static MagickFormat ToMagickFormat(string formatId) => formatId switch
{
diff --git a/src/Filee.Engines/Magick/ImageReader.cs b/src/Filee.Engines/Magick/ImageReader.cs
index 7dc798b3..8d60c350 100644
--- a/src/Filee.Engines/Magick/ImageReader.cs
+++ b/src/Filee.Engines/Magick/ImageReader.cs
@@ -1,8 +1,8 @@
// Reads source images with ImageMagick, handling the formats that need more than "open the file": camera RAW
// (LibRaw settings), layered PSD/PSB/XCF (one flattened picture instead of one file per layer) and Windows
// metafiles (rendered at the preset's DPI), APNG (Filee's own reader composes the frames) and uncompressed DICOM
-// (Filee's own reader, as ImageMagick's Q8 build reads only 8-bit DICOM). Used by every engine that takes a raster
-// image as input.
+// (Filee's own reader, as ImageMagick's Q8 build reads only 8-bit DICOM) and the photo of an iPhone LIVP. Used by every
+// engine that takes a raster image as input.
using System.Buffers.Binary;
using Filee.Core.Presets;
@@ -27,6 +27,8 @@ internal static class ImageReader
return Apng.Read(path);
if (formatId == "dcm" && Dicom.TryRead(path) is { } scan)
return scan;
+ if (formatId == "livp")
+ return ReadLivePhoto(path, preset);
var images = new MagickImageCollection();
var settings = Settings(formatId, preset);
@@ -83,6 +85,25 @@ internal static class ImageReader
return images;
}
+ /// <summary>The photo (JPEG or HEIC) of a LIVP, read from the package without unpacking it.</summary>
+ private static MagickImageCollection ReadLivePhoto(string path, Preset preset)
+ {
+ var (data, format) = Media.LivePhotoSource.ReadStill(path);
+ var settings = Settings(format, preset);
+ settings.Format = ImageEncoder.ToMagickFormat(format);
+ var images = new MagickImageCollection();
+ try
+ {
+ images.Read(data, settings);
+ return images;
+ }
+ catch
+ {
+ images.Dispose();
+ throw;
+ }
+ }
+
/// <summary>Read settings per source format.</summary>
internal static MagickReadSettings Settings(string formatId, Preset preset)
{
diff --git a/src/Filee.Engines/Media/AppleLivePhoto.cs b/src/Filee.Engines/Media/AppleLivePhoto.cs
index 9cec3fdd..b2e4593c 100644
--- a/src/Filee.Engines/Media/AppleLivePhoto.cs
+++ b/src/Filee.Engines/Media/AppleLivePhoto.cs
@@ -1,4 +1,4 @@
-// Apple Live Photo pairing and a timed still-image marker. Only private FFmpeg scratch movies are rewritten.
+// Apple Live Photo pairing: the content identifier the photo (Apple maker note) and its MOV (QuickTime metadata) share.
using System.Buffers.Binary;
using System.Text;
@@ -10,27 +10,9 @@ 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);
- }
-
+ /// <summary>The content identifier in the photo's Apple maker note (tag 17), or null.</summary>
public static string? ImageIdentifier(string imagePath)
{
using var image = new MagickImage();
@@ -55,6 +37,7 @@ internal static class AppleLivePhoto
var at = 16 + i * 12;
if (Read16(at) != 17 || Read16(at + 2) != 2)
continue;
+ // Apple maker-note offsets are relative to the note itself.
var length = Read32(at + 4);
var offset = Read32(at + 8);
if (length < 36 || length > 128 || offset > data.Length || length > data.Length - offset)
@@ -65,31 +48,12 @@ internal static class AppleLivePhoto
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.");
- }
-
+ /// <summary>The content identifier in the movie's QuickTime metadata, or null.</summary>
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 children = Children(ReadMovie(file));
+ // Apple's movie-level meta is a plain container; other writers put 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));
@@ -104,7 +68,9 @@ internal static class AppleLivePhoto
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 itemType = new byte[4];
+ BinaryPrimitives.WriteUInt32BigEndian(itemType, (uint)index);
+ foreach (var value in Children(values).Where(v => v.Type == Encoding.Latin1.GetString(itemType)))
{
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))
@@ -114,64 +80,22 @@ internal static class AppleLivePhoto
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)
+ private static byte[] ReadMovie(Stream file)
{
- 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);
+ 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 data;
+ }
+ file.Position = box.End;
+ }
+ throw new InvalidDataException("Live Photo has no movie metadata.");
}
}
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
index 8fed9554..041e9b95 100644
--- a/src/Filee.Engines/Media/FfmpegConverter.cs
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -4,7 +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.
+// Live / Motion Photos (Android, iPhone) give their video when a preset asks for it (LivePhotoSource, MotionPhoto).
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
@@ -86,13 +86,9 @@ 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" }
+ // The video of a Live / Motion Photo, only when a preset asks for it (see ConversionEdge.MotionPhoto).
+ .. from source in MediaOptions.MotionPhotoSources from target in MediaOptions.MotionPhotoTargets
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),
];
}
@@ -115,13 +111,8 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
public 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.MotionPhoto)
+ return await ExtractMotionAsync(step, progress, cancellationToken);
if (step.To == "heic")
return await HeicWriter.ConvertAsync(ffmpeg, step, progress, cancellationToken);
var input = Path.GetFullPath(step.InputPath);
@@ -180,6 +171,52 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
return [output];
}
+ /// <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
+ /// never touches a file the output would replace.
+ /// </summary>
+ private async Task<IReadOnlyList<string>> ExtractMotionAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ var (video, companion) = await LivePhotoSource.ExtractAsync(step.InputPath, step.From, step.WorkDirectory, _logger, cancellationToken);
+ var staged = new StagedOutput(step.Output, step.WorkDirectory, companion);
+ var written = await ConvertAsync(step with { InputPath = video, From = "mov", MotionPhoto = false, Output = staged },
+ progress, cancellationToken);
+ return staged.Commit(written);
+ }
+
+ /// <summary>
+ /// Hands out paths in the work directory for outputs whose real path comes from <paramref name="final"/>. That one
+ /// is never <paramref name="companion"/>: with "overwrite", IMG_0001.HEIC → MOV would otherwise be written over
+ /// IMG_0001.MOV, the Live Photo's own video, so it gets a numbered name instead.
+ /// </summary>
+ private sealed class StagedOutput(IOutputAllocator final, string workDirectory, string? companion) : IOutputAllocator
+ {
+ private readonly Dictionary<string, string> _paths = [];
+
+ public string? Allocate(string extension, string? suffix = null)
+ {
+ var path = final.Allocate(extension, suffix);
+ for (var n = 2; path is not null && companion is not null && SamePath(path, companion); n++)
+ path = final.Allocate(extension, $"{suffix} ({n})");
+ if (path is null)
+ return null;
+ var temp = Path.Combine(workDirectory, Guid.NewGuid().ToString("N") + "." + extension.TrimStart('.'));
+ _paths[temp] = path;
+ return temp;
+ }
+
+ public IReadOnlyList<string> Commit(IReadOnlyList<string> written) =>
+ written.Select(temp =>
+ {
+ File.Move(temp, _paths[temp], overwrite: true);
+ return _paths[temp];
+ }).ToList();
+
+ private static bool SamePath(string a, string b) =>
+ string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase);
+ }
+
/// <summary>
/// Runs <paramref name="passes"/>, planned with <paramref name="hardware"/>. When a hardware encode fails (a driver
/// error, a picture larger than the chip encodes, …) the file is encoded again as <paramref name="plan"/> plans it
diff --git a/src/Filee.Engines/Media/LivePhotoConversion.cs b/src/Filee.Engines/Media/LivePhotoConversion.cs
deleted file mode 100644
index 89bfb44e..00000000
--- a/src/Filee.Engines/Media/LivePhotoConversion.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-// 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.cs
index 910d9e53..641d76f8 100644
--- a/src/Filee.Engines/Media/LivePhotoSource.cs
+++ b/src/Filee.Engines/Media/LivePhotoSource.cs
@@ -1,8 +1,11 @@
-// Reads LIVP pairs and embedded Android motion videos without unpacking archive paths or changing camera files.
+// The video of a Live / Motion Photo, copied into the job's work directory: the photo, the MOV next to it and a LIVP
+// are only read. Archive entry names are never used as paths.
using System.IO.Compression;
+using System.Xml;
using Filee.Core.Conversion;
-using Filee.Core.Formats;
+using ImageMagick;
+using Microsoft.Extensions.Logging;
namespace Filee.Engines.Media;
@@ -11,66 +14,183 @@ 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)
+ /// <summary>A LIVP holds a photo and its MOV; anything much larger is not one.</summary>
+ private const int MaxPackageEntries = 16;
+
+ private static readonly string[] MovieExtensions = [".mov", ".mp4"];
+ private static readonly string[] StillExtensions = [".jpg", ".jpeg", ".heic", ".heif"];
+
+ /// <summary>
+ /// Copies the video of <paramref name="input"/> (format <paramref name="from"/>) into
+ /// <paramref name="workDirectory"/>: the video appended to an Android Motion Photo, the MOV of a LIVP, or the MOV
+ /// next to an iPhone photo with the same name and content identifier.
+ /// </summary>
+ /// <returns>The copy, and the iPhone MOV it was copied from (null for the others): no output may replace it.</returns>
+ /// <exception cref="ConversionRefusedException"><c>error.no_motion_photo</c>: the photo has no video Filee can read.</exception>
+ public static async Task<(string Video, string? Companion)> ExtractAsync(string input, string from, string workDirectory,
+ ILogger logger, 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)
+ // Stale or broken metadata, or a damaged LIVP: the reason goes to the log, the user gets the plain message.
+ // Metadata of one kind that can't be read doesn't keep the other from being looked at.
+ string? reason = null;
+ try
{
- 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 (from == "livp")
+ return (await CopyPackageVideoAsync(input, workDirectory, logger, ct), null);
+ if (await CopyEmbeddedAsync(input, workDirectory, ct) is { } embedded)
+ return (embedded, null);
}
- if (format is "jpg" or "heic")
+ catch (Exception ex) when (Unreadable(ex))
{
- 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];
- }
+ reason = ex.Message;
}
+ try
+ {
+ if (from is "jpg" or "heic" && PairedMovie(input) is { } companion)
+ return (await CopyFileAsync(companion, workDirectory, ct), companion);
+ }
+ catch (Exception ex) when (Unreadable(ex))
+ {
+ reason ??= ex.Message;
+ }
+ if (reason is not null)
+ logger.LogInformation("{File}: no motion video ({Reason})", input, reason);
throw new ConversionRefusedException("error.no_motion_photo");
}
- private static async Task<string> ExtractPackageAsync(string path, string workDirectory, CancellationToken ct)
+ private static bool Unreadable(Exception ex) => ex is InvalidDataException or XmlException or EndOfStreamException;
+
+ /// <summary>
+ /// The photo of a LIVP, for the image engines: its bytes and format (<c>jpg</c> or <c>heic</c>).
+ /// </summary>
+ /// <exception cref="InvalidDataException">The package has no single photo, or it is too large.</exception>
+ public static (byte[] Data, string Format) ReadStill(string livp)
+ {
+ using var zip = ZipFile.OpenRead(livp);
+ var entry = Single(zip, StillExtensions, "photo");
+ if (entry.Length <= 0 || entry.Length > MaxImageBytes)
+ throw new InvalidDataException("The Live Photo's picture is empty or too large.");
+ var data = new byte[entry.Length];
+ using (var stream = entry.Open())
+ stream.ReadExactly(data);
+ var format = Path.GetExtension(entry.Name).ToLowerInvariant() is ".heic" or ".heif" ? "heic" : "jpg";
+ return (data, format);
+ }
+
+ private static async Task<string?> CopyEmbeddedAsync(string input, string workDirectory, CancellationToken ct)
+ {
+ await using var file = File.OpenRead(input);
+ if (MotionPhoto.FindVideo(file) is not { } video)
+ return null;
+ if (video.Length > MaxVideoBytes)
+ throw new InvalidDataException("Motion Photo video exceeds 512 MiB.");
+ 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;
+ }
+
+ /// <summary>
+ /// The MOV saved next to an iPhone photo (IMG_0001.HEIC + IMG_0001.MOV), when both carry the same content
+ /// identifier: a same-named video alone is not enough.
+ /// </summary>
+ private static string? PairedMovie(string input)
+ {
+ string? id;
+ try
+ {
+ id = AppleLivePhoto.ImageIdentifier(input);
+ }
+ catch (MagickException)
+ {
+ return null;
+ }
+ if (id is null)
+ return null;
+ var full = Path.GetFullPath(input);
+ var name = Path.GetFileNameWithoutExtension(full);
+ var movies = Directory.EnumerateFiles(Path.GetDirectoryName(full)!)
+ .Where(p => Path.GetExtension(p).Equals(".mov", StringComparison.OrdinalIgnoreCase)
+ && Path.GetFileNameWithoutExtension(p).Equals(name, StringComparison.OrdinalIgnoreCase))
+ .ToList();
+ return movies.Count == 1 && id.Equals(AppleLivePhoto.MovieIdentifier(movies[0]), StringComparison.OrdinalIgnoreCase)
+ ? movies[0]
+ : null;
+ }
+
+ /// <summary>
+ /// The MOV of a LIVP. The package makes the pair: a content identifier that doesn't match the photo's (or one that
+ /// can't be read) is only logged.
+ /// </summary>
+ private static async Task<string> CopyPackageVideoAsync(string path, string workDirectory, ILogger logger, 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.");
+ var movie = Path.Combine(workDirectory, Guid.NewGuid().ToString("N") + ".mov");
+ await CopyEntryAsync(Single(zip, MovieExtensions, "video"), movie, MaxVideoBytes, ct);
+
+ var stills = Entries(zip, StillExtensions);
+ string? imageId = null;
+ if (stills.Count == 1 && stills[0].Length is > 0 and <= MaxImageBytes)
+ {
+ var image = Path.Combine(workDirectory, Guid.NewGuid().ToString("N") + Path.GetExtension(stills[0].Name).ToLowerInvariant());
+ await CopyEntryAsync(stills[0], image, MaxImageBytes, ct);
+ try
+ {
+ imageId = AppleLivePhoto.ImageIdentifier(image);
+ }
+ catch (MagickException) { }
+ File.Delete(image);
+ }
+ string? movieId = null;
+ try
+ {
+ movieId = AppleLivePhoto.MovieIdentifier(movie);
+ }
+ catch (InvalidDataException) { }
+ if (imageId is null || movieId is null || !imageId.Equals(movieId, StringComparison.OrdinalIgnoreCase))
+ logger.LogWarning("{File}: the photo's and video's Live Photo identifiers don't match ({Image} / {Movie}); taking the package's video",
+ path, imageId ?? "none", movieId ?? "none");
return movie;
}
+ /// <summary>Files of the package with one of <paramref name="extensions"/>, without macOS resource forks.</summary>
+ private static List<ZipArchiveEntry> Entries(ZipArchive zip, string[] extensions)
+ {
+ if (zip.Entries.Count > MaxPackageEntries)
+ throw new InvalidDataException("A LIVP holds a photo and its video, not this many files.");
+ return zip.Entries
+ .Where(e => e.Name.Length > 0 && !e.Name.StartsWith("._", StringComparison.Ordinal)
+ && !e.FullName.StartsWith("__MACOSX/", StringComparison.OrdinalIgnoreCase)
+ && extensions.Contains(Path.GetExtension(e.Name).ToLowerInvariant()))
+ .ToList();
+ }
+
+ private static ZipArchiveEntry Single(ZipArchive zip, string[] extensions, string what)
+ {
+ var entries = Entries(zip, extensions);
+ return entries.Count == 1 ? entries[0] : throw new InvalidDataException($"A LIVP must contain exactly one {what}.");
+ }
+
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.
+ // The target is a name of Filee's own in the work directory, whatever the entry is called.
await using var source = entry.Open();
await using var output = File.Create(target);
await MovieBoxes.CopyRangeAsync(source, output, entry.Length, ct);
}
+
+ /// <summary>Copies the iPhone MOV, so the conversion reads a copy and never the user's file it might be told to replace.</summary>
+ private static async Task<string> CopyFileAsync(string path, string workDirectory, CancellationToken ct)
+ {
+ await using var source = File.OpenRead(path);
+ if (source.Length <= 0 || source.Length > MaxVideoBytes)
+ throw new InvalidDataException("The Live Photo video is empty or too large.");
+ var copy = Path.Combine(workDirectory, Guid.NewGuid().ToString("N") + ".mov");
+ await using var target = File.Create(copy);
+ await MovieBoxes.CopyRangeAsync(source, target, source.Length, ct);
+ return copy;
+ }
}
diff --git a/src/Filee.Engines/Media/MotionPhoto.cs b/src/Filee.Engines/Media/MotionPhoto.cs
index 97c127d2..3439d69e 100644
--- a/src/Filee.Engines/Media/MotionPhoto.cs
+++ b/src/Filee.Engines/Media/MotionPhoto.cs
@@ -1,4 +1,4 @@
-// Android JPEG Motion Photo metadata and bounded extraction of the video at the end of a camera image.
+// Android Motion Photos: where the video saved with a camera picture is, read from the picture's own metadata.
using System.Buffers.Binary;
using System.Globalization;
@@ -8,7 +8,10 @@ using System.Xml.Linq;
namespace Filee.Engines.Media;
-/// <summary>Google Motion Photo 1.0 JPEGs and legacy Microvideo JPEGs.</summary>
+/// <summary>
+/// Google Motion Photo 1.0 JPEGs (Pixel, Samsung and others: an XMP container directory, the video appended), legacy
+/// MicroVideo JPEGs (an offset from the end of the file) and HEIC / AVIF pictures with the video in an <c>mpvd</c> box.
+/// </summary>
internal static class MotionPhoto
{
private static readonly byte[] XmpHeader = "http://ns.adobe.com/xap/1.0/\0"u8.ToArray();
@@ -16,39 +19,15 @@ internal static class MotionPhoto
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>JPEG metadata comes before the picture data; the walk stops there, and never goes further than this.</summary>
+ private const int MaxMetadataBytes = 8 * 1024 * 1024;
- /// <summary>Finds the declared video, never by searching arbitrary image bytes for an MP4 signature.</summary>
+ /// <summary>
+ /// Finds the declared video, never by searching the picture's bytes for an MP4 signature. Null for a picture
+ /// without one.
+ /// </summary>
+ /// <exception cref="InvalidDataException">The picture says it has a video, but it isn't there (stale metadata).</exception>
+ /// <exception cref="XmlException">The XMP can't be read.</exception>
public static (long Offset, long Length)? FindVideo(Stream file)
{
file.Position = 0;
@@ -60,9 +39,10 @@ internal static class MotionPhoto
var box = MovieBoxes.ReadHeader(file);
if (box.Type == "mpvd")
{
- if (box.End != file.Length || box.Length <= box.HeaderLength)
+ // Samsung writes its own trailer after the box, so the box need not end the file.
+ if (box.Length <= box.HeaderLength)
throw new InvalidDataException("Invalid Motion Photo video box.");
- return (box.Start + box.HeaderLength, box.Length - box.HeaderLength);
+ return Checked(file, box.Start + box.HeaderLength, box.Length - box.HeaderLength);
}
file.Position = box.End;
}
@@ -71,8 +51,7 @@ internal static class MotionPhoto
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))
+ while (file.Position < Math.Min(file.Length, MaxMetadataBytes))
{
if (file.ReadByte() != 0xff)
throw new InvalidDataException("Invalid JPEG marker.");
@@ -87,55 +66,99 @@ internal static class MotionPhoto
var length = BinaryPrimitives.ReadUInt16BigEndian(size) - 2;
if (length < 0 || length > file.Length - file.Position)
throw new InvalidDataException("Invalid JPEG segment length.");
- if (marker == 0xe1)
+ 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;
+ continue;
+ }
+ var data = new byte[length];
+ file.ReadExactly(data);
+ if (!data.AsSpan().StartsWith(XmpHeader) || VideoLength(data) is not { } videoLength)
+ continue;
+ if (videoLength == 0)
+ return null;
+ // The video ends the file; Samsung's own trailer after it is cut off by Checked.
+ var start = file.Length - videoLength;
+ if (videoLength < 16 || start < file.Position)
+ throw new InvalidDataException("Motion Photo video length is outside the file.");
+ return Checked(file, start, videoLength);
+ }
+ return null;
+ }
+
+ /// <summary>
+ /// The length from the end of the file that the XMP gives the video, 0 for a picture marked as not moving (a
+ /// motion photo whose video was switched off), or null
+ /// when this XMP packet says nothing about motion. Properties may be attributes or elements.
+ /// </summary>
+ private static long? VideoLength(byte[] data)
+ {
+ // Some writers pad the packet with NUL bytes after its end, which XML doesn't allow.
+ var end = Math.Max(XmpHeader.Length, Array.LastIndexOf(data, (byte)'>') + 1);
+ using var reader = XmlReader.Create(new MemoryStream(data, XmpHeader.Length, end - XmpHeader.Length),
+ new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 65535 });
+ var xml = XDocument.Load(reader);
+ string? Property(XName name) =>
+ xml.Descendants().Attributes(name).FirstOrDefault()?.Value ?? xml.Descendants(name).FirstOrDefault()?.Value;
+ static string? Field(XElement item, string name) =>
+ item.Attribute(XName.Get(name, Item))?.Value ?? item.Element(XName.Get(name, Item))?.Value;
+
+ if (Property(XName.Get("MotionPhoto", Camera)) is { } motion)
+ {
+ if (motion.Trim() != "1")
+ return 0;
+ // The video is the last item of the directory (a Pixel lists a gain map before it).
+ var last = xml.Descendants(XName.Get("Item", Container)).LastOrDefault();
+ if (last is null || Field(last, "Semantic") != "MotionPhoto"
+ || Field(last, "Mime") is not ("video/mp4" or "video/quicktime")
+ || !long.TryParse(Field(last, "Length"), NumberStyles.None, CultureInfo.InvariantCulture, out var length))
+ throw new InvalidDataException("Motion Photo has no valid video directory entry.");
+ return length;
+ }
+ // MicroVideo (Motion Photo before 1.0): an offset back from the end of the file.
+ if (Property(XName.Get("MicroVideo", Camera))?.Trim() == "1")
+ {
+ return long.TryParse(Property(XName.Get("MicroVideoOffset", Camera)), NumberStyles.None, CultureInfo.InvariantCulture, out var offset)
+ ? offset
+ : throw new InvalidDataException("MicroVideo has no valid offset.");
}
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)
+ /// <summary>
+ /// The video at <paramref name="start"/>, up to the end of its last whole box: an MP4 must start there (not stale
+ /// XMP left by an editor that rewrote the picture) and hold its movie header. Anything after it (Samsung's SEF
+ /// trailer) is left out.
+ /// </summary>
+ private static (long Offset, long Length) Checked(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.");
+ var end = start + length;
+ var at = start;
+ var movie = false;
+ Span<byte> header = stackalloc byte[16];
+ while (end - at >= 8)
+ {
+ file.Position = at;
+ file.ReadExactly(header[..8]);
+ long size = BinaryPrimitives.ReadUInt32BigEndian(header);
+ var type = Encoding.Latin1.GetString(header[4..8]);
+ if (size == 1 && end - at >= 16)
+ {
+ file.ReadExactly(header[8..16]);
+ var large = BinaryPrimitives.ReadUInt64BigEndian(header[8..]);
+ size = large > long.MaxValue ? -1 : (long)large;
+ }
+ else if (size == 0)
+ size = end - at;
+ if (size < 8 || size > end - at || (at == start && type != "ftyp"))
+ break;
+ movie |= type == "moov";
+ at += size;
+ }
+ if (at == start)
+ throw new InvalidDataException("The picture no longer contains its declared Motion Photo video.");
+ if (!movie)
+ throw new InvalidDataException("The Motion Photo video has no movie header.");
+ return (start, at - start);
}
}
diff --git a/src/Filee.Engines/Media/MovieBoxes.cs b/src/Filee.Engines/Media/MovieBoxes.cs
index 891f457a..1aa96836 100644
--- a/src/Filee.Engines/Media/MovieBoxes.cs
+++ b/src/Filee.Engines/Media/MovieBoxes.cs
@@ -1,4 +1,4 @@
-// Small, bounds-checked ISO BMFF box helpers for photo metadata; media payloads are streamed, never loaded whole.
+// Small, bounds-checked ISO BMFF box readers for photo metadata; media payloads are streamed, never loaded whole.
using System.Buffers.Binary;
using System.Text;
@@ -12,6 +12,7 @@ internal readonly record struct MovieBox(string Type, long Start, long Length, i
internal static class MovieBoxes
{
+ /// <summary>Reads the box header at the stream's position; a box reaching past the end of the stream is refused.</summary>
public static MovieBox ReadHeader(Stream file)
{
var start = file.Position;
@@ -36,6 +37,7 @@ internal static class MovieBoxes
return new(type, start, size, headerLength);
}
+ /// <summary>The boxes in <paramref name="data"/> (a parent's payload), after <paramref name="skip"/> bytes.</summary>
public static List<(string Type, byte[] Payload)> Children(byte[] data, int skip = 0)
{
using var stream = new MemoryStream(data);
@@ -51,23 +53,7 @@ internal static class MovieBoxes
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();
-
+ /// <summary>Copies exactly <paramref name="count"/> bytes; a source that ends sooner is an error.</summary>
public static async Task CopyRangeAsync(Stream source, Stream target, long count, CancellationToken ct)
{
var buffer = new byte[81920];
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 47037195..2d7eabec 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1665,42 +1665,30 @@ public class RenderTests
}
[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)
+ [InlineData("en")]
+ [InlineData("ko")]
+ [InlineData("zh-CN")]
+ public void Extract_live_photo_video_option_renders_and_saves_for_mp4_and_mov_only(string language)
{
TestServices.EnsureInitialized(language);
- var preset = Filee.Core.Presets.BuiltInData.LivePhotoPresets().Single(p => p.TargetFormat == target);
+ var preset = Filee.Core.Presets.BuiltInData.MotionPhotoPresets().Single();
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;
+ Assert.True(vm.ShowExtractMotionPhoto);
+ Assert.True(vm.ExtractMotionPhoto);
var window = new PresetEditorWindow { DataContext = vm, Height = 980 };
window.Show();
Pump();
- Save(window, $"preset-livephoto-{target}-{language}.png");
+ Save(window, $"preset-extract-motion-{language}.png");
window.Close();
+
+ vm.Target = vm.Targets.Single(t => t.Value == "mov");
+ Assert.True(vm.ShowExtractMotionPhoto);
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);
+ Assert.True(preset.Media.ExtractMotionPhoto);
+ // A box ticked for MP4 and left behind by another target saves nothing.
var restored = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
- Assert.Equal(2.5, restored.LivePhotoDuration);
- restored.Target = restored.Targets.Single(t => t.Value == "png");
+ restored.Target = restored.Targets.Single(t => t.Value == "webm");
+ Assert.False(restored.ShowExtractMotionPhoto);
Assert.True(restored.Apply());
Assert.False(preset.Media.ExtractMotionPhoto);
}
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index 07fcd054..04c62d20 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -6,33 +6,6 @@ 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()
{
@@ -835,6 +808,37 @@ public class UserDataStoreTests
Assert.DoesNotContain("zip-all", archives.PresetIds);
}
+ [Fact]
+ public void Version_28_libraries_get_extract_live_video_on_no_donut_and_learn_livp()
+ {
+ // As written with schema 28: no "Extract Live Photo video", no .livp on the images donut, and the user took
+ // HEIC off it.
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => p.Id == "extract-motion");
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.Extensions.RemoveAll(e => e is "livp" or "heic");
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(28, presets, profiles));
+
+ var motion = presets.Single(p => p.Id == "extract-motion");
+ Assert.True(motion.Media.ExtractMotionPhoto);
+ Assert.Equal("mp4", motion.TargetFormat);
+ Assert.Equal("extract-frames-jpg", presets[presets.IndexOf(motion) - 1].Id);
+ Assert.DoesNotContain(profiles, p => p.PresetIds.Contains("extract-motion"));
+ Assert.Contains("livp", images.Extensions);
+ Assert.DoesNotContain("heic", images.Extensions);
+ Assert.False(SettingsMigrations.ApplyToLibrary(28, presets, profiles)); // once only
+
+ // Back from an older Filee, which dropped the option it didn't know: the preset extracts again, its name stays.
+ motion.Media.ExtractMotionPhoto = false;
+ motion.Name = "Live video";
+ Assert.True(SettingsMigrations.ApplyToLibrary(28, presets, profiles));
+ Assert.True(motion.Media.ExtractMotionPhoto);
+ Assert.Equal("Live video", motion.Name);
+ Assert.Single(presets, p => p.Id == "extract-motion");
+ }
+
[Fact]
public void Version_15_libraries_get_the_tracing_presets_on_the_images_donut_after_pdf()
{
diff --git a/tests/Filee.Engines.Tests/LivePhotoTests.cs b/tests/Filee.Engines.Tests/LivePhotoTests.cs
index 7d5f8b29..ae65921b 100644
--- a/tests/Filee.Engines.Tests/LivePhotoTests.cs
+++ b/tests/Filee.Engines.Tests/LivePhotoTests.cs
@@ -1,9 +1,9 @@
-// Generated video/photo fixtures: real bidirectional conversions and independent ffprobe checks of Apple timing.
+// Live / Motion Photo → video. Every photo is built here: a real video from FFmpeg, appended to a JPEG or boxed in a
+// HEIC as Pixel, Samsung and older Google cameras do, or saved next to an iPhone-style photo with a shared identifier.
-using System.Globalization;
+using System.Buffers.Binary;
using System.IO.Compression;
using System.Text;
-using System.Text.Json;
using Filee.Core.Conversion;
using Filee.Core.Formats;
using Filee.Core.Presets;
@@ -16,6 +16,8 @@ namespace Filee.Engines.Tests;
[Collection(nameof(FfmpegCollection))]
public class LivePhotoTests(EngineFixture fx) : IClassFixture<EngineFixture>
{
+ private const string LiveId = "6F2C8E8A-1A3B-4C5D-9E0F-112233445566";
+
private static (string Ffmpeg, string Ffprobe) Tools()
{
var tools = FfmpegConverter.Locate();
@@ -23,17 +25,91 @@ public class LivePhotoTests(EngineFixture fx) : IClassFixture<EngineFixture>
return tools.Value;
}
- private async Task<string> VideoAsync(bool audio = true)
+ private static Preset Extract(string target = "mp4", ConflictPolicy conflict = ConflictPolicy.Rename) =>
+ new() { TargetFormat = target, Media = { ExtractMotionPhoto = true }, Output = { Conflict = conflict } };
+
+ /// <summary>A test picture video (2 s, 160×120 unless asked otherwise) with or without a sine tone, as MP4 or MOV.</summary>
+ private async Task<byte[]> VideoAsync(bool audio = true, string extension = "mp4", int seconds = 2, string size = "160x120",
+ string[]? extra = null)
{
- 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",
+ var path = Path.Combine(fx.NewFolder(), "clip ü 中文." + extension);
+ var result = await FfmpegRunner.RunAsync(Tools().Ffmpeg, [
+ .. MediaEncoding.Common, "-f", "lavfi", "-i", $"testsrc2=size={size}: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,
+ "-t", seconds.ToString(System.Globalization.CultureInfo.InvariantCulture), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", .. extra ?? [], path,
], null, TestContext.Current.CancellationToken);
Assert.True(result.ExitCode == 0, result.StandardError);
- return input;
+ return await File.ReadAllBytesAsync(path, TestContext.Current.CancellationToken);
+ }
+
+ private static byte[] Jpeg(uint width = 320, uint height = 200, byte[]? makerNote = null)
+ {
+ using var image = new MagickImage("gradient:#7F77DD-#1D9E75", width, height);
+ if (makerNote is not null)
+ {
+ var exif = new ExifProfile();
+ exif.SetValue(ExifTag.MakerNote, makerNote);
+ image.SetProfile(exif);
+ }
+ return image.ToByteArray(MagickFormat.Jpeg);
+ }
+
+ /// <summary>The JPEG with an XMP segment right after its start marker.</summary>
+ 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, .. U16((ushort)(payload.Length + 2)), .. payload, .. jpeg.Skip(2)];
+ }
+
+ /// <summary>Motion Photo 1.0 XMP as a Pixel writes it (a gain map listed before the video), or with elements.</summary>
+ private static string MotionXmp(long length, bool elements = false) => elements
+ ? $"""
+ <x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
+ <rdf:Description xmlns:GCamera="http://ns.google.com/photos/1.0/camera/" xmlns:Container="http://ns.google.com/photos/1.0/container/" xmlns:Item="http://ns.google.com/photos/1.0/container/item/">
+ <GCamera:MotionPhoto>1</GCamera:MotionPhoto>
+ <GCamera:MotionPhotoVersion>1</GCamera:MotionPhotoVersion>
+ <Container:Directory><rdf:Seq>
+ <rdf:li rdf:parseType="Resource"><Container:Item><Item:Mime>image/jpeg</Item:Mime><Item:Semantic>Primary</Item:Semantic></Container:Item></rdf:li>
+ <rdf:li rdf:parseType="Resource"><Container:Item><Item:Mime>video/mp4</Item:Mime><Item:Semantic>MotionPhoto</Item:Semantic><Item:Length>{length}</Item:Length></Container:Item></rdf:li>
+ </rdf:Seq></Container:Directory>
+ </rdf:Description>
+ </rdf:RDF></x:xmpmeta>
+ """
+ : $"""
+ <x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
+ <rdf:Description xmlns:GCamera="http://ns.google.com/photos/1.0/camera/" xmlns:Container="http://ns.google.com/photos/1.0/container/" xmlns:Item="http://ns.google.com/photos/1.0/container/item/"
+ GCamera:MotionPhoto="1" GCamera:MotionPhotoVersion="1" GCamera:MotionPhotoPresentationTimestampUs="500000">
+ <Container:Directory><rdf:Seq>
+ <rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="Primary" Item:Mime="image/jpeg"/></rdf:li>
+ <rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="GainMap" Item:Mime="image/jpeg" Item:Length="0"/></rdf:li>
+ <rdf:li rdf:parseType="Resource"><Container:Item Item:Mime="video/mp4" Item:Semantic="MotionPhoto" Item:Length="{length}" Item:Padding="0"/></rdf:li>
+ </rdf:Seq></Container:Directory>
+ </rdf:Description>
+ </rdf:RDF></x:xmpmeta>
+ """;
+
+ /// <summary>
+ /// Samsung's SEF trailer as its cameras append it after the video: a "MotionPhoto_Data" block before the video, a
+ /// directory after it. The XMP length counts the directory too.
+ /// </summary>
+ private static (byte[] Before, byte[] After) SamsungTrailer()
+ {
+ byte[] before = [0, 0, 0x30, 0x0a, .. BitConverter.GetBytes(16), .. "MotionPhoto_Data"u8.ToArray()];
+ byte[] after = [.. "SEFH"u8.ToArray(), .. BitConverter.GetBytes(107), .. BitConverter.GetBytes(0)];
+ return (before, [.. after, .. BitConverter.GetBytes(after.Length), .. "SEFT"u8.ToArray()]);
+ }
+
+ private async Task<string> MotionJpegAsync(string name, string form = "attributes", bool audio = true)
+ {
+ var video = await VideoAsync(audio);
+ var (before, after) = form == "samsung" ? SamsungTrailer() : ([], []);
+ var length = video.Length + after.Length;
+ var xmp = form == "microvideo"
+ ? $"<x:xmpmeta xmlns:x='adobe:ns:meta/' xmlns:c='http://ns.google.com/photos/1.0/camera/' c:MicroVideo='1' c:MicroVideoVersion='1' c:MicroVideoOffset='{length}'/>"
+ : MotionXmp(length, elements: form == "elements");
+ var path = Path.Combine(fx.NewFolder(), name);
+ await File.WriteAllBytesAsync(path, [.. JpegWithXmp(Jpeg(), xmp), .. before, .. video, .. after], TestContext.Current.CancellationToken);
+ return path;
}
private static string Output(ConversionJob job)
@@ -42,221 +118,309 @@ public class LivePhotoTests(EngineFixture fx) : IClassFixture<EngineFixture>
return Assert.Single(job.Outputs);
}
+ private static async Task<MediaInfo> ProbeAsync(string path) =>
+ await MediaInfo.ProbeAsync(Tools().Ffprobe, path, TestContext.Current.CancellationToken);
+
[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)
+ [InlineData("attributes", true)]
+ [InlineData("attributes", false)]
+ [InlineData("elements", true)]
+ [InlineData("samsung", true)]
+ [InlineData("microvideo", true)]
+ public async Task Android_motion_photo_jpeg_gives_its_video_and_sound(string form, 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);
+ var photo = await MotionJpegAsync("PXL_20260101_120000000.MP.jpg", form, audio);
+ Assert.Equal("jpg", FormatRegistry.Detect(photo)!.Id);
+ var original = await File.ReadAllBytesAsync(photo, TestContext.Current.CancellationToken);
+
+ var movie = Output(await fx.ConvertAsync([photo], Extract()));
+ Assert.Equal(".mp4", Path.GetExtension(movie));
+ var info = await ProbeAsync(movie);
+ Assert.Equal(160, info.Video!.Width);
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));
+ Assert.InRange(info.Duration!.Value.TotalSeconds, 1.9, 2.1);
+ Assert.Equal(original, await File.ReadAllBytesAsync(photo, 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 Samsung_trailer_after_the_video_is_left_out()
+ {
+ var photo = await MotionJpegAsync("20260101_120000.jpg", "samsung");
+ var (_, after) = SamsungTrailer();
+ await using var file = File.OpenRead(photo);
+ var video = MotionPhoto.FindVideo(file)!.Value;
+ Assert.Equal(file.Length - after.Length, video.Offset + video.Length);
}
[Fact]
- public async Task A_renamed_android_photo_still_extracts_and_plain_jpg_does_not_silently_become_motion()
+ public async Task Heic_motion_photo_reads_its_mpvd_box_even_with_a_trailer_after_it()
{
- 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 } });
+ var video = await VideoAsync();
+ var (_, after) = SamsungTrailer();
+ var path = Path.Combine(fx.NewFolder(), "20260101_120000.heic");
+ await File.WriteAllBytesAsync(path, [.. Box("ftyp", "heic\0\0\0\0mif1heic"u8.ToArray()), .. Box("meta", new byte[12]),
+ .. Box("mpvd", video), .. after], TestContext.Current.CancellationToken);
+
+ await using (var file = File.OpenRead(path))
+ Assert.Equal(video.Length, MotionPhoto.FindVideo(file)!.Value.Length);
+ var movie = Output(await fx.ConvertAsync([path], Extract("mov")));
+ Assert.NotNull((await ProbeAsync(movie)).Audio);
+ }
+
+ /// <summary>IMG_0001.JPG with Apple's maker note and IMG_0001.MOV with the same content identifier.</summary>
+ private async Task<(string Photo, string Movie)> ApplePairAsync(string folder, string movieId = LiveId, string? xmp = null)
+ {
+ var photo = Path.Combine(folder, "IMG_0001.JPG");
+ var jpeg = Jpeg(makerNote: AppleMakerNote(LiveId));
+ await File.WriteAllBytesAsync(photo, xmp is null ? jpeg : JpegWithXmp(jpeg, xmp), TestContext.Current.CancellationToken);
+ var movie = Path.Combine(folder, "IMG_0001.MOV");
+ await File.WriteAllBytesAsync(movie, await VideoAsync(extension: "mov", extra:
+ ["-metadata", $"com.apple.quicktime.content.identifier={movieId}", "-movflags", "use_metadata_tags"]),
+ TestContext.Current.CancellationToken);
+ return (photo, movie);
+ }
+
+ [Fact]
+ public async Task Iphone_photo_gives_the_mov_next_to_it_only_with_the_same_identifier()
+ {
+ var (photo, movie) = await ApplePairAsync(fx.NewFolder());
+ Assert.Equal(LiveId, AppleLivePhoto.ImageIdentifier(photo), StringComparer.OrdinalIgnoreCase);
+ Assert.Equal(LiveId, AppleLivePhoto.MovieIdentifier(movie), StringComparer.OrdinalIgnoreCase);
+ var output = Output(await fx.ConvertAsync([photo], Extract()));
+ Assert.NotNull((await ProbeAsync(output)).Audio);
+
+ // XMP that can't be read (here a DTD) doesn't hide the MOV.
+ var (hostile, _) = await ApplePairAsync(fx.NewFolder(), xmp: "<!DOCTYPE x [<!ENTITY a 'b'>]><x>&a;</x>");
+ Output(await fx.ConvertAsync([hostile], Extract()));
+
+ // A same-named video of another Live Photo is not this photo's.
+ var (other, _) = await ApplePairAsync(fx.NewFolder(), Guid.NewGuid().ToString("D"));
+ var failed = await fx.ConvertAsync([other], Extract());
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)
+ [Fact]
+ public async Task Overwrite_never_writes_over_the_live_photos_own_movie()
{
- 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);
+ var (photo, movie) = await ApplePairAsync(fx.NewFolder());
+ var original = await File.ReadAllBytesAsync(movie, TestContext.Current.CancellationToken);
+
+ var output = Output(await fx.ConvertAsync([photo], Extract("mov", ConflictPolicy.Overwrite)));
+ Assert.Equal(Path.Combine(Path.GetDirectoryName(photo)!, "IMG_0001 (2).mov"), output);
+ Assert.Equal(original, await File.ReadAllBytesAsync(movie, TestContext.Current.CancellationToken));
+ Assert.NotNull((await ProbeAsync(output)).Video);
+ // Once more: the numbered file is the output now, and is overwritten.
+ Assert.Equal(output, Output(await fx.ConvertAsync([photo], Extract("mov", ConflictPolicy.Overwrite))));
+ Assert.Equal(original, await File.ReadAllBytesAsync(movie, TestContext.Current.CancellationToken));
}
[Fact]
- public void Photo_edges_are_direct_and_existing_routes_stay_still_images()
+ public async Task A_cancelled_extraction_leaves_the_file_it_would_replace()
{
- 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"));
+ // Long enough to be cancelled while FFmpeg encodes (VP9): the output is written in the work directory meanwhile.
+ var video = await VideoAsync(seconds: 60, size: "1280x720", extra: ["-preset", "ultrafast"]);
+ var folder = fx.NewFolder();
+ var photo = Path.Combine(folder, "long.jpg");
+ await File.WriteAllBytesAsync(photo, [.. JpegWithXmp(Jpeg(), MotionXmp(video.Length)), .. video], TestContext.Current.CancellationToken);
+ var existing = Path.Combine(folder, "long.webm");
+ await File.WriteAllTextAsync(existing, "the user's own file", TestContext.Current.CancellationToken);
+
+ using var cancellation = new CancellationTokenSource();
+ cancellation.CancelAfter(TimeSpan.FromSeconds(30)); // in case no progress arrives at all
+ var converter = new FfmpegConverter();
+ converter.GetStatus();
+ var step = new ConversionStep(photo, "jpg", "webm",
+ new Preset { TargetFormat = "webm", Media = { ExtractMotionPhoto = true, Quality = MediaQuality.High } },
+ new FixedOutput(existing), fx.NewFolder(), MotionPhoto: true);
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
+ converter.ConvertAsync(step, new CancelOnProgress(cancellation), cancellation.Token));
+ Assert.Equal("the user's own file", await File.ReadAllTextAsync(existing, TestContext.Current.CancellationToken));
}
- [Theory]
- [InlineData("livp")]
- [InlineData("motionphoto")]
- public async Task Existing_outputs_obey_overwrite_and_skip(string format)
+ private sealed class FixedOutput(string path) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null) => path;
+ }
+
+ /// <summary>Cancels once FFmpeg reports progress (synchronously: Progress&lt;T&gt; would post to the thread pool).</summary>
+ private sealed class CancelOnProgress(CancellationTokenSource cancellation) : IProgress<double>
{
- 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")
+ public void Report(double value)
{
- using var zip = ZipFile.OpenRead(second);
- Assert.Equal(2, zip.Entries.Count);
+ if (value > 0.05)
+ cancellation.Cancel();
}
- 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()
+ private async Task<string> LivpAsync(string movieId = LiveId, string prefix = "")
{
- 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))
+ var path = Path.Combine(fx.NewFolder(), "IMG_3218.livp");
+ var movie = await VideoAsync(extension: "mov", extra:
+ ["-metadata", $"com.apple.quicktime.content.identifier={movieId}", "-movflags", "use_metadata_tags"]);
+ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);
+ // As iCloud names them; a macOS resource fork next to them is no second video.
+ foreach (var (name, data) in new[]
+ {
+ ("IMG_3218.JPG.jpeg", Jpeg(240, 180, AppleMakerNote(LiveId))),
+ ("IMG_3218.JPG.mov", movie),
+ ("__MACOSX/._IMG_3218.JPG.mov", new byte[] { 0, 5, 22, 7 }),
+ })
{
- 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);
- }
+ await using var entry = zip.CreateEntry(prefix + name, CompressionLevel.NoCompression).Open();
+ await entry.WriteAsync(data, TestContext.Current.CancellationToken);
}
+ return path;
+ }
+
+ [Fact]
+ public async Task Livp_gives_its_video_without_the_option_and_its_photo_as_a_picture()
+ {
+ var livp = await LivpAsync();
+ Assert.Equal("livp", FormatRegistry.Detect(livp)!.Id);
+ var movie = Output(await fx.ConvertAsync([livp], new Preset { TargetFormat = "mp4" }));
+ Assert.InRange((await ProbeAsync(movie)).Duration!.Value.TotalSeconds, 1.9, 2.1);
+
+ var png = Output(await fx.ConvertAsync([livp], new Preset { TargetFormat = "png" }));
+ using var still = new MagickImage(png);
+ Assert.Equal((240u, 180u), (still.Width, still.Height));
+ }
+
+ [Fact]
+ public async Task Livp_pair_comes_from_the_package_and_its_names_never_become_paths()
+ {
+ // Identifiers that don't match are only logged: the package says which photo and video belong together.
+ var livp = await LivpAsync(Guid.NewGuid().ToString("D"), prefix: "../../outside/");
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);
+ var (video, companion) = await LivePhotoSource.ExtractAsync(livp, "livp", work,
+ Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, TestContext.Current.CancellationToken);
+ Assert.Null(companion);
+ Assert.Equal(work, Path.GetDirectoryName(video));
+ Assert.Single(Directory.GetFiles(work));
Assert.False(Directory.Exists(Path.Combine(fx.Root, "outside")));
+
+ var two = Path.Combine(fx.NewFolder(), "two.livp");
+ using (var zip = ZipFile.Open(two, ZipArchiveMode.Create))
+ {
+ zip.CreateEntry("a.mov").Open().Dispose();
+ zip.CreateEntry("b.mov").Open().Dispose();
+ }
+ var failed = await fx.ConvertAsync([two], new Preset { TargetFormat = "mp4" });
+ Assert.Equal("error.no_motion_photo", failed.Files.Single().ErrorKey);
+ Assert.Null(failed.Files.Single().ErrorDetail);
+ }
+
+ [Fact]
+ public async Task Motion_photo_is_an_ordinary_jpg_without_the_option()
+ {
+ var photo = await MotionJpegAsync("PXL_20260101_120000000.MP.jpg");
+ using (var png = new MagickImage(Output(await fx.ConvertAsync([photo], new Preset { TargetFormat = "png" }))))
+ Assert.Equal((320u, 200u), (png.Width, png.Height));
+ // A video of the still picture, as for any photo.
+ var still = Output(await fx.ConvertAsync([photo], new Preset { TargetFormat = "mp4" }));
+ Assert.Null((await ProbeAsync(still)).Audio);
+
+ var plain = EngineFixture.MakeImage(fx.NewFolder(), "plain.jpg", MagickFormat.Jpeg);
+ var failed = await fx.ConvertAsync([plain], Extract());
+ Assert.Equal("error.no_motion_photo", failed.Files.Single().ErrorKey);
}
[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));
+ [InlineData("gif", MagickFormat.Gif)]
+ [InlineData("png", MagickFormat.Png)]
+ [InlineData("webp", MagickFormat.WebP)]
+ public async Task The_option_leaves_other_pictures_to_their_usual_route(string format, MagickFormat magick)
+ {
+ Tools();
+ var picture = EngineFixture.MakeImage(fx.NewFolder(), "picture." + format, magick);
+ Assert.False(Extract().ExtractsMotionOf(format));
+ Assert.NotNull((await ProbeAsync(Output(await fx.ConvertAsync([picture], Extract())))).Video);
+ }
[Fact]
- public async Task Missing_mismatched_and_multiple_archive_pairs_are_rejected()
+ public void Motion_edges_are_taken_only_when_asked_for()
{
- 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));
+ var planner = fx.Catalog.CreatePlanner(["ffmpeg"]);
+ var step = Assert.Single(planner.Plan("jpg", "mp4", motionPhoto: true)!.Steps);
+ Assert.True(step.MotionPhoto);
+ Assert.All(planner.Plan("jpg", "mp4")!.Steps, s => Assert.False(s.MotionPhoto));
+ Assert.Equal(2, planner.Plan("jpg", "mp4")!.Steps.Count);
+ Assert.Null(planner.Plan("png", "mp4", motionPhoto: true));
+ Assert.Null(planner.Plan("jpg", "webm", motionPhoto: true));
+ Assert.Null(planner.Plan("jpg", "png", motionPhoto: true));
+ Assert.Equal("magick", Assert.Single(planner.Plan("livp", "png")!.Steps).Converter.Id);
+ Assert.Equal("jpg", FormatRegistry.Detect("PXL_20260101.MP.jpg")!.Id);
+ Assert.True(new Preset { TargetFormat = "mov" }.ExtractsMotionOf("livp"));
+ Assert.False(new Preset { TargetFormat = "mov" }.ExtractsMotionOf("jpg"));
}
[Fact]
- public async Task Xmp_is_namespace_aware_and_stale_or_hostile_metadata_is_rejected()
+ public async Task Stale_disabled_or_hostile_metadata_is_no_motion_photo()
{
- 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));
+ var jpeg = Jpeg();
+ var video = Box("ftyp", "isom\0\0\0\0isom"u8.ToArray());
+ // The XMP says there's a video, but an editor rewrote the picture without it.
+ using var stale = new MemoryStream(JpegWithXmp(jpeg, MotionXmp(video.Length)));
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());
+ // A video without a movie header is not one either.
+ using var headless = new MemoryStream([.. JpegWithXmp(jpeg, MotionXmp(video.Length)), .. video]);
+ Assert.Throws<InvalidDataException>(() => MotionPhoto.FindVideo(headless));
+ using var disabled = new MemoryStream([.. JpegWithXmp(jpeg, MotionXmp(video.Length).Replace("GCamera:MotionPhoto=\"1\"", "GCamera:MotionPhoto=\"0\"")), .. video]);
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>"));
+ // An XMP packet padded with NUL bytes after its end (as some editors write it) is read.
+ byte[] movie = [.. video, .. Box("moov", new byte[8])];
+ using var padded = new MemoryStream([.. JpegWithXmp(jpeg, MotionXmp(movie.Length) + "\0\0\0"), .. movie]);
+ Assert.Equal(movie.Length, MotionPhoto.FindVideo(padded)!.Value.Length);
+ using var hostile = new MemoryStream(JpegWithXmp(jpeg, "<!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)];
+ var path = Path.Combine(fx.NewFolder(), "hostile.jpg");
+ await File.WriteAllBytesAsync(path, hostile.ToArray(), TestContext.Current.CancellationToken);
+ var job = await fx.ConvertAsync([path], Extract());
+ Assert.Equal("error.no_motion_photo", job.Files.Single().ErrorKey);
+ Assert.Null(job.Files.Single().ErrorDetail);
}
[Fact]
public void Invalid_and_extended_media_boxes_are_bounded()
{
- using var beyond = new MemoryStream([.. MovieBoxes.U32(100), .. "mpvd"u8.ToArray()]);
+ using var beyond = new MemoryStream([.. 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)]);
+ using var huge = new MemoryStream([.. U32(1), .. "mpvd"u8.ToArray(), .. 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);
+ byte[] movie = [.. Box("ftyp", "isom\0\0\0\0isom"u8.ToArray()), .. Box("moov", new byte[8])];
+ using var large = new MemoryStream([.. Box("ftyp", "heic\0\0\0\0heic"u8.ToArray()), .. U32(1), .. "mpvd"u8.ToArray(), .. U64((ulong)movie.Length + 16), .. movie]);
+ Assert.Equal(movie.Length, MotionPhoto.FindVideo(large)!.Value.Length);
+ }
+
+ /// <summary>Apple's maker note with only tag 17, the content identifier (offsets count from the note's start).</summary>
+ private static byte[] AppleMakerNote(string identifier)
+ {
+ var id = Encoding.ASCII.GetBytes(identifier.ToUpperInvariant() + "\0");
+ return [.. "Apple iOS\0"u8.ToArray(), .. U16(1), .. "MM"u8.ToArray(), .. U16(1),
+ .. U16(17), .. U16(2), .. U32((uint)id.Length), .. U32(32), .. U32(0), .. id];
+ }
+
+ private static byte[] Box(string type, byte[] payload) =>
+ [.. U32((uint)(payload.Length + 8)), .. Encoding.Latin1.GetBytes(type), .. payload];
+
+ private static byte[] U16(ushort value)
+ {
+ var data = new byte[2];
+ BinaryPrimitives.WriteUInt16BigEndian(data, value);
+ return data;
+ }
+
+ private static byte[] U32(uint value)
+ {
+ var data = new byte[4];
+ BinaryPrimitives.WriteUInt32BigEndian(data, value);
+ return data;
+ }
+
+ private static byte[] U64(ulong value)
+ {
+ var data = new byte[8];
+ BinaryPrimitives.WriteUInt64BigEndian(data, value);
+ return data;
}
}