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.

Make iPhone Live Photos and Android Motion Photos from a video

KnifeLemonb2e0ad0208fd
diff --git a/README.ko.md b/README.ko.md
index 50eee0bf..a066c6ae 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -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), 아이폰 라이브 포토(LIVP)는 읽기 | 위 형식끼리(HEIC⁵), PDF, SVG(벡터화), 크기 조정, 흑백; 라이브/모션 포토(아이폰, 안드로이드) → 그 동영상(MP4, MOV⁵) |
+| **이미지**: 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; OFD(중국 전자세금계산서·공문서)는 읽기 · 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 8eefd1d8..a6298969 100644
--- a/README.md
+++ b/README.md
@@ -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), iPhone Live Photo (LIVP) read | any of these (HEIC⁵), PDF, SVG (traced), resized, grayscale; Live/Motion Photos (iPhone, Android) → their video (MP4, MOV⁵) |
+| **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⁵), and a video → Live Photo (iPhone) or Motion Photo (Android)⁵, experimental |
| **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; OFD (Chinese e-invoices, official documents) read · 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.zh-CN.md b/README.zh-CN.md
index d14b62bc..78bc1e73 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -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)、iPhone 实况照片(LIVP)仅读取 | 上述格式互转(HEIC⁵)、PDF、SVG(描摹)、缩放、灰度;实况/动态照片(iPhone、安卓)→ 其中的视频(MP4、MOV⁵) |
+| **图片**: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⁵),以及视频 → 实况照片(iPhone)或动态照片(安卓)⁵(实验功能) |
| **矢量图**: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;OFD(电子发票、公文)仅读取 · 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/docs/ENGINES.md b/docs/ENGINES.md
index b351bcd6..d5d10ff6 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -32,7 +32,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, Live / Motion Photos → their video, 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, a clip of a video → an iPhone Live Photo or Android Motion Photo (experimental), 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
@@ -215,6 +215,8 @@ pinned source in `build/build-linux-native.py` like rhwp (PR #113 did this for S
- **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).
+- **Live / Motion Photos from a video** (JPG and HEIC targets) are FFmpeg's: the clip and the photo's frame come from
+ it, ImageMagick or the HEIC writer only encode that frame (see *Making 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
@@ -1333,6 +1335,49 @@ Same-format edges exist too, so "MP4 720p" works on MP4 files and "MP3 128k" on
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).
+- **Making Live / Motion Photos** (experimental until confirmed on phones; *A video becomes* on a JPG or HEIC preset,
+ `MediaOptions.LivePhoto`; the presets "Live Photo (iPhone)" and "Motion Photo (Android)", JPG, on no donut, added in
+ settings schema 31): a short clip of a video becomes a moving photo instead of one still frame.
+ - Routes: the live edges (`ConversionEdge.LivePhoto`, every video → JPG and HEIC) are taken only when
+ `Preset.MakesLivePhotoOf` the file (an iPhone Live Photo as JPG or HEIC, a Motion Photo as JPG,
+ `MediaOptions.LivePhotoTargets`), and then as the whole route (`RoutePlanner.Plan(from, to, livePhoto: true)`); "Save
+ every frame" is ignored meanwhile. Other files and targets convert as usual.
+ - The clip (`Media/LivePhotoWriter.cs`): *Clip start*, *Clip length* (0.5 to 5 s, 3 by default, shorter when the
+ video ends sooner; a start past the end is refused) and *Photo at* (seconds into the clip, 1.5 by default, the last
+ frame at most). FFmpeg encodes it at 30 fps, upright (the phone's rotation is applied to the pixels), scaled to at
+ most 1440 px on the shorter side (or the preset's maximum height), 8-bit 4:2:0 H.264 (HEVC when the preset asks,
+ tagged `hvc1`), the sound as AAC (mono or stereo, 44.1 or 48 kHz) unless the preset removes it. HDR (PQ or HLG) is
+ tone-mapped to SDR BT.709 with zscale; an FFmpeg without zscale refuses HDR with a message. The photo is the same
+ frame at the video's full size, picked by the same 30 fps timing (`select` on the frame number the clip really has,
+ counted from its `stsz`), encoded at the preset's image quality.
+ - **iPhone Live Photo**: a JPG (or HEIC) and a MOV with the same name and one content identifier (a new upper-case
+ UUID), the pair Photos imports as a Live Photo. The photo carries it in Apple's maker note (Exif `MakerNote`,
+ "Apple iOS" big-endian, tag 17, ASCII), HEIC through the HEIC writer's Exif item. The MOV (QuickTime, `qt ` brand)
+ gets, as an iPhone writes them: `com.apple.quicktime.content.identifier` in a movie-level `meta` (plain container,
+ `mdta` handler, `keys`, `ilst` with a UTF-8 `data` item), and a timed metadata track for the still: track flags 0xF,
+ `tref/cdsc` to the video track, a `mhlr/meta` handler, `gmhd`, an alias data reference, a `mebx` sample entry whose
+ key 1 is `mdta` + `com.apple.quicktime.still-image-time` typed as a signed 8-bit integer (well-known type 65), one
+ 9-byte sample (the item, value -1) of one tick at the movie's timescale, placed by an empty edit at the photo's
+ time (`AppleLivePhoto.TagMovie`). FFmpeg leaves the movie header at the end, so only that header is rewritten: the
+ sample goes into a small `mdat` where it was, and no chunk offset moves. Not written: the other timed metadata of
+ an iPhone (live-photo-info, the still's transform, video orientation) and its camera keys, which Photos does not
+ need to pair the files.
+ - **Android Motion Photo**: one `NAME.MP.jpg` (the name a Pixel gives them): the JPEG, then the clip as MP4 appended,
+ ending the file. Its XMP APP1 (after the JFIF APP0 and an Exif APP1) is laid out as a Pixel's:
+ `GCamera:MotionPhoto` 1, `MotionPhotoVersion` 1, `MotionPhotoPresentationTimestampUs` (the photo's time in the
+ clip), and a `Container:Directory` of the primary JPEG and the video (`video/mp4`, `MotionPhoto`, its length,
+ `Padding` 0); the older `GCamera:MicroVideo` properties (the same length as `MicroVideoOffset`) are written too for
+ older Google Photos (`MotionPhoto.WriteAsync`). Samsung's own SEF trailer is not written.
+ - Expected to work, to be confirmed on devices: Photos on iPhone, iPad and Mac with both files imported together
+ (iCloud Photos, AirDrop of both, Image Capture or Photos on a Mac; a single file sent through a messenger loses the
+ pairing), Google Photos on Android, iPhone and the web, and galleries that read Google's Motion Photo XMP (Samsung
+ Gallery on recent One UI is likely but untested). Not expected: galleries that only know their maker's own format.
+ - Everything is written in the work directory and moved into place at the end, first next to its target under a
+ hidden name, then renamed over it: a failed or cancelled run never touches an existing file. The pair keeps one
+ name: when the MOV's name is taken (another file, or the video being converted, which is never written over) both
+ take the next number (`clip (2).jpg` + `clip (2).mov`); a MOV is only written over together with the photo
+ "overwrite" replaces; "skip" skips the pair when the photo exists. Filee's own extraction (above) reads both kinds
+ back.
- 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/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index fa7fabae..5a2df519 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -78,6 +78,8 @@
"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.live_photo_start": "The clip starts after the end of this video. Choose an earlier \"Clip start\"",
+ "error.live_photo_hdr": "This FFmpeg has no zscale filter, so this HDR video can't become a Live / Motion Photo. Filee's FFmpeg download has 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",
@@ -92,6 +94,7 @@
"error.geo_unsupported_shape": "This kind of shape isn't supported",
"error.geo_too_large": "The Shapefile would pass the format's 2 GB limit",
"notice.pdf_not_smaller": "Couldn't make it smaller, so it was copied as it is",
+ "notice.live_photo_pair": "Saved as a photo and a MOV with the same name. Import both together (iCloud Photos, AirDrop or Photos on a Mac) to get a Live Photo",
"notice.geo_datum_assumed": "The datum isn't WGS 84; positions were converted as if it were and can be off by up to hundreds of metres",
"notice.geo_gpx_lossy": "GPX holds only points, routes and tracks with a few fields: other attributes were left out and polygons became tracks",
"notice.geo_text_cut": "Some text was longer than a Shapefile field allows (254 bytes) and was cut",
@@ -191,6 +194,8 @@
"preset.extract_frames_png": "Extract frames (PNG)",
"preset.extract_frames_jpg": "Extract frames (JPG)",
"preset.extract_motion": "Extract Live Photo video",
+ "preset.live_photo_iphone": "Live Photo (iPhone)",
+ "preset.motion_photo_android": "Motion Photo (Android)",
"format.folder": "Folder",
"format.category.Image": "Image",
@@ -443,6 +448,18 @@
"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.group.live_photo": "Live / Motion Photo",
+ "presets.live_photo": "A video becomes",
+ "presets.live_photo.None": "One still frame",
+ "presets.live_photo.Apple": "Live Photo (iPhone): photo + MOV",
+ "presets.live_photo.Android": "Motion Photo (Android): one JPG",
+ "presets.live_photo_hint.apple": "A short clip becomes a photo and a MOV with the same name and a shared Live Photo identifier. Import both into Photos together. The video is at most 1440 px on its shorter side. Experimental: not yet confirmed on every iPhone.",
+ "presets.live_photo_hint.android": "A short clip becomes one JPG (NAME.MP.jpg) with the video inside, as Pixel phones save Motion Photos, for Google Photos and other galleries that read them. The video is at most 1440 px on its shorter side. Experimental: not yet confirmed on every phone.",
+ "presets.live_photo_start": "Clip start (s)",
+ "presets.live_photo_length": "Clip length (s)",
+ "presets.live_photo_cover": "Photo at (s)",
+ "presets.live_photo_quality": "Photo quality",
+ "presets.live_photo_video_quality": "Video quality",
"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 bbd6ee2e..b629b590 100644
--- a/src/Filee.App/Assets/i18n/es.json
+++ b/src/Filee.App/Assets/i18n/es.json
@@ -72,6 +72,8 @@
"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.live_photo_start": "El clip empieza después del final de este vídeo. Elige un «Inicio del clip» anterior",
+ "error.live_photo_hdr": "Este FFmpeg no tiene el filtro zscale, así que este vídeo HDR no puede convertirse en Live Photo ni Motion Photo. El FFmpeg que descarga Filee lo tiene",
"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",
@@ -86,6 +88,7 @@
"error.geo_unsupported_shape": "Este tipo de forma no es compatible",
"error.geo_too_large": "El Shapefile superaría el límite de 2 GB del formato",
"notice.pdf_not_smaller": "No se pudo reducir su tamaño, por lo que se copió tal cual",
+ "notice.live_photo_pair": "Guardado como una foto y un MOV con el mismo nombre. Impórtalos juntos (Fotos de iCloud, AirDrop o Fotos en un Mac) para obtener una Live Photo",
"notice.geo_datum_assumed": "El datum no es WGS 84; las posiciones se convirtieron como si lo fuera y pueden desviarse hasta cientos de metros",
"notice.geo_gpx_lossy": "GPX solo guarda puntos, rutas y tracks con pocos campos: se omitieron los demás atributos y los polígonos pasaron a ser tracks",
"notice.geo_text_cut": "Parte del texto superaba la longitud de campo de Shapefile (254 bytes) y se recortó",
@@ -181,6 +184,8 @@
"preset.extract_frames_png": "Extraer fotogramas (PNG)",
"preset.extract_frames_jpg": "Extraer fotogramas (JPG)",
"preset.extract_motion": "Extraer vídeo de Live Photo",
+ "preset.live_photo_iphone": "Live Photo (iPhone)",
+ "preset.motion_photo_android": "Motion Photo (Android)",
"format.folder": "Carpeta",
"format.category.Image": "Imagen",
"format.category.Pdf": "PDF",
@@ -428,6 +433,18 @@
"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.group.live_photo": "Live Photo / Motion Photo",
+ "presets.live_photo": "Un vídeo se convierte en",
+ "presets.live_photo.None": "Un fotograma fijo",
+ "presets.live_photo.Apple": "Live Photo (iPhone): foto + MOV",
+ "presets.live_photo.Android": "Motion Photo (Android): un JPG",
+ "presets.live_photo_hint.apple": "Un clip corto se convierte en una foto y un MOV con el mismo nombre y un identificador de Live Photo común. Impórtalos juntos en Fotos. El vídeo mide como máximo 1440 px en su lado corto. Experimental: aún no confirmado en todos los iPhone.",
+ "presets.live_photo_hint.android": "Un clip corto se convierte en un solo JPG (NOMBRE.MP.jpg) con el vídeo dentro, como guardan los teléfonos Pixel sus Motion Photos, para Google Fotos y otras galerías que las leen. El vídeo mide como máximo 1440 px en su lado corto. Experimental: aún no confirmado en todos los teléfonos.",
+ "presets.live_photo_start": "Inicio del clip (s)",
+ "presets.live_photo_length": "Duración del clip (s)",
+ "presets.live_photo_cover": "Foto en (s)",
+ "presets.live_photo_quality": "Calidad de la foto",
+ "presets.live_photo_video_quality": "Calidad del vídeo",
"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 e9768061..40568891 100644
--- a/src/Filee.App/Assets/i18n/hi.json
+++ b/src/Filee.App/Assets/i18n/hi.json
@@ -72,6 +72,8 @@
"error.too_many_frames": "तस्वीरों के रूप में सहेजने के लिए बहुत ज़्यादा फ़्रेम हैं, \"हर Nवाँ फ़्रेम\" बढ़ाएँ",
"error.not_enough_space": "तस्वीरों के लिए डिस्क पर पर्याप्त खाली जगह नहीं है",
"error.no_motion_photo": "इस फ़ोटो में ऐसा कोई वीडियो नहीं है जिसे Filee पढ़ सके (Android मोशन फ़ोटो, या पास में अपनी MOV फ़ाइल वाली iPhone लाइव फ़ोटो)",
+ "error.live_photo_start": "क्लिप इस वीडियो के ख़त्म होने के बाद शुरू होती है। \"क्लिप की शुरुआत\" पहले चुनें",
+ "error.live_photo_hdr": "इस FFmpeg में zscale फ़िल्टर नहीं है, इसलिए यह HDR वीडियो लाइव / मोशन फ़ोटो नहीं बन सकता। Filee से डाउनलोड होने वाले FFmpeg में यह है",
"error.rhwp_timeout": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका",
"error.rhwp_timeout_calibre": "rhwp इस लंबे दस्तावेज़ को समय पर पूरा नहीं कर सका। ई-बुक के लिए, सेटिंग्स → इंजन में Calibre को HWPX writer के ऊपर ले जाएँ, तब Calibre PDF बहुत तेज़ी से बनाएगा",
"error.needs_shaping": "इस लिपि को सही ढंग से कन्वर्ट करने के लिए LibreOffice चाहिए। इसे सेटिंग्स → इंजन में इंस्टॉल करें",
@@ -86,6 +88,7 @@
"error.geo_unsupported_shape": "इस तरह का आकार समर्थित नहीं है",
"error.geo_too_large": "Shapefile फ़ॉर्मैट की 2 GB सीमा से बड़ी हो जाएगी",
"notice.pdf_not_smaller": "इसे छोटा नहीं किया जा सका, इसलिए जैसा है वैसा ही कॉपी कर दिया गया",
+ "notice.live_photo_pair": "एक ही नाम की फ़ोटो और MOV के रूप में सहेजा गया। लाइव फ़ोटो पाने के लिए दोनों को साथ में इम्पोर्ट करें (iCloud Photos, AirDrop या Mac पर Photos)",
"notice.geo_datum_assumed": "डेटम WGS 84 नहीं है। स्थितियाँ ऐसे कन्वर्ट की गईं मानो वह WGS 84 हो, इसलिए वे कुछ सौ मीटर तक खिसक सकती हैं",
"notice.geo_gpx_lossy": "GPX में केवल पॉइंट, रूट और ट्रैक कुछ फ़ील्ड के साथ रहते हैं: बाकी एट्रिब्यूट छोड़ दिए गए और पॉलीगॉन ट्रैक बन गए",
"notice.geo_text_cut": "कुछ टेक्स्ट Shapefile फ़ील्ड की सीमा (254 बाइट) से लंबा था और काट दिया गया",
@@ -181,6 +184,8 @@
"preset.extract_frames_png": "फ़्रेम निकालें (PNG)",
"preset.extract_frames_jpg": "फ़्रेम निकालें (JPG)",
"preset.extract_motion": "लाइव फ़ोटो वीडियो निकालें",
+ "preset.live_photo_iphone": "लाइव फ़ोटो (iPhone)",
+ "preset.motion_photo_android": "मोशन फ़ोटो (Android)",
"format.folder": "फ़ोल्डर",
"format.category.Image": "इमेज",
"format.category.Pdf": "PDF",
@@ -428,6 +433,18 @@
"presets.frame_estimate": "30 fps के एक मिनट के वीडियो से {0} तस्वीरें बनती हैं, प्रति वीडियो अधिकतम {1}।",
"presets.extract_motion_photo": "लाइव/मोशन फ़ोटो का वीडियो निकालें",
"presets.extract_motion_photo_hint": "फ़ोटो उसके साथ सहेजा गया वीडियो बन जाती है: Android मोशन फ़ोटो के अंदर वाला वीडियो, या iPhone लाइव फ़ोटो के पास रखी उसी नाम की MOV फ़ाइल।\nबाकी तस्वीरें स्थिर तस्वीर का वीडियो बनती हैं।",
+ "presets.group.live_photo": "लाइव / मोशन फ़ोटो",
+ "presets.live_photo": "वीडियो बनता है",
+ "presets.live_photo.None": "एक स्थिर फ़्रेम",
+ "presets.live_photo.Apple": "लाइव फ़ोटो (iPhone): फ़ोटो + MOV",
+ "presets.live_photo.Android": "मोशन फ़ोटो (Android): एक JPG",
+ "presets.live_photo_hint.apple": "एक छोटी क्लिप एक ही नाम और एक ही लाइव फ़ोटो पहचानकर्ता वाली फ़ोटो और MOV बनती है। दोनों को साथ में Photos में इम्पोर्ट करें। वीडियो की छोटी भुजा अधिकतम 1440 px होती है। प्रयोगात्मक: अभी हर iPhone पर पुष्टि नहीं हुई है।",
+ "presets.live_photo_hint.android": "एक छोटी क्लिप अंदर वीडियो वाली एक JPG (नाम.MP.jpg) बनती है, जैसे Pixel फ़ोन मोशन फ़ोटो सहेजते हैं, Google Photos और इन्हें पढ़ने वाली दूसरी गैलरी के लिए। वीडियो की छोटी भुजा अधिकतम 1440 px होती है। प्रयोगात्मक: अभी हर फ़ोन पर पुष्टि नहीं हुई है।",
+ "presets.live_photo_start": "क्लिप की शुरुआत (से.)",
+ "presets.live_photo_length": "क्लिप की लंबाई (से.)",
+ "presets.live_photo_cover": "फ़ोटो का समय (से.)",
+ "presets.live_photo_quality": "फ़ोटो की क्वालिटी",
+ "presets.live_photo_video_quality": "वीडियो की क्वालिटी",
"presets.ico_sizes": "आइकन आकार",
"presets.group.pdf": "PDF",
"presets.merge": "सभी फ़ाइलों को एक PDF में मर्ज करें",
diff --git a/src/Filee.App/Assets/i18n/ja.json b/src/Filee.App/Assets/i18n/ja.json
index 481cc786..9e334220 100644
--- a/src/Filee.App/Assets/i18n/ja.json
+++ b/src/Filee.App/Assets/i18n/ja.json
@@ -72,6 +72,8 @@
"error.too_many_frames": "画像として保存するフレーム数が多すぎます。「Nフレームごと」の値を大きくしてください",
"error.not_enough_space": "画像を保存するための空き容量が不足しています",
"error.no_motion_photo": "この写真には、Fileeが読み取れる動画がありません(Androidのモーションフォト、または隣にMOVがあるiPhoneのLive Photo)",
+ "error.live_photo_start": "クリップの開始位置が動画の終わりより後です。「クリップの開始」をもっと前にしてください",
+ "error.live_photo_hdr": "このFFmpegにはzscaleフィルターがないため、HDR動画をLive Photo/モーションフォトにできません。FileeからダウンロードするFFmpegにはあります",
"error.rhwp_timeout": "文書が長いため、rhwpが制限時間内に処理を終えられませんでした",
"error.rhwp_timeout_calibre": "文書が長いため、rhwpが制限時間内に処理を終えられませんでした。電子書籍の場合は、「設定」→「変換エンジン」でCalibreを「HWPX writer」より上に移動してください。CalibreならPDFを大幅に速く作成できます",
"error.needs_shaping": "この文字体系の文書を正しく変換するにはLibreOfficeが必要です。「設定」→「変換エンジン」でインストールしてください",
@@ -86,6 +88,7 @@
"error.geo_unsupported_shape": "この種類の図形には対応していません",
"error.geo_too_large": "Shapefile形式の上限(2 GB)を超えてしまいます",
"notice.pdf_not_smaller": "サイズを小さくできなかったため、元のままコピーしました",
+ "notice.live_photo_pair": "同じ名前の写真とMOVとして保存しました。両方を一緒に取り込むと(iCloud写真、AirDrop、Macの写真アプリ)Live Photoになります",
"notice.geo_datum_assumed": "測地系がWGS 84ではありません。WGS 84とみなして変換したため、位置が最大で数百メートルずれることがあります",
"notice.geo_gpx_lossy": "GPXに保存できるのはポイント、ルート、トラックと一部の項目だけです。そのほかの属性は省き、ポリゴンはトラックにしました",
"notice.geo_text_cut": "一部のテキストがShapefileのフィールドの上限(254バイト)を超えたため、切り詰めました",
@@ -181,6 +184,8 @@
"preset.extract_frames_png": "フレームを抽出(PNG)",
"preset.extract_frames_jpg": "フレームを抽出(JPG)",
"preset.extract_motion": "Live Photoの動画を抽出",
+ "preset.live_photo_iphone": "Live Photo(iPhone)",
+ "preset.motion_photo_android": "モーションフォト(Android)",
"format.folder": "フォルダー",
"format.category.Image": "画像",
"format.category.Pdf": "PDF",
@@ -428,6 +433,18 @@
"presets.frame_estimate": "30 fpsの動画は、1分あたり{0}枚の画像になります(動画1本につき最大{1}枚)。",
"presets.extract_motion_photo": "Live Photo・モーションフォトの動画を抽出",
"presets.extract_motion_photo_hint": "写真と一緒に保存された動画を取り出します。Androidのモーションフォトは写真の中の動画、iPhoneのLive Photoは隣にある同じ名前のMOVを使います。\nほかの画像は静止画の動画になります。",
+ "presets.group.live_photo": "Live Photo/モーションフォト",
+ "presets.live_photo": "動画の保存方法",
+ "presets.live_photo.None": "静止画1枚",
+ "presets.live_photo.Apple": "Live Photo(iPhone):写真 + MOV",
+ "presets.live_photo.Android": "モーションフォト(Android):JPG 1つ",
+ "presets.live_photo_hint.apple": "短いクリップを、同じ名前で同じLive Photo識別子を持つ写真とMOVにします。写真アプリに両方を一緒に取り込んでください。動画は短辺が最大1440ピクセルです。試験的な機能:すべてのiPhoneで確認されたわけではありません。",
+ "presets.live_photo_hint.android": "短いクリップを、動画を含むJPG 1つ(名前.MP.jpg)にします。Pixelがモーションフォトを保存する形式なので、Googleフォトなどモーションフォトを読めるギャラリーで動きます。動画は短辺が最大1440ピクセルです。試験的な機能:すべてのスマートフォンで確認されたわけではありません。",
+ "presets.live_photo_start": "クリップの開始(秒)",
+ "presets.live_photo_length": "クリップの長さ(秒)",
+ "presets.live_photo_cover": "写真の位置(秒)",
+ "presets.live_photo_quality": "写真の品質",
+ "presets.live_photo_video_quality": "動画の品質",
"presets.ico_sizes": "アイコンサイズ",
"presets.group.pdf": "PDF",
"presets.merge": "すべてのファイルを1つのPDFに結合",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index af6a06a2..b0e1a6f0 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -78,6 +78,8 @@
"error.too_many_frames": "프레임이 너무 많아요. 'N번째 프레임마다' 값을 늘려 주세요",
"error.not_enough_space": "이미지를 저장할 디스크 공간이 부족해요",
"error.no_motion_photo": "이 사진에서 읽을 수 있는 동영상을 찾지 못했어요 (안드로이드 모션 포토, 또는 옆에 MOV가 있는 아이폰 라이브 포토)",
+ "error.live_photo_start": "클립 시작이 동영상 끝보다 뒤예요. \"클립 시작\"을 더 앞으로 정해 주세요",
+ "error.live_photo_hdr": "이 FFmpeg에는 zscale 필터가 없어서 HDR 동영상을 라이브/모션 포토로 만들 수 없어요. Filee에서 내려받는 FFmpeg에는 있어요",
"error.rhwp_timeout": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요",
"error.rhwp_timeout_calibre": "문서가 길어서 rhwp가 제한 시간 안에 끝내지 못했어요. 전자책이라면 설정 → 변환 엔진에서 Calibre를 HWPX writer보다 위로 옮겨 주세요. Calibre가 PDF를 훨씬 빨리 만들어요",
"error.needs_shaping": "이 문자는 LibreOffice가 있어야 제대로 변환돼요. 설정 → 변환 엔진에서 설치해 주세요",
@@ -92,6 +94,7 @@
"error.geo_unsupported_shape": "지원하지 않는 도형 종류예요",
"error.geo_too_large": "Shapefile의 한계인 2GB를 넘어요",
"notice.pdf_not_smaller": "더 작게 만들 수 없어서 그대로 복사했어요",
+ "notice.live_photo_pair": "같은 이름의 사진과 MOV로 저장했어요. 두 파일을 함께 가져오면(iCloud 사진, AirDrop, Mac의 사진 앱) 라이브 포토가 돼요",
"notice.geo_datum_assumed": "측지계가 WGS 84가 아니라서 같은 것으로 보고 변환했어요. 위치가 수백 m까지 어긋날 수 있어요",
"notice.geo_gpx_lossy": "GPX는 점·경로·트랙과 몇 가지 항목만 담아요. 다른 속성은 빠졌고 면은 트랙으로 바뀌었어요",
"notice.geo_text_cut": "Shapefile 필드 길이(254바이트)보다 긴 글자는 잘렸어요",
@@ -191,6 +194,8 @@
"preset.extract_frames_png": "프레임 추출 (PNG)",
"preset.extract_frames_jpg": "프레임 추출 (JPG)",
"preset.extract_motion": "라이브 포토 동영상 추출",
+ "preset.live_photo_iphone": "라이브 포토 (아이폰)",
+ "preset.motion_photo_android": "모션 포토 (안드로이드)",
"format.folder": "폴더",
"format.category.Image": "이미지",
@@ -443,6 +448,18 @@
"presets.frame_estimate": "30fps 동영상 1분이면 이미지 {0}장이 생겨요. 동영상 하나에 최대 {1}장까지예요.",
"presets.extract_motion_photo": "라이브/모션 포토 동영상 추출",
"presets.extract_motion_photo_hint": "사진과 함께 저장된 동영상을 꺼내요. 안드로이드 모션 포토는 사진 안의 동영상을, 아이폰 라이브 포토는 옆에 있는 같은 이름의 MOV를 써요.\n다른 이미지는 정지 화면 동영상이 돼요.",
+ "presets.group.live_photo": "라이브 / 모션 포토",
+ "presets.live_photo": "동영상을 이렇게 저장",
+ "presets.live_photo.None": "정지 화면 한 장",
+ "presets.live_photo.Apple": "라이브 포토 (아이폰): 사진 + MOV",
+ "presets.live_photo.Android": "모션 포토 (안드로이드): JPG 하나",
+ "presets.live_photo_hint.apple": "짧은 클립이 같은 이름의 사진과 MOV가 되고, 둘은 같은 라이브 포토 식별자를 가져요. 사진 앱에 두 파일을 함께 가져오세요. 동영상은 짧은 쪽이 최대 1440픽셀이에요. 실험 기능: 모든 아이폰에서 확인되지는 않았어요.",
+ "presets.live_photo_hint.android": "짧은 클립이 동영상이 들어 있는 JPG 하나(이름.MP.jpg)가 돼요. 픽셀 폰이 모션 포토를 저장하는 방식이라 Google 포토처럼 모션 포토를 읽는 갤러리에서 움직여요. 동영상은 짧은 쪽이 최대 1440픽셀이에요. 실험 기능: 모든 폰에서 확인되지는 않았어요.",
+ "presets.live_photo_start": "클립 시작 (초)",
+ "presets.live_photo_length": "클립 길이 (초)",
+ "presets.live_photo_cover": "사진 위치 (초)",
+ "presets.live_photo_quality": "사진 품질",
+ "presets.live_photo_video_quality": "동영상 품질",
"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 46317ff2..9406fd73 100644
--- a/src/Filee.App/Assets/i18n/pl.json
+++ b/src/Filee.App/Assets/i18n/pl.json
@@ -78,6 +78,8 @@
"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.live_photo_start": "Klip zaczyna się po końcu tego wideo. Wybierz wcześniejszy „Początek klipu”",
+ "error.live_photo_hdr": "Ten FFmpeg nie ma filtra zscale, więc z tego wideo HDR nie powstanie Live Photo ani Motion Photo. FFmpeg pobierany przez Filee go ma",
"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",
@@ -92,6 +94,7 @@
"error.geo_unsupported_shape": "Ten rodzaj kształtu nie jest obsługiwany",
"error.geo_too_large": "Shapefile przekroczyłby limit 2 GB tego formatu",
"notice.pdf_not_smaller": "Nie udało się zmniejszyć pliku, więc skopiowano go bez zmian",
+ "notice.live_photo_pair": "Zapisano jako zdjęcie i plik MOV o tej samej nazwie. Zaimportuj je razem (Zdjęcia iCloud, AirDrop lub Zdjęcia na Macu), aby otrzymać Live Photo",
"notice.geo_datum_assumed": "Datum nie jest WGS 84; pozycje przeliczono tak, jakby było, więc mogą się różnić nawet o setki metrów",
"notice.geo_gpx_lossy": "GPX przechowuje tylko punkty, trasy i ślady z kilkoma polami: pozostałe atrybuty pominięto, a poligony stały się śladami",
"notice.geo_text_cut": "Część tekstu była dłuższa niż pole Shapefile (254 bajty) i została przycięta",
@@ -191,6 +194,8 @@
"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",
+ "preset.live_photo_iphone": "Live Photo (iPhone)",
+ "preset.motion_photo_android": "Motion Photo (Android)",
"format.folder": "Folder",
"format.category.Image": "Obraz",
@@ -443,6 +448,18 @@
"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.group.live_photo": "Live Photo / Motion Photo",
+ "presets.live_photo": "Wideo staje się",
+ "presets.live_photo.None": "Jedną nieruchomą klatką",
+ "presets.live_photo.Apple": "Live Photo (iPhone): zdjęcie + MOV",
+ "presets.live_photo.Android": "Motion Photo (Android): jeden JPG",
+ "presets.live_photo_hint.apple": "Krótki klip staje się zdjęciem i plikiem MOV o tej samej nazwie i ze wspólnym identyfikatorem Live Photo. Zaimportuj oba razem do Zdjęć. Krótszy bok wideo ma najwyżej 1440 px. Funkcja eksperymentalna: jeszcze nie potwierdzona na każdym iPhonie.",
+ "presets.live_photo_hint.android": "Krótki klip staje się jednym plikiem JPG (NAZWA.MP.jpg) z wideo w środku, tak jak telefony Pixel zapisują Motion Photo, dla Zdjęć Google i innych galerii, które je odczytują. Krótszy bok wideo ma najwyżej 1440 px. Funkcja eksperymentalna: jeszcze nie potwierdzona na każdym telefonie.",
+ "presets.live_photo_start": "Początek klipu (s)",
+ "presets.live_photo_length": "Długość klipu (s)",
+ "presets.live_photo_cover": "Zdjęcie w (s)",
+ "presets.live_photo_quality": "Jakość zdjęcia",
+ "presets.live_photo_video_quality": "Jakość wideo",
"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/ru.json b/src/Filee.App/Assets/i18n/ru.json
index 7ba36652..8292fd81 100644
--- a/src/Filee.App/Assets/i18n/ru.json
+++ b/src/Filee.App/Assets/i18n/ru.json
@@ -78,6 +78,8 @@
"error.too_many_frames": "Слишком много кадров для сохранения картинками — увеличьте «Каждый N-й кадр»",
"error.not_enough_space": "Не хватает места на диске для картинок",
"error.no_motion_photo": "В этом фото нет видео, которое Filee может прочитать (Motion Photo с Android или Live Photo с iPhone с файлом MOV рядом)",
+ "error.live_photo_start": "Клип начинается после конца этого видео. Выберите более раннее «Начало клипа»",
+ "error.live_photo_hdr": "В этом FFmpeg нет фильтра zscale, поэтому из этого HDR-видео нельзя сделать Live Photo или Motion Photo. В FFmpeg, который скачивает Filee, он есть",
"error.rhwp_timeout": "rhwp не успел обработать этот длинный документ",
"error.rhwp_timeout_calibre": "rhwp не успел обработать этот длинный документ. Для электронной книги поставьте Calibre выше HWPX writer в разделе «Настройки → Движки» — так Calibre сделает PDF намного быстрее",
"error.needs_shaping": "Чтобы правильно сконвертировать текст в этой системе письма, нужен LibreOffice. Установите его в разделе «Настройки → Движки»",
@@ -92,6 +94,7 @@
"error.geo_unsupported_shape": "Такой тип фигуры не поддерживается",
"error.geo_too_large": "Shapefile превысил бы предел формата в 2 ГБ",
"notice.pdf_not_smaller": "Уменьшить не получилось, файл скопирован как есть",
+ "notice.live_photo_pair": "Сохранено как фото и MOV с одинаковым именем. Импортируйте их вместе (Фото iCloud, AirDrop или «Фото» на Mac), чтобы получить Live Photo",
"notice.geo_datum_assumed": "Датум отличается от WGS 84; координаты пересчитаны как для WGS 84 и могут сместиться на сотни метров",
"notice.geo_gpx_lossy": "GPX хранит только точки, маршруты и треки с небольшим набором полей: остальные атрибуты не вошли, а полигоны стали треками",
"notice.geo_text_cut": "Часть текста не помещалась в поле Shapefile (254 байта) и была обрезана",
@@ -191,6 +194,8 @@
"preset.extract_frames_png": "Кадры в картинки (PNG)",
"preset.extract_frames_jpg": "Кадры в картинки (JPG)",
"preset.extract_motion": "Видео из Live Photo",
+ "preset.live_photo_iphone": "Live Photo (iPhone)",
+ "preset.motion_photo_android": "Motion Photo (Android)",
"format.folder": "Папка",
"format.category.Image": "Изображение",
@@ -443,6 +448,18 @@
"presets.frame_estimate": "Минута видео с 30 кадрами в секунду даст картинок: {0}, не больше {1} на одно видео.",
"presets.extract_motion_photo": "Извлекать видео из Live/Motion Photo",
"presets.extract_motion_photo_hint": "Фото превращается в видео, сохранённое вместе с ним: встроенное в Motion Photo с Android или файл MOV рядом с Live Photo с iPhone.\nДругие картинки превращаются в видео из неподвижного кадра.",
+ "presets.group.live_photo": "Live Photo / Motion Photo",
+ "presets.live_photo": "Видео становится",
+ "presets.live_photo.None": "Одним неподвижным кадром",
+ "presets.live_photo.Apple": "Live Photo (iPhone): фото + MOV",
+ "presets.live_photo.Android": "Motion Photo (Android): один JPG",
+ "presets.live_photo_hint.apple": "Короткий клип становится фото и MOV с одинаковым именем и общим идентификатором Live Photo. Импортируйте оба файла в «Фото» вместе. Короткая сторона видео — не больше 1440 px. Экспериментально: пока проверено не на всех iPhone.",
+ "presets.live_photo_hint.android": "Короткий клип становится одним JPG (ИМЯ.MP.jpg) с видео внутри — так телефоны Pixel сохраняют Motion Photo — для Google Фото и других галерей, которые их читают. Короткая сторона видео — не больше 1440 px. Экспериментально: пока проверено не на всех телефонах.",
+ "presets.live_photo_start": "Начало клипа (с)",
+ "presets.live_photo_length": "Длина клипа (с)",
+ "presets.live_photo_cover": "Фото на (с)",
+ "presets.live_photo_quality": "Качество фото",
+ "presets.live_photo_video_quality": "Качество видео",
"presets.ico_sizes": "Размеры значка",
"presets.group.pdf": "PDF",
"presets.merge": "Объединить все файлы в один PDF",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index a17e3e22..49173894 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -78,6 +78,8 @@
"error.too_many_frames": "帧数太多,请调大“每 N 帧”",
"error.not_enough_space": "磁盘空间不足,无法保存这些图片",
"error.no_motion_photo": "这张照片中没有可读取的视频(安卓动态照片,或旁边有 MOV 的 iPhone 实况照片)",
+ "error.live_photo_start": "片段开始位置在视频结束之后。请把“片段开始”设得更早",
+ "error.live_photo_hdr": "此 FFmpeg 没有 zscale 滤镜,无法把 HDR 视频制作成实况/动态照片。Filee 下载的 FFmpeg 带有该滤镜",
"error.rhwp_timeout": "文档太长,rhwp 未能在时限内完成",
"error.rhwp_timeout_calibre": "文档太长,rhwp 未能在时限内完成。如果是电子书,请在“设置 → 转换引擎”中把 Calibre 移到 HWPX writer 之上,Calibre 生成 PDF 要快得多",
"error.needs_shaping": "这种文字需要 LibreOffice 才能正确转换,请在“设置 → 转换引擎”中安装",
@@ -92,6 +94,7 @@
"error.geo_unsupported_shape": "不支持此类形状",
"error.geo_too_large": "将超过 Shapefile 2 GB 的上限",
"notice.pdf_not_smaller": "无法再缩小,已原样复制",
+ "notice.live_photo_pair": "已保存为同名的照片和 MOV。将两者一起导入(iCloud 照片、隔空投送或 Mac 上的“照片”)即可得到实况照片",
"notice.geo_datum_assumed": "基准面不是 WGS 84,已按相同处理,位置可能偏差数百米",
"notice.geo_gpx_lossy": "GPX 只能保存点、路线和轨迹及少数字段,其他属性已省略,面变成了轨迹",
"notice.geo_text_cut": "部分文字超过 Shapefile 字段长度(254 字节),已被截断",
@@ -191,6 +194,8 @@
"preset.extract_frames_png": "提取帧 (PNG)",
"preset.extract_frames_jpg": "提取帧 (JPG)",
"preset.extract_motion": "提取实况/动态照片视频",
+ "preset.live_photo_iphone": "实况照片(iPhone)",
+ "preset.motion_photo_android": "动态照片(安卓)",
"format.folder": "文件夹",
"format.category.Image": "图片",
@@ -443,6 +448,18 @@
"presets.frame_estimate": "30 fps 的视频每分钟生成 {0} 张图片,每个视频最多 {1} 张。",
"presets.extract_motion_photo": "提取实况/动态照片中的视频",
"presets.extract_motion_photo_hint": "取出与照片一起保存的视频。安卓动态照片取其中内嵌的视频,iPhone 实况照片取旁边同名的 MOV。\n其他图片仍转换为静态画面的视频。",
+ "presets.group.live_photo": "实况/动态照片",
+ "presets.live_photo": "视频保存为",
+ "presets.live_photo.None": "一张静态画面",
+ "presets.live_photo.Apple": "实况照片(iPhone)- 照片 + MOV",
+ "presets.live_photo.Android": "动态照片(安卓)- 一个 JPG",
+ "presets.live_photo_hint.apple": "将短片段保存为同名的照片和 MOV,两者带有相同的实况照片标识符。请把两个文件一起导入“照片”。视频短边最大 1440 像素。实验功能,尚未在所有 iPhone 上确认。",
+ "presets.live_photo_hint.android": "将短片段保存为内含视频的一个 JPG(名称.MP.jpg),与 Pixel 手机保存动态照片的方式相同,可在 Google 相册等支持动态照片的图库中播放。视频短边最大 1440 像素。实验功能,尚未在所有手机上确认。",
+ "presets.live_photo_start": "片段开始(秒)",
+ "presets.live_photo_length": "片段长度(秒)",
+ "presets.live_photo_cover": "照片位置(秒)",
+ "presets.live_photo_quality": "照片质量",
+ "presets.live_photo_video_quality": "视频质量",
"presets.ico_sizes": "图标尺寸",
"presets.group.pdf": "PDF",
"presets.merge": "将所有文件合并为一个 PDF",
diff --git a/src/Filee.App/Services/PresetAvailability.cs b/src/Filee.App/Services/PresetAvailability.cs
index 4df9a17d..888aa216 100644
--- a/src/Filee.App/Services/PresetAvailability.cs
+++ b/src/Filee.App/Services/PresetAvailability.cs
@@ -47,10 +47,11 @@ public sealed class PresetAvailability(ConverterCatalog catalog, ILocalizer loc,
return true; // merged as it is
var frames = preset.SavesFramesOf(f.Id);
var motion = preset.ExtractsMotionOf(f.Id);
+ var live = preset.MakesLivePhotoOf(f.Id);
if (!turns)
- return planner.CanConvert(f.Id, target, frames, motionPhoto: motion);
+ return planner.CanConvert(f.Id, target, frames, motionPhoto: motion, livePhoto: live);
// Rotate / flip: a route only counts when an engine on it turns images (not a PDF or a video copied).
- if (planner.Plan(f.Id, target, frames, motionPhoto: motion) is not { } route)
+ if (planner.Plan(f.Id, target, frames, motionPhoto: motion, livePhoto: live) is not { } route)
return false;
if (route.FirstTransformStep() >= 0)
return true;
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 31f3eacb..6ddb748a 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -122,6 +122,10 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_combineIntoOne = _edit.Archive.CombineIntoOne;
_saveEveryFrame = _edit.Media.SaveEveryFrame;
_extractMotionPhoto = _edit.Media.ExtractMotionPhoto;
+ _livePhotoValue = _edit.Media.LivePhoto;
+ _livePhotoStart = _edit.Media.LivePhotoStart;
+ _livePhotoLength = _edit.Media.LivePhotoLength;
+ _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);
@@ -200,9 +204,67 @@ public sealed partial class PresetEditorViewModel : ObservableObject
nameof(ShowAudioChannels), nameof(ShowWav), nameof(VideoCodecs), nameof(VideoCodecChoice), nameof(ShowVideoCodec), nameof(ShowHardwareEncoding),
nameof(AudioCodecs), nameof(AudioCodecChoice), nameof(ShowAudioCodec),
nameof(ShowArchive), nameof(ShowArchiveOptions), nameof(ShowExtractNote),
- nameof(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace), nameof(ShowExtractMotionPhoto))]
+ nameof(ShowSaveEveryFrame), nameof(ShowAnimationSpeed), nameof(ShowTrace), nameof(ShowExtractMotionPhoto),
+ nameof(ShowLivePhotoChoice), nameof(LivePhotoKinds), nameof(LivePhotoChoice), nameof(IsLivePhoto), nameof(LivePhotoHint))]
private Choice<string> _target;
+ private LivePhotoKind _livePhotoValue;
+
+ /// <summary>What a video becomes for a JPG or HEIC target: one still frame, or a Live / Motion Photo it can be written as.</summary>
+ public IReadOnlyList<Choice<LivePhotoKind>> LivePhotoKinds =>
+ [.. Enum.GetValues<LivePhotoKind>()
+ .Where(k => k == LivePhotoKind.None || MediaOptions.LivePhotoTargets(k).Contains(TargetId))
+ .Select(k => new Choice<LivePhotoKind>(k, _loc[$"presets.live_photo.{k}"]))];
+
+ /// <summary>The chosen kind; one the target can't be written as shows (and is saved) as None.</summary>
+ public Choice<LivePhotoKind> LivePhotoChoice
+ {
+ get => LivePhotoKinds.FirstOrDefault(c => c.Value == _livePhotoValue) ?? LivePhotoKinds[0];
+ set
+ {
+ // The combo box clears its selection while its list is replaced: announcing the value shows it again.
+ if (value is null)
+ {
+ OnPropertyChanged();
+ return;
+ }
+ if (value.Value == _livePhotoValue)
+ return;
+ _livePhotoValue = value.Value;
+ OnPropertyChanged();
+ foreach (var name in (string[])[nameof(IsLivePhoto), nameof(LivePhotoHint), nameof(ShowImage), nameof(ShowPdf), nameof(ShowSaveEveryFrame)])
+ OnPropertyChanged(name);
+ }
+ }
+
+ [ObservableProperty] private double _livePhotoStart;
+ [ObservableProperty] private double _livePhotoLength;
+ [ObservableProperty] private double _livePhotoCover;
+
+ /// <summary>The clip's video codec: H.264, or HEVC for smaller files (MediaOptions.VideoCodec).</summary>
+ public IReadOnlyList<Choice<VideoCodec>> LivePhotoCodecs =>
+ [
+ new(VideoCodec.Default, _loc["presets.video_codec.h264"]),
+ new(VideoCodec.Hevc, _loc["presets.video_codec.hevc"]),
+ ];
+
+ public Choice<VideoCodec> LivePhotoCodecChoice
+ {
+ get => LivePhotoCodecs.FirstOrDefault(c => c.Value == _videoCodecValue) ?? LivePhotoCodecs[0];
+ set
+ {
+ if (value is null)
+ {
+ OnPropertyChanged();
+ return;
+ }
+ if (value.Value == _videoCodecValue)
+ return;
+ _videoCodecValue = value.Value;
+ OnPropertyChanged();
+ }
+ }
+
private VideoCodec _videoCodecValue;
private AudioCodec _audioCodecValue;
@@ -397,7 +459,14 @@ 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;
+ public bool ShowImage => !IsTool && TargetIsImage && !IsLivePhoto;
+ /// <summary>JPG and HEIC: a video can become a Live / Motion Photo instead of one still frame.</summary>
+ public bool ShowLivePhotoChoice => !IsTool && LivePhotoKinds.Count > 1;
+ /// <summary>A Live / Motion Photo is chosen and the target can be written as it: its clip options are shown.</summary>
+ public bool IsLivePhoto => ShowLivePhotoChoice && _livePhotoValue != LivePhotoKind.None
+ && MediaOptions.LivePhotoTargets(_livePhotoValue).Contains(TargetId);
+ /// <summary>What the chosen kind writes and where it is expected to work.</summary>
+ public string LivePhotoHint => _loc[_livePhotoValue == LivePhotoKind.Android ? "presets.live_photo_hint.android" : "presets.live_photo_hint.apple"];
/// <summary>Images and PDFs (pictures placed on pages) can be turned and flipped.</summary>
private bool CanTurn => TargetIsImage || TargetId == "pdf";
/// <summary>Rotate and flip for a PDF target, which has no image card to show them in.</summary>
@@ -408,7 +477,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, 3D and geospatial targets.</summary>
- public bool ShowPdf => !IsTool && TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font
+ public bool ShowPdf => !IsTool && !IsLivePhoto && TargetCategory is not (FormatCategory.Video or FormatCategory.Audio or FormatCategory.Archive or FormatCategory.Font
or FormatCategory.Subtitle or FormatCategory.Data or FormatCategory.Model3D or FormatCategory.Geo) && TargetId != "eml";
/// <summary>"Save as ZIP" is offered for geospatial targets, whose results are several files (a Shapefile) or travel zipped.</summary>
public bool ShowZipResult => TargetCategory == FormatCategory.Geo;
@@ -445,7 +514,7 @@ public sealed partial class PresetEditorViewModel : ObservableObject
/// <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);
+ public bool ShowSaveEveryFrame => !IsTool && !IsLivePhoto && 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>
@@ -535,13 +604,22 @@ public sealed partial class PresetEditorViewModel : ObservableObject
media.AudioChannels = AudioChannels.Value;
media.AudioSampleRate = SampleRate.Value;
media.WavFormat = WavFormat.Value;
- media.VideoCodec = MediaCodecs.Effective(TargetId, _videoCodecValue);
+ // A Live Photo's clip is a MOV (or an MP4 in a Motion Photo): H.264 or HEVC, whatever the photo's format.
+ media.VideoCodec = IsLivePhoto
+ ? (_videoCodecValue == VideoCodec.Hevc ? VideoCodec.Hevc : VideoCodec.Default)
+ : MediaCodecs.Effective(TargetId, _videoCodecValue);
media.AudioCodec = MediaCodecs.Effective(TargetId, _audioCodecValue);
media.HardwareEncoding = HardwareEncoding;
// Only where the option is shown: a box ticked for PNG and left behind by another target saves nothing.
media.SaveEveryFrame = ShowSaveEveryFrame && SaveEveryFrame;
media.FrameInterval = media.SaveEveryFrame ? Math.Clamp(FrameInterval, 1, 1000) : 1;
media.ExtractMotionPhoto = ShowExtractMotionPhoto && ExtractMotionPhoto;
+ media.LivePhoto = IsLivePhoto ? _livePhotoValue : LivePhotoKind.None;
+ static double Seconds(double value, double fallback, double min, double max) =>
+ double.IsFinite(value) ? Math.Clamp(value, min, max) : fallback;
+ media.LivePhotoStart = Seconds(LivePhotoStart, 0, 0, 24 * 3600);
+ media.LivePhotoLength = Seconds(LivePhotoLength, 3, MediaOptions.MinLivePhotoLength, MediaOptions.MaxLivePhotoLength);
+ media.LivePhotoCover = Seconds(LivePhotoCover, 1.5, 0, MediaOptions.MaxLivePhotoLength);
_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 08c7f488..4468623d 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -38,6 +38,56 @@
</StackPanel>
</Grid>
+ <!-- Live / Motion Photo of a video (JPG, HEIC): the kind on a row of its own, so its names are never cut off -->
+ <Border x:Name="LivePhotoCard" Classes="card" IsVisible="{Binding ShowLivePhotoChoice}" Padding="14">
+ <StackPanel Spacing="10">
+ <TextBlock Classes="h2" Text="{DynamicResource presets.group.live_photo}" />
+ <StackPanel>
+ <TextBlock Classes="label" TextWrapping="Wrap" Text="{DynamicResource presets.live_photo}" />
+ <ComboBox ItemsSource="{Binding LivePhotoKinds}" SelectedItem="{Binding LivePhotoChoice}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel Spacing="10" IsVisible="{Binding IsLivePhoto}">
+ <TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding LivePhotoHint}" />
+ <UniformGrid Columns="3" ColumnSpacing="12">
+ <StackPanel>
+ <TextBlock Classes="label" TextWrapping="Wrap" Text="{DynamicResource presets.live_photo_start}" />
+ <NumericUpDown Value="{Binding LivePhotoStart}" Minimum="0" Maximum="86400" Increment="0.5" FormatString="0.##" />
+ </StackPanel>
+ <StackPanel>
+ <TextBlock Classes="label" TextWrapping="Wrap" Text="{DynamicResource presets.live_photo_length}" />
+ <NumericUpDown Value="{Binding LivePhotoLength}" Minimum="0.5" Maximum="5" Increment="0.5" FormatString="0.##" />
+ </StackPanel>
+ <StackPanel>
+ <TextBlock Classes="label" TextWrapping="Wrap" Text="{DynamicResource presets.live_photo_cover}" />
+ <NumericUpDown Value="{Binding LivePhotoCover}" Minimum="0" Maximum="5" Increment="0.1" FormatString="0.##" />
+ </StackPanel>
+ </UniformGrid>
+ <StackPanel>
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" Text="{Binding Quality}" FontWeight="SemiBold" />
+ <TextBlock Classes="label" Text="{DynamicResource presets.live_photo_quality}" />
+ </DockPanel>
+ <Slider Minimum="1" Maximum="100" Value="{Binding Quality}" TickFrequency="1" IsSnapToTickEnabled="True" />
+ </StackPanel>
+ <UniformGrid Columns="2" ColumnSpacing="12" RowSpacing="10">
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.live_photo_video_quality}" />
+ <ComboBox ItemsSource="{Binding MediaQualities}" SelectedItem="{Binding MediaQuality}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.max_height}" />
+ <ComboBox ItemsSource="{Binding MaxHeights}" SelectedItem="{Binding MaxHeight}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <StackPanel>
+ <TextBlock Classes="label" Text="{DynamicResource presets.video_codec}" />
+ <ComboBox ItemsSource="{Binding LivePhotoCodecs}" SelectedItem="{Binding LivePhotoCodecChoice}" HorizontalAlignment="Stretch" />
+ </StackPanel>
+ <CheckBox VerticalAlignment="Bottom" Content="{DynamicResource presets.remove_audio}" IsChecked="{Binding RemoveAudio}" />
+ </UniformGrid>
+ </StackPanel>
+ </StackPanel>
+ </Border>
+
<!-- Image options -->
<Border Classes="card" IsVisible="{Binding ShowImage}" Padding="14">
<StackPanel Spacing="10">
diff --git a/src/Filee.Core/Conversion/IConverter.cs b/src/Filee.Core/Conversion/IConverter.cs
index cbf34edc..3a84b9d8 100644
--- a/src/Filee.Core/Conversion/IConverter.cs
+++ b/src/Filee.Core/Conversion/IConverter.cs
@@ -30,7 +30,7 @@ namespace Filee.Core.Conversion;
/// <param name="FrameSequence">
/// The edge writes every frame of a video as numbered pictures into a folder (<see cref="Presets.MediaOptions.SaveEveryFrame"/>).
/// It is never part of an ordinary route (a video → JPG stays one still frame), and with
-/// <see cref="RoutePlanner.Plan(string, string, bool, bool, bool)"/> asking for frames it is the whole route.
+/// <see cref="RoutePlanner.Plan(string, string, bool, bool, bool, bool)"/> asking for frames it is the whole route.
/// </param>
/// <param name="Unshaped">
/// The engine draws text one character after the other, left to right, without complex-script shaping (no joined
@@ -41,11 +41,16 @@ namespace Filee.Core.Conversion;
/// <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.
+/// <see cref="RoutePlanner.Plan(string, string, bool, bool, bool, bool)"/> asking for it it is the whole route.
+/// </param>
+/// <param name="LivePhoto">
+/// The edge makes a Live / Motion Photo of a short clip of a video (<see cref="Presets.MediaOptions.LivePhoto"/>). It is
+/// never part of an ordinary route (a video → JPG is otherwise one still frame), and with
+/// <see cref="RoutePlanner.Plan(string, string, bool, 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);
+ bool DirectOnly = false, bool FrameSequence = false, bool Unshaped = false, bool MotionPhoto = false, bool LivePhoto = false);
/// <summary>
/// A conversion an engine refuses with a reason the user can act on, shown in their language (the file's
@@ -106,6 +111,10 @@ public interface IOutputAllocator
/// The step takes a <see cref="ConversionEdge.MotionPhoto"/> edge: the video of the Live / Motion Photo becomes the
/// output, not its still picture.
/// </param>
+/// <param name="LivePhoto">
+/// The step takes a <see cref="ConversionEdge.LivePhoto"/> edge: a clip of the video becomes a Live / Motion Photo
+/// (<see cref="Presets.MediaOptions.LivePhoto"/> says which kind).
+/// </param>
public sealed record ConversionStep(
string InputPath,
string From,
@@ -115,7 +124,8 @@ public sealed record ConversionStep(
string WorkDirectory,
bool FrameSequence = false,
Action<string>? Notice = null,
- bool MotionPhoto = false);
+ bool MotionPhoto = false,
+ bool LivePhoto = 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 817ac0a2..14b9f1a5 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -367,11 +367,13 @@ public sealed class JobQueue : IAsyncDisposable
: job.Preset.TargetFormat;
// "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).
+ // video" likewise takes a photo's video, and "Live / Motion Photo" makes one of a 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);
+ var livePhoto = finalOutput && job.Preset.MakesLivePhotoOf(source.Id);
+ var route = planner.Plan(source.Id, target, frames, motionPhoto: motionPhoto, livePhoto: livePhoto);
if (route is null)
return Fail(file, "error.no_route", $"{source.Id} → {target}");
@@ -437,7 +439,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, step.MotionPhoto);
+ key => file.NoticeKey = key, step.MotionPhoto, step.LivePhoto);
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 050c1a80..b19047eb 100644
--- a/src/Filee.Core/Conversion/RoutePlanner.cs
+++ b/src/Filee.Core/Conversion/RoutePlanner.cs
@@ -11,8 +11,10 @@ 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>
+/// <param name="MotionPhoto">The hop takes the video of a Live / Motion Photo (<see cref="ConversionEdge.MotionPhoto"/>).</param>
+/// <param name="LivePhoto">The hop makes a Live / Motion Photo of a video (<see cref="ConversionEdge.LivePhoto"/>).</param>
public sealed record RouteStep(IConverter Converter, string From, string To, bool FrameSequence = false, bool Unshaped = false,
- bool MotionPhoto = false);
+ bool MotionPhoto = false, bool LivePhoto = false);
/// <summary>A planned conversion from one format to another.</summary>
public sealed record Route(IReadOnlyList<RouteStep> Steps, int Cost)
@@ -66,27 +68,35 @@ public sealed class RoutePlanner
/// 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)
+ /// <param name="livePhoto">
+ /// Make a Live / Motion Photo of a video (<see cref="Presets.Preset.MakesLivePhotoOf"/>): the route is one
+ /// <see cref="ConversionEdge.LivePhoto"/> 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, bool livePhoto = false)
{
from = from.ToLowerInvariant();
to = to.ToLowerInvariant();
- if (frames || motionPhoto)
+ if (frames || motionPhoto || livePhoto)
{
+ // One of them: frames, then the video of a photo, then a photo of a video.
+ motionPhoto &= !frames;
+ livePhoto &= !frames && !motionPhoto;
var special = EdgesFrom(from)
- .Where(e => e.Edge.To == to && (frames ? e.Edge.FrameSequence : e.Edge.MotionPhoto))
+ .Where(e => e.Edge.To == to && (frames ? e.Edge.FrameSequence : motionPhoto ? e.Edge.MotionPhoto : e.Edge.LivePhoto))
.OrderBy(e => e.Cost)
.FirstOrDefault();
return special.Converter is null
? null
- : new Route([new RouteStep(special.Converter, from, to, FrameSequence: frames, MotionPhoto: !frames)], special.Cost);
+ : new Route([new RouteStep(special.Converter, from, to, FrameSequence: frames, MotionPhoto: motionPhoto, LivePhoto: livePhoto)],
+ special.Cost);
}
// Same-format "conversions" (re-encode, split, compress) must use an explicit self edge.
if (from == to)
{
var best = EdgesFrom(from)
- .Where(e => e.Edge.To == to && !e.Edge.FrameSequence && !e.Edge.MotionPhoto)
+ .Where(e => e.Edge.To == to && !e.Edge.FrameSequence && !e.Edge.MotionPhoto && !e.Edge.LivePhoto)
.OrderBy(e => e.Cost)
.FirstOrDefault();
return best.Converter is null
@@ -115,7 +125,7 @@ public sealed class RoutePlanner
foreach (var (converter, edge, edgeCost) in EdgesFrom(node))
{
- if (edge.To == edge.From || edge.FrameSequence || edge.MotionPhoto
+ if (edge.To == edge.From || edge.FrameSequence || edge.MotionPhoto || edge.LivePhoto
|| (edge.ImageSourcesOnly && !imageSource) || (edge.NotForImageSources && imageSource)
|| (edge.Unshaped && shaping)
|| (edge.DirectOnly && (node != from || edge.To != to)))
@@ -144,8 +154,9 @@ 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;
+ /// <param name="livePhoto">A Live / Motion Photo of a video (see <see cref="Plan"/>).</param>
+ public bool CanConvert(string from, string to, bool frames = false, bool motionPhoto = false, bool livePhoto = false) =>
+ Plan(from, to, frames, motionPhoto: motionPhoto, livePhoto: livePhoto) is not null;
private IReadOnlyList<(IConverter Converter, ConversionEdge Edge, int Cost)> EdgesFrom(string format) =>
_edgesFrom.TryGetValue(format, out var edges) ? edges : [];
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index d6174613..3bdaf92a 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -74,6 +74,7 @@ public static class BuiltInData
.. PdfSlidesPresets(),
.. FramePresets(),
.. MotionPhotoPresets(),
+ .. LivePhotoPresets(),
new() { Id = "to-docx", Name = "DOCX", TargetFormat = "docx" },
new() { Id = "to-hwpx", Name = "HWPX", TargetFormat = "hwpx" },
.. HwpPresets(),
@@ -100,6 +101,16 @@ public static class BuiltInData
new() { Id = "extract-motion", NameKey = "preset.extract_motion", TargetFormat = "mp4", Media = { ExtractMotionPhoto = true } },
];
+ /// <summary>
+ /// A clip of a video as an iPhone Live Photo (a JPG and a MOV) or an Android Motion Photo (added in settings schema
+ /// 31), on no donut: users add them in Settings → Toolbar.
+ /// </summary>
+ public static List<Preset> LivePhotoPresets() =>
+ [
+ new() { Id = "live-photo-iphone", NameKey = "preset.live_photo_iphone", TargetFormat = "jpg", Media = { LivePhoto = LivePhotoKind.Apple } },
+ new() { Id = "motion-photo-android", NameKey = "preset.motion_photo_android", TargetFormat = "jpg", Media = { LivePhoto = LivePhotoKind.Android } },
+ ];
+
/// <summary>
/// "Compress PDF": pictures at 150 dpi, the rest compressed losslessly (added in settings schema 20). On no default
/// donut, the PDF donut is full: users add it in Settings → Toolbar.
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 4257eda5..bf80d026 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -140,6 +140,7 @@ public sealed class Preset
/// </summary>
public bool SavesFramesOf(string sourceFormat) =>
Media.SaveEveryFrame
+ && !MakesLivePhotoOf(sourceFormat)
&& MediaOptions.FrameTargets.Contains(TargetFormat)
&& Formats.FormatRegistry.FindById(sourceFormat)?.Category == Formats.FormatCategory.Video;
@@ -154,6 +155,15 @@ public sealed class Preset
&& MediaOptions.MotionPhotoSources.Contains(sourceFormat)
&& (Media.ExtractMotionPhoto || sourceFormat == "livp");
+ /// <summary>
+ /// True if converting a <paramref name="sourceFormat"/> file makes a Live / Motion Photo of a short clip
+ /// (<see cref="MediaOptions.LivePhoto"/>): the file is a video and the target one the kind is written as
+ /// (<see cref="MediaOptions.LivePhotoTargets"/>). Other files, and other targets, convert as usual.
+ /// </summary>
+ public bool MakesLivePhotoOf(string sourceFormat) =>
+ MediaOptions.LivePhotoTargets(Media.LivePhoto).Contains(TargetFormat)
+ && Formats.FormatRegistry.FindById(sourceFormat)?.Category == Formats.FormatCategory.Video;
+
/// <summary>True for a <see cref="PresetKind.Tool"/>.</summary>
[JsonIgnore]
public bool IsTool => Kind == PresetKind.Tool;
@@ -493,6 +503,39 @@ public sealed class MediaOptions
/// </summary>
public bool ExtractMotionPhoto { get; set; }
+ /// <summary>
+ /// Video → JPG (or HEIC for an iPhone): a Live / Motion Photo of a short clip instead of one still frame. Only for
+ /// video sources and a target in <see cref="LivePhotoTargets"/> (<see cref="Preset.MakesLivePhotoOf"/>).
+ /// </summary>
+ [JsonConverter(typeof(LenientEnumJsonConverter<LivePhotoKind>))]
+ public LivePhotoKind LivePhoto { get; set; }
+
+ /// <summary>The photo formats a <paramref name="kind"/> of Live / Motion Photo is written as.</summary>
+ public static IReadOnlyList<string> LivePhotoTargets(LivePhotoKind kind) => kind switch
+ {
+ LivePhotoKind.Apple => ["jpg", "heic"],
+ LivePhotoKind.Android => ["jpg"],
+ _ => [],
+ };
+
+ /// <summary>Shortest and longest clip of a Live / Motion Photo, in seconds (phones record about 3).</summary>
+ public const double MinLivePhotoLength = 0.5, MaxLivePhotoLength = 5;
+
+ /// <summary>With <see cref="LivePhoto"/>: where the clip starts in the video, in seconds.</summary>
+ public double LivePhotoStart { get; set; }
+
+ /// <summary>
+ /// With <see cref="LivePhoto"/>: how long the clip is, in seconds (<see cref="MinLivePhotoLength"/> to
+ /// <see cref="MaxLivePhotoLength"/>); shorter when the video ends sooner.
+ /// </summary>
+ public double LivePhotoLength { get; set; } = 3;
+
+ /// <summary>
+ /// With <see cref="LivePhoto"/>: the frame that becomes the photo, in seconds from the start of the clip (the
+ /// middle, as a phone takes it, by default); the clip's last frame when the clip is shorter.
+ /// </summary>
+ public double LivePhotoCover { get; set; } = 1.5;
+
/// <summary>With <see cref="SaveEveryFrame"/>: extract every Nth frame (1 = every frame).</summary>
public int FrameInterval { get; set; } = 1;
@@ -506,6 +549,17 @@ public sealed class MediaOptions
public MediaOptions Clone() => (MediaOptions)MemberwiseClone();
}
+/// <summary>The kind of moving photo a video becomes (<see cref="MediaOptions.LivePhoto"/>).</summary>
+public enum LivePhotoKind
+{
+ /// <summary>One still frame, as usual.</summary>
+ None,
+ /// <summary>An iPhone Live Photo: a JPG or HEIC and a MOV with the same name and content identifier.</summary>
+ Apple,
+ /// <summary>An Android Motion Photo: one JPG with the clip (MP4) appended, described in its XMP.</summary>
+ Android,
+}
+
/// <summary>Video codec of a video target. <see cref="Default"/> is the target's usual codec (H.264, VP9 for WebM, ...).</summary>
public enum VideoCodec
{
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 863795d3..d01183cf 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 = 29;
+ public const int CurrentSchemaVersion = 31;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index cdb64750..97d006ba 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -701,6 +701,28 @@ internal static class SettingsMigrations
}
changed |= LearnExtensions(profiles, out _, ["livp"]);
}
+ // v31 (30 is kept for another change): "Live Photo (iPhone)" and "Motion Photo (Android)" (a clip of a video
+ // as a moving photo), after "Extract Live Photo video" as in a new library, on no donut. Present already
+ // but saved since by a Filee before 31: that one dropped the option and left a plain JPG preset, so it is
+ // put back.
+ if (from < 31)
+ {
+ foreach (var live in BuiltInData.LivePhotoPresets())
+ {
+ if (presets.FirstOrDefault(p => p.Id == live.Id) is { } existing)
+ {
+ if (existing.Media.LivePhoto == LivePhotoKind.None && existing.TargetFormat == live.TargetFormat)
+ {
+ existing.Media.LivePhoto = live.Media.LivePhoto;
+ changed = true;
+ }
+ continue;
+ }
+ var at = presets.FindLastIndex(p => p.Id is "extract-motion" or "live-photo-iphone" or "extract-frames-jpg");
+ presets.Insert(at < 0 ? presets.Count : at + 1, live);
+ changed = true;
+ }
+ }
return changed;
}
diff --git a/src/Filee.Engines/Heic/HeicWriter.cs b/src/Filee.Engines/Heic/HeicWriter.cs
index f1e175f8..f11f29ff 100644
--- a/src/Filee.Engines/Heic/HeicWriter.cs
+++ b/src/Filee.Engines/Heic/HeicWriter.cs
@@ -31,21 +31,10 @@ internal static class HeicWriter
var picture = pictures[i];
var share = 0.85 / pictures.Count;
var start = 0.15 + i * share;
- var stream = Path.Combine(step.WorkDirectory, $"heic-{Guid.NewGuid():N}.hevc");
- var (columns, rows, tileWidth, tileHeight) = Layout(picture.Width, picture.Height);
-
- ProcessResult result;
+ byte[] heif;
using (ProgressEstimate.Start(progress, TimeSpan.FromSeconds(5), start, start + share * 0.95))
- result = await FfmpegRunner.RunAsync(ffmpeg, Arguments(picture.Png, stream, picture.Width, picture.Height,
- step.Preset.Image.Quality), null, cancellationToken);
- if (result.ExitCode != 0)
- {
- var reason = FfmpegRunner.Summarize(result.StandardError);
- throw new InvalidOperationException($"FFmpeg failed (exit code {result.ExitCode}){(reason.Length > 0 ? ": " + reason : ".")}");
- }
-
- var heif = HeifFile.Write(new HeifImage(picture.Width, picture.Height, HevcStream.Parse(await File.ReadAllBytesAsync(stream, cancellationToken)),
- tileWidth, tileHeight, columns, rows, picture.IccProfile, picture.Exif));
+ heif = await EncodeAsync(ffmpeg, picture.Png, picture.Width, picture.Height, picture.IccProfile, picture.Exif,
+ step.Preset.Image.Quality, step.WorkDirectory, cancellationToken);
var output = step.Output.Allocate("heic", pictures.Count > 1 ? $"_p{i + 1}" : null);
if (output is null)
continue;
@@ -56,6 +45,26 @@ internal static class HeicWriter
return written;
}
+ /// <summary>
+ /// A HEIC file of the 8-bit RGB PNG <paramref name="png"/> (<paramref name="width"/> × <paramref name="height"/>)
+ /// with its colour profile and Exif (a TIFF header, or "Exif\0\0" and one): x265 encodes the tiles into the work
+ /// directory, HeifFile puts them together.
+ /// </summary>
+ internal static async Task<byte[]> EncodeAsync(string ffmpeg, string png, int width, int height, byte[]? iccProfile, byte[]? exif,
+ int quality, string workDirectory, CancellationToken cancellationToken)
+ {
+ var stream = Path.Combine(workDirectory, $"heic-{Guid.NewGuid():N}.hevc");
+ var (columns, rows, tileWidth, tileHeight) = Layout(width, height);
+ var result = await FfmpegRunner.RunAsync(ffmpeg, Arguments(png, stream, width, height, quality), null, cancellationToken);
+ if (result.ExitCode != 0)
+ {
+ var reason = FfmpegRunner.Summarize(result.StandardError);
+ throw new InvalidOperationException($"FFmpeg failed (exit code {result.ExitCode}){(reason.Length > 0 ? ": " + reason : ".")}");
+ }
+ return HeifFile.Write(new HeifImage(width, height, HevcStream.Parse(await File.ReadAllBytesAsync(stream, cancellationToken)),
+ tileWidth, tileHeight, columns, rows, iccProfile, exif));
+ }
+
/// <summary>
/// Reads the source with ImageMagick and writes every picture to convert (TIFF pages; the first frame of an
/// animation) as a PNG, after the preset's orientation, resize and metadata options. HEIC is written without
diff --git a/src/Filee.Engines/Media/AppleLivePhoto.cs b/src/Filee.Engines/Media/AppleLivePhoto.cs
index b2e4593c..21ac9cb7 100644
--- a/src/Filee.Engines/Media/AppleLivePhoto.cs
+++ b/src/Filee.Engines/Media/AppleLivePhoto.cs
@@ -1,4 +1,5 @@
-// Apple Live Photo pairing: the content identifier the photo (Apple maker note) and its MOV (QuickTime metadata) share.
+// Apple Live Photo pairing: the content identifier the photo (Apple maker note) and its MOV (QuickTime metadata) share,
+// read from a pair and written into a new one, with the movie's timed "still image time" marking the photo's frame.
using System.Buffers.Binary;
using System.Text;
@@ -10,8 +11,15 @@ 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;
+ /// <summary>Tag 17 of Apple's maker note: the Live Photo's content identifier, an ASCII UUID.</summary>
+ private const ushort ContentIdentifierTag = 17;
+
+ /// <summary>"Signed 8-bit integer" among QuickTime's well-known metadata data types.</summary>
+ private const uint WellKnownInt8 = 65;
+
/// <summary>The content identifier in the photo's Apple maker note (tag 17), or null.</summary>
public static string? ImageIdentifier(string imagePath)
{
@@ -35,7 +43,7 @@ internal static class AppleLivePhoto
for (var i = 0; i < count; i++)
{
var at = 16 + i * 12;
- if (Read16(at) != 17 || Read16(at + 2) != 2)
+ if (Read16(at) != ContentIdentifierTag || Read16(at + 2) != 2)
continue;
// Apple maker-note offsets are relative to the note itself.
var length = Read32(at + 4);
@@ -48,11 +56,30 @@ internal static class AppleLivePhoto
return null;
}
+ /// <summary>
+ /// An Apple maker note holding only <paramref name="identifier"/> (tag 17), laid out as an iPhone writes its own:
+ /// "Apple iOS", version 1, big-endian, one IFD entry, no next IFD, the value after it. Offsets count from the
+ /// start of the note, so it stays valid wherever the Exif writer puts it.
+ /// </summary>
+ internal static byte[] MakerNote(string identifier)
+ {
+ var id = Encoding.ASCII.GetBytes(Guid.Parse(identifier).ToString("D").ToUpperInvariant() + "\0");
+ const uint valueOffset = 14 + 2 + 12 + 4;
+ return
+ [
+ .. "Apple iOS\0"u8, 0, 1, .. "MM"u8,
+ .. U16(1),
+ .. U16(ContentIdentifierTag), .. U16(2), .. U32((uint)id.Length), .. U32(valueOffset),
+ .. U32(0),
+ .. id,
+ ];
+ }
+
/// <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 children = Children(ReadMovie(file));
+ var children = Children(ReadMovieHeader(file, MaxMovieHeader).Payload);
// 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"))
@@ -68,9 +95,7 @@ internal static class AppleLivePhoto
var index = keyList.FindIndex(k => k.Type == "mdta" && Encoding.UTF8.GetString(k.Payload) == ContentIdentifier) + 1;
if (index == 0)
continue;
- var itemType = new byte[4];
- BinaryPrimitives.WriteUInt32BigEndian(itemType, (uint)index);
- foreach (var value in Children(values).Where(v => v.Type == Encoding.Latin1.GetString(itemType)))
+ foreach (var value in Children(values).Where(v => v.Type == Encoding.Latin1.GetString(U32((uint)index))))
{
var item = Children(value.Payload).FirstOrDefault(c => c.Type == "data").Payload;
if (item is { Length: > 8 } && Guid.TryParse(Encoding.UTF8.GetString(item, 8, item.Length - 8), out var id))
@@ -80,22 +105,125 @@ internal static class AppleLivePhoto
return null;
}
- private static byte[] ReadMovie(Stream file)
+ /// <summary>
+ /// Makes the MOV at <paramref name="path"/> (FFmpeg's, movie header at the end) the video of a Live Photo, as an
+ /// iPhone's are: <c>com.apple.quicktime.content.identifier</c> in the movie-level metadata (<c>moov/meta</c>:
+ /// <c>hdlr</c> "mdta", <c>keys</c>, <c>ilst</c>), and a timed metadata track (<c>mebx</c>, referring to the video
+ /// track) whose one sample, <c>com.apple.quicktime.still-image-time</c> = -1, is shown at
+ /// <paramref name="stillSeconds"/>, the photo's frame. Only the movie header is rewritten: the sample goes into a
+ /// small <c>mdat</c> where the header was, and no media data moves, so every chunk offset stays right.
+ /// </summary>
+ /// <exception cref="InvalidDataException">The movie is not as FFmpeg writes it.</exception>
+ public static void TagMovie(string path, string identifier, double stillSeconds)
{
- file.Position = 0;
- while (file.Position < file.Length)
+ using var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
+ var (moov, payload) = ReadMovieHeader(file, MaxMovieHeader);
+ if (moov.End != file.Length)
+ throw new InvalidDataException("The movie header must end the file.");
+ var children = Children(payload);
+ var mvhd = children.Single(c => c.Type == "mvhd").Payload;
+ if (mvhd.Length < 100)
+ throw new InvalidDataException("Invalid movie header.");
+ var longTimes = mvhd[0] == 1;
+ var timescale = BinaryPrimitives.ReadUInt32BigEndian(mvhd.AsSpan(longTimes ? 20 : 12));
+ var duration = longTimes ? BinaryPrimitives.ReadUInt64BigEndian(mvhd.AsSpan(24)) : BinaryPrimitives.ReadUInt32BigEndian(mvhd.AsSpan(16));
+ var created = longTimes ? 0 : BinaryPrimitives.ReadUInt32BigEndian(mvhd.AsSpan(4));
+ var trackId = BinaryPrimitives.ReadUInt32BigEndian(mvhd.AsSpan(mvhd.Length - 4));
+ if (timescale == 0 || trackId is 0 or uint.MaxValue)
+ throw new InvalidDataException("Invalid movie timescale or next track id.");
+ BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(mvhd.Length - 4), trackId + 1);
+
+ var video = children.FirstOrDefault(c => c.Type == "trak" && HandlerOf(c.Payload) == "vide").Payload
+ ?? throw new InvalidDataException("The movie has no video track.");
+ var tkhd = Children(video).Single(c => c.Type == "tkhd").Payload;
+ var videoId = BinaryPrimitives.ReadUInt32BigEndian(tkhd.AsSpan(tkhd[0] == 1 ? 20 : 12));
+
+ // The still is one tick long and starts at its frame: it must lie inside the movie.
+ var still = (ulong)Math.Round(Math.Max(0, stillSeconds) * timescale);
+ if (duration > 0)
+ still = Math.Min(still, duration - 1);
+ if (still >= uint.MaxValue)
+ throw new InvalidDataException("The still image time is outside the movie.");
+
+ // One sample: a 9-byte item of local key 1 (still-image-time), the int8 -1 an iPhone writes.
+ var sample = Box(LocalKey(1), new byte[] { 0xff });
+ var mdat = Box("mdat", sample);
+ var sampleOffset = (ulong)moov.Start + 8;
+ var track = StillImageTrack(trackId, videoId, created, timescale, (uint)still, sampleOffset, (uint)sample.Length);
+
+ var lastTrack = children.FindLastIndex(c => c.Type == "trak");
+ var boxes = new List<byte[]>();
+ for (var i = 0; i < children.Count; i++)
{
- 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;
+ // An identifier the source carried is replaced, never kept next to the new one.
+ if (children[i].Type != "meta")
+ boxes.Add(Box(children[i].Type, children[i].Payload));
+ if (i == lastTrack)
+ boxes.Add(track);
}
- throw new InvalidDataException("Live Photo has no movie metadata.");
+ boxes.Add(MovieMetadata(identifier));
+
+ file.SetLength(moov.Start);
+ file.Position = moov.Start;
+ file.Write(mdat);
+ file.Write(Box("moov", [.. boxes]));
+ }
+
+ /// <summary>The type of a key in a <c>mebx</c> sample entry, and of its items in a sample: the local id.</summary>
+ private static string LocalKey(uint id) => Encoding.Latin1.GetString(U32(id));
+
+ private static byte[] Ascii(string text) => Encoding.ASCII.GetBytes(text);
+
+ /// <summary>A QuickTime component name: one length byte, then the characters.</summary>
+ private static byte[] Pascal(string text) => [(byte)text.Length, .. Encoding.ASCII.GetBytes(text)];
+
+ /// <summary>
+ /// Movie-level metadata as Apple writes it: a plain <c>meta</c> container (no version and flags) with an "mdta"
+ /// handler, the key and its UTF-8 value (type 1, no locale).
+ /// </summary>
+ private static byte[] MovieMetadata(string identifier) =>
+ Box("meta",
+ Box("hdlr", new byte[8], Ascii("mdta"), new byte[14]),
+ FullBox("keys", 0, 0, U32(1), Box("mdta", Encoding.UTF8.GetBytes(ContentIdentifier))),
+ Box("ilst", Box(LocalKey(1), Box("data", U32(1), U32(0), Encoding.UTF8.GetBytes(identifier.ToUpperInvariant())))));
+
+ /// <summary>
+ /// The timed metadata track of the still image time, laid out like an iPhone's: track flags 0xF, an empty edit up
+ /// to the still, then the one-tick sample; media timescale = movie timescale; a "mhlr/meta" handler with a base
+ /// media header (<c>gmhd</c>), a self-referencing alias data reference, a <c>mebx</c> sample description whose
+ /// key 1 is <c>mdta</c> + still-image-time typed as a signed 8-bit integer; <c>cdsc</c> to the video track.
+ /// </summary>
+ private static byte[] StillImageTrack(uint id, uint videoId, uint created, uint timescale, uint still, ulong offset, uint sampleSize)
+ {
+ byte[] identity = [.. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x10000), .. U32(0), .. U32(0), .. U32(0), .. U32(0x40000000)];
+ var tkhd = FullBox("tkhd", 0, 0xf, U32(created), U32(created), U32(id), U32(0), U32(still + 1), new byte[8],
+ U16(0), U16(0), U16(0), U16(0), identity, U32(0), U32(0));
+ byte[] Edit(uint length, int mediaTime) => [.. U32(length), .. U32(unchecked((uint)mediaTime)), .. U16(1), .. U16(0)];
+ var edits = still > 0 ? new[] { Edit(still, -1), Edit(1, 0) } : [Edit(1, 0)];
+ var elst = FullBox("elst", 0, 0, [U32((uint)edits.Length), .. edits]);
+
+ var sampleEntry = Box("mebx", new byte[6], U16(1),
+ Box("keys", Box(LocalKey(1),
+ Box("keyd", Ascii("mdta"), Encoding.UTF8.GetBytes(StillImageTime)),
+ Box("dtyp", U32(0), U32(WellKnownInt8)))));
+ var chunkOffset = offset <= uint.MaxValue
+ ? FullBox("stco", 0, 0, U32(1), U32((uint)offset))
+ : FullBox("co64", 0, 0, U32(1), U64(offset));
+ var stbl = Box("stbl",
+ FullBox("stsd", 0, 0, U32(1), sampleEntry),
+ FullBox("stts", 0, 0, U32(1), U32(1), U32(1)),
+ FullBox("stsc", 0, 0, U32(1), U32(1), U32(1), U32(1)),
+ FullBox("stsz", 0, 0, U32(0), U32(1), U32(sampleSize)),
+ chunkOffset);
+ var minf = Box("minf",
+ Box("gmhd", FullBox("gmin", 0, 0, U16(0x40), U16(0x8000), U16(0x8000), U16(0x8000), U16(0), U16(0))),
+ FullBox("hdlr", 0, 0, Ascii("dhlr"), Ascii("alis"), Ascii("appl"), U32(0), U32(0), Pascal("Core Media Data Handler")),
+ Box("dinf", FullBox("dref", 0, 0, U32(1), FullBox("alis", 0, 1))),
+ stbl);
+ var mdia = Box("mdia",
+ FullBox("mdhd", 0, 0, U32(created), U32(created), U32(timescale), U32(1), U16(0x55c4), U16(0)),
+ FullBox("hdlr", 0, 0, Ascii("mhlr"), Ascii("meta"), Ascii("appl"), U32(1), U32(0), Pascal("Core Media Metadata")),
+ minf);
+ return Box("trak", tkhd, Box("edts", elst), Box("tref", Box("cdsc", U32(videoId))), mdia);
}
}
diff --git a/src/Filee.Engines/Media/FfmpegConverter.cs b/src/Filee.Engines/Media/FfmpegConverter.cs
index 041e9b95..637239f2 100644
--- a/src/Filee.Engines/Media/FfmpegConverter.cs
+++ b/src/Filee.Engines/Media/FfmpegConverter.cs
@@ -4,7 +4,8 @@
// 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).
-// Live / Motion Photos (Android, iPhone) give their video when a preset asks for it (LivePhotoSource, MotionPhoto).
+// Live / Motion Photos (Android, iPhone) give their video when a preset asks for it (LivePhotoSource, MotionPhoto), and
+// a clip of a video becomes one (LivePhotoWriter).
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
@@ -45,7 +46,7 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
public int MaxParallelism => 2;
/// <summary>Only HEIC, which ImageMagick reads and turns before x265 encodes it (Heic/HeicWriter); never video.</summary>
- public bool Transforms(string from, string to) => to == "heic";
+ public bool Transforms(string from, string to) => to == "heic" && FormatRegistry.FindById(from)?.Category != FormatCategory.Video;
public IReadOnlyList<ConversionEdge> Edges { get; } = BuildEdges();
@@ -89,6 +90,10 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
// 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),
+ // A clip of a video as a Live / Motion Photo, only when a preset asks for it (see ConversionEdge.LivePhoto).
+ .. from source in videos
+ from target in MediaOptions.LivePhotoTargets(LivePhotoKind.Apple).Union(MediaOptions.LivePhotoTargets(LivePhotoKind.Android))
+ select new ConversionEdge(source, target, LivePhoto: true),
];
}
@@ -113,6 +118,9 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
var (ffmpeg, ffprobe) = _tools ?? Locate() ?? throw new InvalidOperationException("FFmpeg was not found.");
if (step.MotionPhoto)
return await ExtractMotionAsync(step, progress, cancellationToken);
+ if (step.LivePhoto)
+ return await LivePhotoWriter.ConvertAsync(ffmpeg, ffprobe, step, EncodersOf(ffmpeg), filter => HasFilter(ffmpeg, filter),
+ progress, cancellationToken);
if (step.To == "heic")
return await HeicWriter.ConvertAsync(ffmpeg, step, progress, cancellationToken);
var input = Path.GetFullPath(step.InputPath);
@@ -335,6 +343,35 @@ public sealed partial class FfmpegConverter(ILogger? logger = null) : IConverter
}
});
+ private static readonly ConcurrentDictionary<string, IReadOnlySet<string>?> Filters = new();
+
+ /// <summary>
+ /// True when <paramref name="ffmpeg"/> has the filter <paramref name="name"/> (<c>ffmpeg -filters</c>, cached per
+ /// executable): a copy the user picked may lack zscale. Assumed when the list can't be read.
+ /// </summary>
+ internal static bool HasFilter(string ffmpeg, string name) =>
+ Filters.GetOrAdd($"{ffmpeg}|{File.GetLastWriteTimeUtc(ffmpeg).Ticks}", _ =>
+ {
+ try
+ {
+ var result = FfmpegRunner.RunBriefly(ffmpeg, ["-hide_banner", "-filters"], QueryTimeout);
+ return result.ExitCode == 0 ? ParseFilters(result.StandardOutput) : null;
+ }
+ catch (Exception ex) when (ex is TimeoutException or InvalidOperationException or System.ComponentModel.Win32Exception or IOException)
+ {
+ return null;
+ }
+ }) is not { } filters || filters.Contains(name);
+
+ /// <summary>The filter names in <c>ffmpeg -filters</c> output (" .S zscale V->V Apply resizing, …").</summary>
+ internal static IReadOnlySet<string> ParseFilters(string list) =>
+ list.Split('\n')
+ .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ .Where(parts => parts.Length >= 3 && parts[0].Length is 2 or 3 && parts[0].All(c => c is '.' or 'T' or 'S' or 'C')
+ && parts[2].Contains("->", StringComparison.Ordinal))
+ .Select(parts => parts[1])
+ .ToHashSet(StringComparer.Ordinal);
+
/// <summary>The encoder names in <c>ffmpeg -encoders</c> output.</summary>
internal static IReadOnlySet<string> ParseEncoders(string list) =>
// " V....D libx265 libx265 H.265 / HEVC (codec hevc)"
diff --git a/src/Filee.Engines/Media/LivePhotoWriter.cs b/src/Filee.Engines/Media/LivePhotoWriter.cs
new file mode 100644
index 00000000..aa50d7f3
--- /dev/null
+++ b/src/Filee.Engines/Media/LivePhotoWriter.cs
@@ -0,0 +1,273 @@
+// Video → a Live / Motion Photo of a short clip: an iPhone pair (a JPG or HEIC and a MOV with the same name and content
+// identifier) or an Android Motion Photo (one JPG with the clip appended). Everything is written in the work directory
+// and moved into place at the end, the pair together.
+
+using System.Globalization;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Heic;
+using ImageMagick;
+
+namespace Filee.Engines.Media;
+
+/// <summary>A clip of a video: its start and length in seconds, and the frame (at 30 fps) that becomes the photo.</summary>
+internal readonly record struct LivePhotoClip(double Start, double Length, int CoverFrame);
+
+internal static class LivePhotoWriter
+{
+ /// <summary>Frames per second of the clip: what phones record Live and Motion Photos at.</summary>
+ public const int Fps = 30;
+
+ /// <summary>The shorter side of the clip unless the preset asks for less: an iPhone's Live Photo video is 1440 × 1920.</summary>
+ public const int ShortSide = 1440;
+
+ /// <summary>
+ /// HDR (PQ or HLG) to SDR BT.709: phones show a Live / Motion Photo's video as SDR next to an SDR photo. Needs
+ /// FFmpeg's zscale filter (zimg).
+ /// </summary>
+ internal const string ToneMap =
+ "zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p,";
+
+ public static async Task<IReadOnlyList<string>> ConvertAsync(string ffmpeg, string ffprobe, ConversionStep step,
+ IReadOnlySet<string>? encoders, Func<string, bool> hasFilter, IProgress<double>? progress, CancellationToken ct)
+ {
+ var options = step.Preset.Media;
+ var apple = options.LivePhoto == LivePhotoKind.Apple;
+ var input = Path.GetFullPath(step.InputPath);
+ var info = await MediaInfo.ProbeAsync(ffprobe, input, ct);
+ var video = info.Video ?? throw new InvalidOperationException("The file has no video stream.");
+ var clip = Clip(options, info.Duration?.TotalSeconds);
+ if (video.IsHdr && !hasFilter("zscale"))
+ throw new ConversionRefusedException("error.live_photo_hdr");
+ var toneMap = video.IsHdr ? ToneMap : "";
+ progress?.Report(0.02);
+
+ // The names first: a file the output rules skip costs no encoding.
+ var photoExtension = step.To == "heic" ? "heic" : "jpg";
+ var targets = apple
+ ? AllocatePair(step.Output, photoExtension, input)
+ : step.Output.Allocate("jpg", ".MP") is { } single ? [single] : null;
+ if (targets is null)
+ return [];
+
+ var token = Guid.NewGuid().ToString("N");
+ var movie = Path.Combine(step.WorkDirectory, token + (apple ? ".mov" : ".mp4"));
+ var png = Path.Combine(step.WorkDirectory, token + ".png");
+ var photo = Path.Combine(step.WorkDirectory, token + "." + photoExtension);
+
+ var encoder = MediaEncoding.VideoEncoder("mov", "libx264", options.VideoCodec, encoders);
+ var audio = options.RemoveAudio ? null : info.Audio;
+ await FfmpegConverter.RunPassAsync(ffmpeg, new FfmpegPass(ClipArguments(input, movie, apple ? "mov" : "mp4", clip, video, audio,
+ options, encoder, toneMap), 0.8), TimeSpan.FromSeconds(clip.Length), progress, 0, ct);
+
+ // The frame of the photo, within the frames the clip really has (a video may end sooner than it says).
+ uint frames;
+ await using (var written = File.OpenRead(movie))
+ frames = MovieBoxes.VideoSampleCount(MovieBoxes.ReadMovieHeader(written).Payload);
+ if (frames == 0)
+ throw new InvalidOperationException("FFmpeg wrote a clip without frames.");
+ var cover = Math.Min(clip.CoverFrame, (int)frames - 1);
+ await FfmpegConverter.RunPassAsync(ffmpeg, new FfmpegPass(CoverArguments(input, png, clip.Start, cover, video, toneMap), 0.1),
+ null, progress, 0.8, ct);
+ if (!File.Exists(png))
+ throw new InvalidOperationException("FFmpeg did not write the photo's frame.");
+
+ var quality = Math.Clamp(step.Preset.Image.Quality, 1, 100);
+ var coverSeconds = (double)cover / Fps;
+ if (apple)
+ {
+ var id = Guid.NewGuid().ToString("D").ToUpperInvariant();
+ var exif = new ExifProfile();
+ exif.SetValue(ExifTag.MakerNote, AppleLivePhoto.MakerNote(id));
+ if (photoExtension == "heic")
+ {
+ var (width, height) = PictureSize(png);
+ await File.WriteAllBytesAsync(photo, await HeicWriter.EncodeAsync(ffmpeg, png, width, height, null, exif.ToByteArray(),
+ quality, step.WorkDirectory, ct), ct);
+ }
+ else
+ await File.WriteAllBytesAsync(photo, Jpeg(png, quality, exif), ct);
+ AppleLivePhoto.TagMovie(movie, id, coverSeconds);
+ Commit([(movie, targets[1]), (photo, targets[0])]);
+ step.Notice?.Invoke("notice.live_photo_pair");
+ }
+ else
+ {
+ await MotionPhoto.WriteAsync(Jpeg(png, quality, null), movie, photo, (long)Math.Round(coverSeconds * 1_000_000), ct);
+ Commit([(photo, targets[0])]);
+ }
+ progress?.Report(1);
+ return targets;
+ }
+
+ /// <summary>
+ /// The clip the preset asks for in a video of <paramref name="duration"/> seconds (null when unknown): the start,
+ /// a length of <see cref="MediaOptions.MinLivePhotoLength"/> to <see cref="MediaOptions.MaxLivePhotoLength"/>
+ /// seconds (shorter when the video ends sooner) and the photo's frame within it (its last frame at most).
+ /// </summary>
+ /// <exception cref="ConversionRefusedException"><c>error.live_photo_start</c>: the clip starts after the video ends.</exception>
+ internal static LivePhotoClip Clip(MediaOptions options, double? duration)
+ {
+ static double Finite(double value, double fallback) => double.IsFinite(value) ? value : fallback;
+ var start = Math.Max(0, Finite(options.LivePhotoStart, 0));
+ var length = Math.Clamp(Finite(options.LivePhotoLength, 3), MediaOptions.MinLivePhotoLength, MediaOptions.MaxLivePhotoLength);
+ if (duration is > 0 and var total)
+ {
+ // At least two frames, or there is nothing to move.
+ if (start > 0 && total - start < 2.0 / Fps)
+ throw new ConversionRefusedException("error.live_photo_start");
+ length = Math.Min(length, total - start);
+ }
+ var lastFrame = Math.Max(0, (int)Math.Ceiling(length * Fps - 1e-6) - 1);
+ var cover = Math.Max(0, Finite(options.LivePhotoCover, length / 2));
+ return new(start, length, Math.Min((int)Math.Floor(cover * Fps + 1e-6), lastFrame));
+ }
+
+ /// <summary>
+ /// The size of the clip: the picture as it is shown (pixel aspect and rotation applied) scaled down so that its
+ /// shorter side is at most <paramref name="maxShortSide"/>, with even sides.
+ /// </summary>
+ internal static (int Width, int Height) ClipSize(VideoStreamInfo video, int maxShortSide)
+ {
+ var width = video.Width * (video.SampleAspect > 0 ? video.SampleAspect : 1);
+ double height = video.Height;
+ if (video.IsRotated)
+ (width, height) = (height, width);
+ var scale = Math.Min(1, maxShortSide / Math.Max(1, Math.Min(width, height)));
+ static int Even(double value) => Math.Max(2, (int)Math.Round(value / 2) * 2);
+ return (Even(width * scale), Even(height * scale));
+ }
+
+ /// <summary>
+ /// The clip as a QuickTime movie (iPhone) or MP4 (Android): 30 fps, 8-bit 4:2:0 H.264 (HEVC when the preset asks,
+ /// tagged hvc1 for Apple), AAC in stereo or mono. FFmpeg turns the picture upright, so the orientation is kept
+ /// in the pixels. The movie header stays at the end, where <see cref="AppleLivePhoto.TagMovie"/> rewrites it.
+ /// </summary>
+ internal static List<string> ClipArguments(string input, string output, string muxer, LivePhotoClip clip, VideoStreamInfo video,
+ AudioStreamInfo? audio, MediaOptions options, string encoder, string toneMap)
+ {
+ var (width, height) = ClipSize(video, options.MaxHeight > 0 ? Math.Min(options.MaxHeight, ShortSide) : ShortSide);
+ List<string> args =
+ [
+ .. MediaEncoding.Common, "-ss", Seconds(clip.Start), "-i", input, "-map", "0:V:0",
+ .. audio is null ? Array.Empty<string>() : ["-map", "0:a:0"],
+ "-t", Seconds(clip.Length),
+ "-vf", $"{toneMap}fps={Fps},scale={width}:{height},setsar=1,format=yuv420p",
+ ];
+ var crf = Choose(options.Quality, encoder == "libx265" ? [22, 26, 30] : [18, 23, 28]);
+ args.AddRange(encoder == "libx265"
+ ? ["-c:v", "libx265", "-preset", "medium", "-crf", crf, "-x265-params", "log-level=error", "-tag:v", "hvc1"]
+ : ["-c:v", "libx264", "-preset", "medium", "-crf", crf, "-profile:v", "high"]);
+ args.AddRange(["-pix_fmt", "yuv420p"]);
+ if (toneMap.Length > 0)
+ args.AddRange(["-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709"]);
+ if (audio is null)
+ args.Add("-an");
+ else
+ {
+ var bitrate = options.AudioBitrateKbps > 0 ? options.AudioBitrateKbps : options.Quality == MediaQuality.Small ? 96 : 160;
+ args.AddRange(["-c:a", "aac", "-b:a", bitrate.ToString(CultureInfo.InvariantCulture) + "k",
+ "-ac", audio.Channels == 1 ? "1" : "2", "-ar", audio.SampleRate is 44100 or 48000 ? audio.SampleRate.ToString(CultureInfo.InvariantCulture) : "48000"]);
+ }
+ args.AddRange(["-sn", "-dn", "-map_chapters", "-1", "-map_metadata", "0", "-metadata", "major_brand=", "-metadata", "minor_version=",
+ "-metadata", "compatible_brands=", "-max_muxing_queue_size", "4096", "-f", muxer, "-progress", "pipe:1", output]);
+ return args;
+ }
+
+ /// <summary>
+ /// The photo: frame <paramref name="frame"/> of the clip at the video's full size, picked by the same 30 fps
+ /// timing as the clip so it is exactly the frame the still image time points at.
+ /// </summary>
+ internal static List<string> CoverArguments(string input, string output, double start, int frame, VideoStreamInfo video, string toneMap)
+ {
+ var square = Math.Abs(video.SampleAspect - 1) > 0.01 && video.SampleAspect > 0 ? "scale=w='trunc(iw*sar/2)*2':h=ih,setsar=1," : "";
+ return
+ [
+ .. MediaEncoding.Common, "-ss", Seconds(start), "-i", input, "-map", "0:V:0",
+ "-vf", $"{toneMap}fps={Fps},select=eq(n\\,{frame.ToString(CultureInfo.InvariantCulture)}),{square}format=rgb24",
+ "-frames:v", "1", "-fps_mode", "passthrough", "-update", "1", "-c:v", "png", "-f", "image2", "-progress", "pipe:1", output,
+ ];
+ }
+
+ /// <summary>
+ /// The paths of an iPhone pair: the photo where the output rules put it, and the MOV next to it with the same name.
+ /// When that MOV is taken (another file, or the video being converted) both get the next free number, so the two
+ /// always keep the same name. A MOV is only written over with the photo that is overwritten with it. Null when the
+ /// rules skip the photo.
+ /// </summary>
+ internal static string[]? AllocatePair(IOutputAllocator output, string photoExtension, string input)
+ {
+ for (var attempt = 1; attempt <= 100; attempt++)
+ {
+ var photo = output.Allocate(photoExtension, attempt == 1 ? null : $" ({attempt})");
+ if (photo is null)
+ return null;
+ var movie = Path.ChangeExtension(photo, "mov");
+ if (SamePath(movie, input) || Directory.Exists(movie))
+ continue;
+ if (File.Exists(photo) || !File.Exists(movie))
+ return [photo, movie];
+ }
+ throw new IOException("No free name for the Live Photo's photo and video.");
+ }
+
+ /// <summary>
+ /// Moves the finished files from the work directory into place: first next to their targets under a hidden name
+ /// (a move to another drive copies, which can fail without touching anything of the user's), then each renamed
+ /// over its target, in the order given. Hidden copies a failure leaves are removed.
+ /// </summary>
+ internal static void Commit(IReadOnlyList<(string Source, string Target)> files)
+ {
+ var staged = new List<(string Staged, string Target)>();
+ try
+ {
+ foreach (var (source, target) in files)
+ {
+ var stage = Path.Combine(Path.GetDirectoryName(target)!, $".filee-{Guid.NewGuid():N}{Path.GetExtension(target)}");
+ staged.Add((stage, target));
+ File.Move(source, stage);
+ }
+ foreach (var (stage, target) in staged)
+ File.Move(stage, target, overwrite: true);
+ }
+ finally
+ {
+ foreach (var (stage, _) in staged)
+ TryDelete(stage);
+ }
+ }
+
+ private static byte[] Jpeg(string png, int quality, ExifProfile? exif)
+ {
+ using var image = new MagickImage(png);
+ image.Quality = (uint)quality;
+ if (exif is not null)
+ image.SetProfile(exif);
+ return image.ToByteArray(MagickFormat.Jpeg);
+ }
+
+ private static (int Width, int Height) PictureSize(string png)
+ {
+ var info = new MagickImageInfo(png);
+ return ((int)info.Width, (int)info.Height);
+ }
+
+ private static string Choose(MediaQuality quality, int[] values) =>
+ values[quality switch { MediaQuality.High => 0, MediaQuality.Small => 2, _ => 1 }].ToString(CultureInfo.InvariantCulture);
+
+ private static string Seconds(double seconds) => seconds.ToString("0.######", CultureInfo.InvariantCulture);
+
+ private static bool SamePath(string a, string b) =>
+ string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase);
+
+ private static void TryDelete(string path)
+ {
+ try
+ {
+ if (File.Exists(path))
+ File.Delete(path);
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ }
+}
diff --git a/src/Filee.Engines/Media/MotionPhoto.cs b/src/Filee.Engines/Media/MotionPhoto.cs
index 3439d69e..928580bb 100644
--- a/src/Filee.Engines/Media/MotionPhoto.cs
+++ b/src/Filee.Engines/Media/MotionPhoto.cs
@@ -1,4 +1,5 @@
-// Android Motion Photos: where the video saved with a camera picture is, read from the picture's own metadata.
+// Android Motion Photos: where the video saved with a camera picture is, read from the picture's own metadata, and new
+// ones written the way a Pixel writes them.
using System.Buffers.Binary;
using System.Globalization;
@@ -22,6 +23,93 @@ internal static class MotionPhoto
/// <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>
+ /// Writes a Motion Photo 1.0 JPEG to <paramref name="output"/>: <paramref name="jpeg"/> with the Motion Photo XMP
+ /// after its JFIF and Exif segments (JFIF must come first), then the MP4 <paramref name="video"/> appended, ending
+ /// the file. The XMP is laid out as a Pixel writes it (<c>GCamera:MotionPhoto</c> 1, version 1, the still's
+ /// presentation time; a container directory of the primary JPEG and the video with its length and no padding),
+ /// plus the older MicroVideo properties (the same length as an offset from the end) for older Google Photos.
+ /// </summary>
+ public static async Task WriteAsync(byte[] jpeg, string video, string output, long presentationMicroseconds, CancellationToken ct)
+ {
+ var length = new FileInfo(video).Length;
+ var payload = Xmp(length, presentationMicroseconds);
+ var at = XmpPosition(jpeg);
+ await using var target = File.Create(output);
+ await target.WriteAsync(jpeg.AsMemory(0, at), ct);
+ var header = new byte[4];
+ header[0] = 0xff;
+ header[1] = 0xe1;
+ BinaryPrimitives.WriteUInt16BigEndian(header.AsSpan(2), checked((ushort)(payload.Length + 2)));
+ await target.WriteAsync(header, ct);
+ await target.WriteAsync(payload, ct);
+ await target.WriteAsync(jpeg.AsMemory(at), ct);
+ await using var movie = File.OpenRead(video);
+ await MovieBoxes.CopyRangeAsync(movie, target, length, ct);
+ }
+
+ /// <summary>The XMP segment's payload: the XMP signature, then the packet.</summary>
+ internal static byte[] Xmp(long videoLength, long presentationMicroseconds)
+ {
+ var length = videoLength.ToString(CultureInfo.InvariantCulture);
+ var time = presentationMicroseconds.ToString(CultureInfo.InvariantCulture);
+ 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 rdf:about=""
+ xmlns:GCamera="{Camera}"
+ xmlns:Container="{Container}"
+ xmlns:Item="{Item}"
+ GCamera:MotionPhoto="1"
+ GCamera:MotionPhotoVersion="1"
+ GCamera:MotionPhotoPresentationTimestampUs="{time}"
+ GCamera:MicroVideo="1"
+ GCamera:MicroVideoVersion="1"
+ GCamera:MicroVideoOffset="{length}"
+ GCamera:MicroVideoPresentationTimestampUs="{time}">
+ <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:Mime="video/mp4"
+ Item:Semantic="MotionPhoto"
+ Item:Length="{length}"
+ Item:Padding="0"/>
+ </rdf:li>
+ </rdf:Seq>
+ </Container:Directory>
+ </rdf:Description>
+ </rdf:RDF>
+ </x:xmpmeta>
+ """;
+ return [.. XmpHeader, .. Encoding.UTF8.GetBytes(xml)];
+ }
+
+ /// <summary>Where the XMP segment goes: after the start marker and the JFIF (APP0) and Exif (APP1) segments.</summary>
+ internal static int XmpPosition(byte[] jpeg)
+ {
+ if (jpeg.Length < 4 || jpeg[0] != 0xff || jpeg[1] != 0xd8)
+ throw new InvalidDataException("The Motion Photo's picture is not a JPEG.");
+ var at = 2;
+ while (at + 4 <= jpeg.Length && jpeg[at] == 0xff)
+ {
+ var marker = jpeg[at + 1];
+ var exif = marker == 0xe1 && jpeg.AsSpan(at + 4).StartsWith("Exif\0"u8);
+ if (marker != 0xe0 && !exif)
+ break;
+ var end = at + 2 + BinaryPrimitives.ReadUInt16BigEndian(jpeg.AsSpan(at + 2));
+ if (end > jpeg.Length)
+ throw new InvalidDataException("Invalid JPEG segment length.");
+ at = end;
+ }
+ return at;
+ }
+
/// <summary>
/// Finds the declared video, never by searching the picture's bytes for an MP4 signature. Null for a picture
/// without one.
diff --git a/src/Filee.Engines/Media/MovieBoxes.cs b/src/Filee.Engines/Media/MovieBoxes.cs
index 1aa96836..36231f68 100644
--- a/src/Filee.Engines/Media/MovieBoxes.cs
+++ b/src/Filee.Engines/Media/MovieBoxes.cs
@@ -1,4 +1,5 @@
-// Small, bounds-checked ISO BMFF box readers for photo metadata; media payloads are streamed, never loaded whole.
+// Small, bounds-checked ISO BMFF box readers for photo metadata, and the writers of the few boxes Filee adds; media
+// payloads are streamed, never loaded whole.
using System.Buffers.Binary;
using System.Text;
@@ -53,6 +54,100 @@ internal static class MovieBoxes
return result;
}
+ /// <summary>A box of <paramref name="type"/> (four Latin-1 characters) around <paramref name="parts"/>.</summary>
+ public static byte[] Box(string type, params byte[][] parts)
+ {
+ var box = new byte[checked(8 + parts.Sum(p => p.Length))];
+ BinaryPrimitives.WriteUInt32BigEndian(box, (uint)box.Length);
+ if (Encoding.Latin1.GetBytes(type, box.AsSpan(4)) != 4)
+ throw new ArgumentException("A box type has four characters.", nameof(type));
+ var at = 8;
+ foreach (var part in parts)
+ {
+ part.CopyTo(box, at);
+ at += part.Length;
+ }
+ return box;
+ }
+
+ /// <summary>A box that starts with a version and flags (a "full box").</summary>
+ public static byte[] FullBox(string type, byte version, uint flags, params byte[][] parts) =>
+ Box(type, [U32(((uint)version << 24) | (flags & 0xffffff)), .. parts]);
+
+ public static byte[] U16(int value)
+ {
+ var bytes = new byte[2];
+ BinaryPrimitives.WriteUInt16BigEndian(bytes, checked((ushort)value));
+ return bytes;
+ }
+
+ public static byte[] U32(uint value)
+ {
+ var bytes = new byte[4];
+ BinaryPrimitives.WriteUInt32BigEndian(bytes, value);
+ return bytes;
+ }
+
+ public static byte[] U64(ulong value)
+ {
+ var bytes = new byte[8];
+ BinaryPrimitives.WriteUInt64BigEndian(bytes, value);
+ return bytes;
+ }
+
+ /// <summary>The handler type of a track (<c>vide</c>, <c>soun</c>, <c>meta</c>, …), from its <c>mdia/hdlr</c>.</summary>
+ public static string? HandlerOf(byte[] trak)
+ {
+ var mdia = Children(trak).FirstOrDefault(c => c.Type == "mdia").Payload;
+ var hdlr = mdia is null ? null : Children(mdia).FirstOrDefault(c => c.Type == "hdlr").Payload;
+ return hdlr is { Length: >= 12 } ? Encoding.Latin1.GetString(hdlr, 8, 4) : null;
+ }
+
+ /// <summary>The samples (frames) of the first video track of the movie <paramref name="moov"/> (its payload).</summary>
+ public static uint VideoSampleCount(byte[] moov)
+ {
+ foreach (var trak in Children(moov).Where(c => c.Type == "trak").Select(c => c.Payload))
+ {
+ if (HandlerOf(trak) != "vide")
+ continue;
+ var stbl = Descend(trak, "mdia", "minf", "stbl");
+ var stsz = stbl is null ? null : Children(stbl).FirstOrDefault(c => c.Type == "stsz").Payload;
+ if (stsz is { Length: >= 12 })
+ return BinaryPrimitives.ReadUInt32BigEndian(stsz.AsSpan(8));
+ }
+ throw new InvalidDataException("The movie has no video track.");
+ }
+
+ /// <summary>The payload of the box at <paramref name="path"/> below <paramref name="parent"/>, or null.</summary>
+ private static byte[]? Descend(byte[] parent, params string[] path)
+ {
+ byte[]? current = parent;
+ foreach (var type in path)
+ current = current is null ? null : Children(current).FirstOrDefault(c => c.Type == type).Payload;
+ return current;
+ }
+
+ /// <summary>Reads the movie header (<c>moov</c>) of <paramref name="file"/>: its box and payload.</summary>
+ /// <exception cref="InvalidDataException">The file has none, or one larger than <paramref name="limit"/>.</exception>
+ public static (MovieBox Box, byte[] Payload) ReadMovieHeader(Stream file, int limit = 16 * 1024 * 1024)
+ {
+ file.Position = 0;
+ while (file.Position < file.Length)
+ {
+ var box = ReadHeader(file);
+ if (box.Type == "moov")
+ {
+ if (box.Length > limit)
+ throw new InvalidDataException("The movie header 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("The file has no movie header.");
+ }
+
/// <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)
{
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 573fa27c..b7922614 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -1804,6 +1804,48 @@ public class RenderTests
Assert.False(preset.Media.ExtractMotionPhoto);
}
+ [AvaloniaTheory]
+ [InlineData("en")]
+ [InlineData("ko")]
+ [InlineData("ja")]
+ [InlineData("zh-CN")]
+ [InlineData("ru")]
+ public void Live_photo_options_render_for_jpg_and_heic_and_save_only_there(string language)
+ {
+ TestServices.EnsureInitialized(language);
+ var preset = Filee.Core.Presets.BuiltInData.LivePhotoPresets().First();
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
+ Assert.True(vm.ShowLivePhotoChoice);
+ Assert.True(vm.IsLivePhoto);
+ Assert.False(vm.ShowImage);
+ Assert.False(vm.ShowSaveEveryFrame);
+ Assert.Equal(3, vm.LivePhotoKinds.Count);
+ var window = new PresetEditorWindow { DataContext = vm, Height = 980 };
+ window.Show();
+ Pump();
+ Save(window, $"preset-live-photo-{language}.png");
+ window.Close();
+
+ // HEIC is an iPhone's: no Motion Photo there.
+ vm.Target = vm.Targets.Single(t => t.Value == "heic");
+ Assert.Equal(2, vm.LivePhotoKinds.Count);
+ Assert.True(vm.IsLivePhoto);
+ vm.LivePhotoCodecChoice = vm.LivePhotoCodecs.Single(c => c.Value == Filee.Core.Presets.VideoCodec.Hevc);
+ vm.LivePhotoLength = 60;
+ Assert.True(vm.Apply());
+ Assert.Equal(("heic", Filee.Core.Presets.LivePhotoKind.Apple), (preset.TargetFormat, preset.Media.LivePhoto));
+ Assert.Equal(Filee.Core.Presets.VideoCodec.Hevc, preset.Media.VideoCodec);
+ Assert.Equal(Filee.Core.Presets.MediaOptions.MaxLivePhotoLength, preset.Media.LivePhotoLength);
+
+ // A kind left behind by a target that can't be one saves nothing.
+ var restored = new PresetEditorViewModel(preset, AppHost.Get<ILocalizer>());
+ restored.Target = restored.Targets.Single(t => t.Value == "png");
+ Assert.False(restored.ShowLivePhotoChoice);
+ Assert.True(restored.ShowImage);
+ Assert.True(restored.Apply());
+ Assert.Equal(Filee.Core.Presets.LivePhotoKind.None, preset.Media.LivePhoto);
+ }
+
private static void Pump()
{
// Let layout, bindings and a few animation frames run.
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index 7089e627..abb64cf6 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -954,6 +954,54 @@ public class UserDataStoreTests
Assert.Single(presets, p => p.Id == "extract-motion");
}
+ [Fact]
+ public void Version_29_libraries_get_the_live_photo_presets_after_extract_live_video_on_no_donut()
+ {
+ // As written with schema 29 (30 is another change's): no Live / Motion Photo presets.
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => p.Id is "live-photo-iphone" or "motion-photo-android");
+ var profiles = BuiltInData.CreateProfiles();
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(29, presets, profiles));
+
+ var iphone = presets.Single(p => p.Id == "live-photo-iphone");
+ var android = presets.Single(p => p.Id == "motion-photo-android");
+ Assert.Equal((LivePhotoKind.Apple, "jpg"), (iphone.Media.LivePhoto, iphone.TargetFormat));
+ Assert.Equal((LivePhotoKind.Android, "jpg"), (android.Media.LivePhoto, android.TargetFormat));
+ // Where a new library has them, on no donut.
+ Assert.Equal(BuiltInData.CreatePresets().Select(p => p.Id), presets.Select(p => p.Id));
+ Assert.Equal("extract-motion", presets[presets.IndexOf(iphone) - 1].Id);
+ Assert.DoesNotContain(profiles, p => p.PresetIds.Contains("live-photo-iphone") || p.PresetIds.Contains("motion-photo-android"));
+ Assert.False(SettingsMigrations.ApplyToLibrary(29, presets, profiles)); // once only
+
+ // Back from an older Filee, which dropped the option it didn't know: the preset makes Live Photos again.
+ iphone.Media.LivePhoto = LivePhotoKind.None;
+ iphone.Name = "My Live Photo";
+ Assert.True(SettingsMigrations.ApplyToLibrary(30, presets, profiles));
+ Assert.Equal(LivePhotoKind.Apple, iphone.Media.LivePhoto);
+ Assert.Equal("My Live Photo", iphone.Name);
+ Assert.Single(presets, p => p.Id == "live-photo-iphone");
+ }
+
+ [Fact]
+ public void Live_photo_options_survive_saving_and_unknown_kinds_read_as_none()
+ {
+ var preset = new Preset
+ {
+ TargetFormat = "heic",
+ Media = { LivePhoto = LivePhotoKind.Apple, LivePhotoStart = 2.5, LivePhotoLength = 2, LivePhotoCover = 0.5 },
+ };
+ var json = System.Text.Json.JsonSerializer.Serialize(preset, FileeJsonContext.Default.Preset);
+ Assert.Contains("\"livePhoto\": \"Apple\"", json);
+ var read = System.Text.Json.JsonSerializer.Deserialize(json, FileeJsonContext.Default.Preset)!;
+ Assert.Equal((LivePhotoKind.Apple, 2.5, 2.0, 0.5),
+ (read.Media.LivePhoto, read.Media.LivePhotoStart, read.Media.LivePhotoLength, read.Media.LivePhotoCover));
+
+ // A kind of a newer Filee: still one preset that loads, as a plain conversion.
+ var future = System.Text.Json.JsonSerializer.Deserialize(json.Replace("\"Apple\"", "\"Hologram\""), FileeJsonContext.Default.Preset)!;
+ Assert.Equal(LivePhotoKind.None, future.Media.LivePhoto);
+ }
+
[Fact]
public void Version_15_libraries_get_the_tracing_presets_on_the_images_donut_after_pdf()
{
diff --git a/tests/Filee.Engines.Tests/LivePhotoCreationTests.cs b/tests/Filee.Engines.Tests/LivePhotoCreationTests.cs
new file mode 100644
index 00000000..7f02eed5
--- /dev/null
+++ b/tests/Filee.Engines.Tests/LivePhotoCreationTests.cs
@@ -0,0 +1,467 @@
+// Video → Live / Motion Photo. The outputs are taken apart box by box and segment by segment: the structure an iPhone
+// and a Pixel write (identifiers, the still image time track, the XMP container directory and the appended MP4), then
+// played by ffprobe and read back by Filee's own Live / Motion Photo extraction.
+
+using System.Buffers.Binary;
+using System.Globalization;
+using System.Text;
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Core.Formats;
+using Filee.Core.Presets;
+using Filee.Engines.Media;
+using ImageMagick;
+
+namespace Filee.Engines.Tests;
+
+[Collection(nameof(FfmpegCollection))]
+public class LivePhotoCreationTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static (string Ffmpeg, string Ffprobe) Tools()
+ {
+ var tools = FfmpegConverter.Locate();
+ Assert.SkipUnless(tools is not null, "FFmpeg is not installed.");
+ return tools.Value;
+ }
+
+ private static Preset Live(LivePhotoKind kind, string target = "jpg", ConflictPolicy conflict = ConflictPolicy.Rename) =>
+ new() { TargetFormat = target, Media = { LivePhoto = kind }, Output = { Conflict = conflict } };
+
+ /// <summary>A test picture video with a sine tone (or without), 30 fps, as <paramref name="name"/> in a new folder.</summary>
+ private async Task<string> VideoAsync(string name = "clip.mp4", bool audio = true, int seconds = 4, string size = "320x240",
+ string[]? extra = null)
+ {
+ var path = Path.Combine(fx.NewFolder(), name);
+ 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", seconds.ToString(CultureInfo.InvariantCulture), .. extra ?? ["-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p"], "-c:a", "aac", path,
+ ], null, TestContext.Current.CancellationToken);
+ Assert.True(result.ExitCode == 0, result.StandardError);
+ return path;
+ }
+
+ private static IReadOnlyList<string> Outputs(ConversionJob job)
+ {
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey}: {f.ErrorDetail}")));
+ return [.. job.Outputs];
+ }
+
+ private static string Probe(string path, params string[] entries)
+ {
+ var result = FfmpegRunner.RunBriefly(Tools().Ffprobe, ["-v", "error", .. entries, path], TimeSpan.FromSeconds(30));
+ Assert.True(result.ExitCode == 0, result.StandardError);
+ return result.StandardOutput;
+ }
+
+ // ───────────────────────── iPhone ─────────────────────────
+
+ [Theory]
+ [InlineData("jpg", true)]
+ [InlineData("jpg", false)]
+ [InlineData("heic", true)]
+ public async Task Iphone_live_photo_is_a_photo_and_a_mov_sharing_one_identifier(string target, bool audio)
+ {
+ var video = await VideoAsync(audio: audio);
+ var outputs = Outputs(await fx.ConvertAsync([video], Live(LivePhotoKind.Apple, target)));
+ Assert.Equal(2, outputs.Count);
+ var photo = Assert.Single(outputs, p => p.EndsWith("." + target, StringComparison.Ordinal));
+ var movie = Assert.Single(outputs, p => p.EndsWith(".mov", StringComparison.Ordinal));
+ Assert.Equal(Path.Combine(Path.GetDirectoryName(video)!, "clip"), Path.ChangeExtension(photo, null));
+ Assert.Equal(Path.ChangeExtension(photo, null), Path.ChangeExtension(movie, null));
+
+ // The same identifier in the maker note (tag 17) and the movie's metadata, upper case as Apple writes it.
+ var id = AppleLivePhoto.ImageIdentifier(photo);
+ Assert.NotNull(id);
+ Assert.Equal(id, AppleLivePhoto.MovieIdentifier(movie), StringComparer.OrdinalIgnoreCase);
+ var movieBytes = await File.ReadAllBytesAsync(movie, TestContext.Current.CancellationToken);
+ Assert.True(movieBytes.AsSpan().IndexOf(Encoding.ASCII.GetBytes(id.ToUpperInvariant())) >= 0);
+
+ var still = StillImageTrack(movie);
+ // The default photo is the middle of the 3-second clip: frame 45 at 30 fps, 1.5 s.
+ Assert.Equal(1.5, still.Seconds, 3);
+ Assert.Equal(still.VideoTrackId, still.DescribedTrackId);
+
+ // ffprobe plays it: the clip, its sound, and the timed metadata as a mebx data stream.
+ var info = await MediaInfo.ProbeAsync(Tools().Ffprobe, movie, TestContext.Current.CancellationToken);
+ Assert.InRange(info.Duration!.Value.TotalSeconds, 2.9, 3.1);
+ Assert.Equal(audio, info.Audio is not null);
+ Assert.Equal((320, 240), (info.Video!.Width, info.Video.Height));
+ Assert.Contains("mebx", Probe(movie, "-show_entries", "stream=codec_tag_string", "-of", "csv=p=0"));
+ Assert.StartsWith("qt ", Encoding.Latin1.GetString(await ReadAtAsync(movie, 8, 4)));
+
+ using (var picture = new MagickImage())
+ {
+ picture.Ping(photo);
+ Assert.Equal((320u, 240u), (picture.Width, picture.Height));
+ }
+ if (target == "jpg")
+ Assert.Equal("JFIF", Segments(await File.ReadAllBytesAsync(photo, TestContext.Current.CancellationToken))[0].Name);
+
+ // Filee's own extraction recognises the pair: the photo gives the MOV next to it.
+ var extract = new Preset { TargetFormat = "mp4", Media = { ExtractMotionPhoto = true } };
+ var extracted = Assert.Single(Outputs(await fx.ConvertAsync([photo], extract)));
+ Assert.InRange((await MediaInfo.ProbeAsync(Tools().Ffprobe, extracted, TestContext.Current.CancellationToken)).Duration!.Value.TotalSeconds, 2.9, 3.1);
+ }
+
+ [Fact]
+ public async Task Clip_start_length_and_photo_frame_follow_the_preset()
+ {
+ var video = await VideoAsync(seconds: 6);
+ var preset = Live(LivePhotoKind.Apple);
+ preset.Media.LivePhotoStart = 2;
+ preset.Media.LivePhotoLength = 2.5;
+ preset.Media.LivePhotoCover = 0.4;
+ var movie = Outputs(await fx.ConvertAsync([video], preset)).Single(p => p.EndsWith(".mov", StringComparison.Ordinal));
+ Assert.InRange((await MediaInfo.ProbeAsync(Tools().Ffprobe, movie, TestContext.Current.CancellationToken)).Duration!.Value.TotalSeconds, 2.4, 2.6);
+ Assert.Equal(0.4, StillImageTrack(movie).Seconds, 3);
+
+ // A photo time past the end of the clip is its last frame; a start past the end of the video is refused.
+ preset.Media.LivePhotoStart = 5;
+ preset.Media.LivePhotoCover = 4;
+ var shortened = Outputs(await fx.ConvertAsync([video], preset)).Single(p => p.EndsWith(".mov", StringComparison.Ordinal));
+ Assert.Equal(29 / 30.0, StillImageTrack(shortened).Seconds, 3);
+ preset.Media.LivePhotoStart = 30;
+ var refused = await fx.ConvertAsync([video], preset);
+ Assert.Equal("error.live_photo_start", refused.Files.Single().ErrorKey);
+ }
+
+ [Fact]
+ public async Task Portrait_phone_video_stays_upright_in_the_photo_and_the_clip()
+ {
+ // 320×240 recorded sideways: the display matrix turns it, as phones do.
+ var source = await VideoAsync();
+ var rotated = Path.Combine(fx.NewFolder(), "portrait.mov");
+ var result = await FfmpegRunner.RunAsync(Tools().Ffmpeg, [.. MediaEncoding.Common, "-display_rotation", "90", "-i", source, "-c", "copy", rotated],
+ null, TestContext.Current.CancellationToken);
+ Assert.True(result.ExitCode == 0, result.StandardError);
+
+ var outputs = Outputs(await fx.ConvertAsync([rotated], Live(LivePhotoKind.Apple)));
+ var info = await MediaInfo.ProbeAsync(Tools().Ffprobe, outputs.Single(p => p.EndsWith(".mov", StringComparison.Ordinal)),
+ TestContext.Current.CancellationToken);
+ Assert.Equal((240, 320, 0), (info.Video!.Width, info.Video.Height, info.Video.Rotation));
+ using var photo = new MagickImage(outputs.Single(p => p.EndsWith(".jpg", StringComparison.Ordinal)));
+ Assert.Equal((240u, 320u), (photo.Width, photo.Height));
+ }
+
+ [Fact]
+ public async Task The_pair_keeps_one_name_and_never_takes_the_videos_own()
+ {
+ // clip.mov is the video itself: the pair becomes "clip (2)", even when told to overwrite.
+ var video = await VideoAsync("clip.mov");
+ var original = await File.ReadAllBytesAsync(video, TestContext.Current.CancellationToken);
+ var outputs = Outputs(await fx.ConvertAsync([video], Live(LivePhotoKind.Apple, conflict: ConflictPolicy.Overwrite)));
+ var folder = Path.GetDirectoryName(video)!;
+ Assert.Equal(new[] { Path.Combine(folder, "clip (2).jpg"), Path.Combine(folder, "clip (2).mov") }, outputs.Order());
+ Assert.Equal(original, await File.ReadAllBytesAsync(video, TestContext.Current.CancellationToken));
+
+ // Another MOV of that name: both files move on to the next number together.
+ var other = await VideoAsync("trip.mp4");
+ var foreign = Path.Combine(Path.GetDirectoryName(other)!, "trip.mov");
+ await File.WriteAllTextAsync(foreign, "someone else's video", TestContext.Current.CancellationToken);
+ var renamed = Outputs(await fx.ConvertAsync([other], Live(LivePhotoKind.Apple)));
+ Assert.Equal(new[] { "trip (2).jpg", "trip (2).mov" }, renamed.Select(Path.GetFileName).Order());
+ Assert.Equal("someone else's video", await File.ReadAllTextAsync(foreign, TestContext.Current.CancellationToken));
+
+ // Skip: an existing photo skips the whole pair.
+ var skipped = await fx.ConvertAsync([other], Live(LivePhotoKind.Apple, conflict: ConflictPolicy.Skip));
+ Assert.Equal(FileState.Skipped, skipped.Files.Single().State);
+ }
+
+ [Fact]
+ public async Task A_failed_live_photo_leaves_the_files_it_would_replace()
+ {
+ var folder = fx.NewFolder();
+ var broken = Path.Combine(folder, "broken.mp4");
+ await File.WriteAllBytesAsync(broken, [0, 0, 0, 24, .. "ftypisom"u8.ToArray(), .. new byte[64]], TestContext.Current.CancellationToken);
+ var photo = Path.Combine(folder, "broken.jpg");
+ var movie = Path.Combine(folder, "broken.mov");
+ await File.WriteAllTextAsync(photo, "the user's photo", TestContext.Current.CancellationToken);
+ await File.WriteAllTextAsync(movie, "the user's video", TestContext.Current.CancellationToken);
+ Tools();
+
+ var job = await fx.ConvertAsync([broken], Live(LivePhotoKind.Apple, conflict: ConflictPolicy.Overwrite));
+ Assert.Equal(FileState.Failed, job.Files.Single().State);
+ Assert.Equal("the user's photo", await File.ReadAllTextAsync(photo, TestContext.Current.CancellationToken));
+ Assert.Equal("the user's video", await File.ReadAllTextAsync(movie, TestContext.Current.CancellationToken));
+ Assert.Equal(3, Directory.GetFiles(folder).Length);
+ }
+
+ [Fact]
+ public async Task Hdr_video_is_tone_mapped_to_sdr()
+ {
+ var (ffmpeg, _) = Tools();
+ Assert.SkipUnless(FfmpegConverter.HasFilter(ffmpeg, "zscale"), "This FFmpeg has no zscale.");
+ // HLG as phones record it; the encoder takes the colour tags from the frames.
+ var video = await VideoAsync("hlg.mov", extra: ["-vf", "setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc",
+ "-c:v", "libx265", "-preset", "ultrafast", "-pix_fmt", "yuv420p10le", "-x265-params", "log-level=error"]);
+ Assert.True((await MediaInfo.ProbeAsync(Tools().Ffprobe, video, TestContext.Current.CancellationToken)).Video!.IsHdr);
+
+ var movie = Outputs(await fx.ConvertAsync([video], Live(LivePhotoKind.Android))).Single();
+ var info = await MediaInfo.ProbeAsync(Tools().Ffprobe, await TailAsync(movie), TestContext.Current.CancellationToken);
+ Assert.False(info.Video!.IsHdr);
+ Assert.Equal("yuv420p", info.Video.PixelFormat);
+ }
+
+ // ───────────────────────── Android ─────────────────────────
+
+ [Theory]
+ [InlineData(true, VideoCodec.Default)]
+ [InlineData(false, VideoCodec.Hevc)]
+ public async Task Android_motion_photo_is_one_jpg_with_the_mp4_at_its_end(bool audio, VideoCodec codec)
+ {
+ var video = await VideoAsync(audio: audio);
+ var preset = Live(LivePhotoKind.Android);
+ preset.Media.VideoCodec = codec;
+ var photo = Assert.Single(Outputs(await fx.ConvertAsync([video], preset)));
+ Assert.Equal("clip.MP.jpg", Path.GetFileName(photo));
+ Assert.Equal("jpg", FormatRegistry.Detect(photo)!.Id);
+
+ var bytes = await File.ReadAllBytesAsync(photo, TestContext.Current.CancellationToken);
+ var segments = Segments(bytes);
+ // JFIF first, then the XMP.
+ Assert.Equal("JFIF", segments[0].Name);
+ var xmp = segments.Single(s => s.Name == "http://ns.adobe.com/xap/1.0/");
+ var xml = XDocument.Parse(Encoding.UTF8.GetString(bytes, xmp.Offset + 29, xmp.Length - 29));
+ XNamespace camera = "http://ns.google.com/photos/1.0/camera/", container = "http://ns.google.com/photos/1.0/container/",
+ item = "http://ns.google.com/photos/1.0/container/item/";
+ var description = xml.Descendants().Single(e => e.Attribute(camera + "MotionPhoto") is not null);
+ Assert.Equal("1", description.Attribute(camera + "MotionPhoto")!.Value);
+ Assert.Equal("1", description.Attribute(camera + "MotionPhotoVersion")!.Value);
+ Assert.Equal("1500000", description.Attribute(camera + "MotionPhotoPresentationTimestampUs")!.Value);
+ var items = xml.Descendants(container + "Item").ToList();
+ Assert.Equal(new[] { "Primary", "MotionPhoto" }, items.Select(i => i.Attribute(item + "Semantic")!.Value));
+ Assert.Equal("image/jpeg", items[0].Attribute(item + "Mime")!.Value);
+ Assert.Equal("video/mp4", items[1].Attribute(item + "Mime")!.Value);
+ Assert.Equal("0", items[1].Attribute(item + "Padding")!.Value);
+ var length = long.Parse(items[1].Attribute(item + "Length")!.Value, CultureInfo.InvariantCulture);
+ Assert.Equal(length.ToString(CultureInfo.InvariantCulture), description.Attribute(camera + "MicroVideoOffset")!.Value);
+
+ // The length is the MP4's, which ends the file: it starts with ftyp right after the JPEG's end marker.
+ var start = bytes.Length - length;
+ Assert.Equal("ftyp", Encoding.Latin1.GetString(bytes, (int)start + 4, 4));
+ Assert.Equal(new byte[] { 0xff, 0xd9 }, bytes[((int)start - 2)..(int)start]);
+ await using (var file = File.OpenRead(photo))
+ Assert.Equal((start, length), MotionPhoto.FindVideo(file));
+
+ var tail = await TailAsync(photo);
+ var info = await MediaInfo.ProbeAsync(Tools().Ffprobe, tail, TestContext.Current.CancellationToken);
+ Assert.InRange(info.Duration!.Value.TotalSeconds, 2.9, 3.1);
+ Assert.Equal(audio, info.Audio is not null);
+ Assert.Equal(codec == VideoCodec.Hevc ? "hevc" : "h264", info.Video!.Codec);
+ using (var picture = new MagickImage(photo))
+ Assert.Equal((320u, 240u), (picture.Width, picture.Height));
+
+ // Filee's own extraction takes the video out again.
+ var extract = new Preset { TargetFormat = "mp4", Media = { ExtractMotionPhoto = true } };
+ var extracted = Assert.Single(Outputs(await fx.ConvertAsync([photo], extract)));
+ Assert.InRange((await MediaInfo.ProbeAsync(Tools().Ffprobe, extracted, TestContext.Current.CancellationToken)).Duration!.Value.TotalSeconds, 2.9, 3.1);
+ }
+
+ // ───────────────────────── Without FFmpeg ─────────────────────────
+
+ [Fact]
+ public void Live_photo_edges_are_taken_only_when_asked_for()
+ {
+ var planner = fx.Catalog.CreatePlanner(["ffmpeg"]);
+ var step = Assert.Single(planner.Plan("mp4", "jpg", livePhoto: true)!.Steps);
+ Assert.True(step.LivePhoto);
+ Assert.True(Assert.Single(planner.Plan("mov", "heic", livePhoto: true)!.Steps).LivePhoto);
+ Assert.All(planner.Plan("mp4", "jpg")!.Steps, s => Assert.False(s.LivePhoto));
+ Assert.Null(planner.Plan("mp4", "png", livePhoto: true));
+ Assert.Null(planner.Plan("png", "jpg", livePhoto: true));
+
+ Assert.True(Live(LivePhotoKind.Apple).MakesLivePhotoOf("mp4"));
+ Assert.True(Live(LivePhotoKind.Apple, "heic").MakesLivePhotoOf("mov"));
+ Assert.False(Live(LivePhotoKind.Android, "heic").MakesLivePhotoOf("mov"));
+ Assert.False(Live(LivePhotoKind.Apple).MakesLivePhotoOf("png"));
+ Assert.False(Live(LivePhotoKind.None).MakesLivePhotoOf("mp4"));
+ // Never every frame and a Live Photo at once.
+ var both = Live(LivePhotoKind.Apple);
+ both.Media.SaveEveryFrame = true;
+ Assert.False(both.SavesFramesOf("mp4"));
+ Assert.Equal(2, BuiltInData.LivePhotoPresets().Count(p => p.MakesLivePhotoOf("mp4")));
+ }
+
+ [Theory]
+ [InlineData(0.0, 3.0, 1.5, 10.0, 0.0, 3.0, 45)]
+ [InlineData(0.0, 3.0, 1.5, 1.0, 0.0, 1.0, 29)]
+ [InlineData(8.0, 3.0, 1.0, 10.0, 8.0, 2.0, 30)]
+ [InlineData(0.0, 60.0, 99.0, null, 0.0, 5.0, 149)]
+ [InlineData(-4.0, 0.01, -1.0, 10.0, 0.0, 0.5, 0)]
+ public void Clip_is_bounded_by_the_video_and_the_limits(double start, double length, double cover, double? duration,
+ double expectedStart, double expectedLength, int expectedFrame)
+ {
+ var clip = LivePhotoWriter.Clip(new MediaOptions { LivePhotoStart = start, LivePhotoLength = length, LivePhotoCover = cover }, duration);
+ Assert.Equal(expectedStart, clip.Start, 6);
+ Assert.Equal(expectedLength, clip.Length, 6);
+ Assert.Equal(expectedFrame, clip.CoverFrame);
+ Assert.Throws<ConversionRefusedException>(() => LivePhotoWriter.Clip(new MediaOptions { LivePhotoStart = 10 }, 10));
+ }
+
+ [Fact]
+ public void Clip_size_keeps_the_shown_shape_and_limits_the_shorter_side()
+ {
+ Assert.Equal((2560, 1440), LivePhotoWriter.ClipSize(new VideoStreamInfo(3840, 2160, 1, 0, 30), 1440));
+ Assert.Equal((1440, 2560), LivePhotoWriter.ClipSize(new VideoStreamInfo(3840, 2160, 1, -90, 30), 1440));
+ Assert.Equal((320, 240), LivePhotoWriter.ClipSize(new VideoStreamInfo(320, 240, 1, 0, 30), 1440));
+ // Anamorphic DV: square pixels.
+ Assert.Equal((640, 480), LivePhotoWriter.ClipSize(new VideoStreamInfo(720, 480, 8 / 9.0, 0, 30), 1440));
+ Assert.Equal((960, 720), LivePhotoWriter.ClipSize(new VideoStreamInfo(1920, 1440, 1, 0, 30), 720));
+ }
+
+ [Fact]
+ public void Maker_note_is_apples_layout_and_reads_back()
+ {
+ const string id = "6f2c8e8a-1a3b-4c5d-9e0f-112233445566";
+ var note = AppleLivePhoto.MakerNote(id);
+ Assert.StartsWith("Apple iOS\0\0\u0001MM", Encoding.Latin1.GetString(note));
+ Assert.Equal(1, BinaryPrimitives.ReadUInt16BigEndian(note.AsSpan(14)));
+ Assert.Equal((17, 2, 37u, 32u), (BinaryPrimitives.ReadUInt16BigEndian(note.AsSpan(16)), BinaryPrimitives.ReadUInt16BigEndian(note.AsSpan(18)),
+ BinaryPrimitives.ReadUInt32BigEndian(note.AsSpan(20)), BinaryPrimitives.ReadUInt32BigEndian(note.AsSpan(24))));
+ Assert.Equal(id.ToUpperInvariant() + "\0", Encoding.ASCII.GetString(note, 32, 37));
+ Assert.Equal(id, AppleLivePhoto.ReadMakerNote(note));
+ }
+
+ [Fact]
+ public void Xmp_goes_after_jfif_and_exif()
+ {
+ using var image = new MagickImage(MagickColors.Teal, 8, 8);
+ var exif = new ExifProfile();
+ exif.SetValue(ExifTag.Software, "test");
+ image.SetProfile(exif);
+ var jpeg = image.ToByteArray(MagickFormat.Jpeg);
+ var segments = Segments(jpeg);
+ Assert.Equal(new[] { "JFIF", "Exif" }, segments.Take(2).Select(s => s.Name));
+ Assert.Equal(segments[2].Offset - 4, MotionPhoto.XmpPosition(jpeg));
+ Assert.Equal(2, MotionPhoto.XmpPosition([0xff, 0xd8, 0xff, 0xdb, 0, 2]));
+ Assert.Throws<InvalidDataException>(() => MotionPhoto.XmpPosition([0x89, 0x50, 0x4e, 0x47]));
+ }
+
+ [Fact]
+ public void Filter_list_is_read_from_ffmpeg_output()
+ {
+ var filters = FfmpegConverter.ParseFilters("""
+ Filters:
+ T.. = Timeline support
+ ...
+ .. libplacebo N->V Apply various GPU filters from libplacebo
+ .S zscale V->V Apply resizing, colorspace and bit depth conversion.
+ TSC scale V->V Scale the input video size.
+ """.Replace("\r", ""));
+ Assert.Equal(new[] { "libplacebo", "scale", "zscale" }, filters.Order());
+ }
+
+ [Fact]
+ public void Pair_allocation_moves_both_names_on_together()
+ {
+ var folder = fx.NewFolder();
+ var input = Path.Combine(folder, "a.mov");
+ File.WriteAllText(input, "");
+ File.WriteAllText(Path.Combine(folder, "a (2).mov"), "");
+ var output = new NumberingOutput(folder, "a");
+ Assert.Equal(new[] { Path.Combine(folder, "a (3).jpg"), Path.Combine(folder, "a (3).mov") }, LivePhotoWriter.AllocatePair(output, "jpg", input));
+ Assert.Null(LivePhotoWriter.AllocatePair(new SkippingOutput(), "jpg", input));
+ }
+
+ /// <summary>Hands out "name" + suffix, as the output rules do for a free name.</summary>
+ private sealed class NumberingOutput(string folder, string name) : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null) => Path.Combine(folder, $"{name}{suffix}.{extension}");
+ }
+
+ private sealed class SkippingOutput : IOutputAllocator
+ {
+ public string? Allocate(string extension, string? suffix = null) => null;
+ }
+
+ // ───────────────────────── Reading the outputs ─────────────────────────
+
+ private sealed record StillImage(double Seconds, uint VideoTrackId, uint DescribedTrackId);
+
+ /// <summary>
+ /// The still image time track of <paramref name="movie"/>, checked against the layout an iPhone writes, with the
+ /// time its one sample is shown at.
+ /// </summary>
+ private static StillImage StillImageTrack(string movie)
+ {
+ var bytes = File.ReadAllBytes(movie);
+ using var stream = new MemoryStream(bytes);
+ var moov = MovieBoxes.ReadMovieHeader(stream).Payload;
+ var children = MovieBoxes.Children(moov);
+ var mvhd = children.Single(c => c.Type == "mvhd").Payload;
+ var timescale = BinaryPrimitives.ReadUInt32BigEndian(mvhd.AsSpan(12));
+ var video = children.Single(c => c.Type == "trak" && MovieBoxes.HandlerOf(c.Payload) == "vide").Payload;
+ var videoId = BinaryPrimitives.ReadUInt32BigEndian(Child(video, "tkhd").AsSpan(12));
+ var track = children.Single(c => c.Type == "trak" && MovieBoxes.HandlerOf(c.Payload) == "meta").Payload;
+
+ var tkhd = Child(track, "tkhd");
+ Assert.Equal(0xfu, BinaryPrimitives.ReadUInt32BigEndian(tkhd) & 0xffffff);
+ var mdia = Child(track, "mdia");
+ Assert.Equal("mhlrmetaappl", Encoding.Latin1.GetString(Child(mdia, "hdlr"), 4, 12));
+ Assert.Equal(timescale, BinaryPrimitives.ReadUInt32BigEndian(Child(mdia, "mdhd").AsSpan(12)));
+ var minf = Child(mdia, "minf");
+ Assert.NotNull(Child(minf, "gmhd"));
+ var stbl = Child(minf, "stbl");
+ var stsd = Child(stbl, "stsd");
+ var entry = MovieBoxes.Children(stsd, 8).Single();
+ Assert.Equal("mebx", entry.Type);
+ var key = MovieBoxes.Children(MovieBoxes.Children(entry.Payload, 8).Single(c => c.Type == "keys").Payload).Single();
+ Assert.Equal(1u, BinaryPrimitives.ReadUInt32BigEndian(Encoding.Latin1.GetBytes(key.Type)));
+ var parts = MovieBoxes.Children(key.Payload);
+ Assert.Equal("mdta" + AppleLivePhoto.StillImageTime, Encoding.UTF8.GetString(parts.Single(p => p.Type == "keyd").Payload));
+ Assert.Equal(new byte[] { 0, 0, 0, 0, 0, 0, 0, 65 }, parts.Single(p => p.Type == "dtyp").Payload);
+
+ // One 9-byte sample: item size, local key 1, int8 -1.
+ Assert.Equal(9u, BinaryPrimitives.ReadUInt32BigEndian(Child(stbl, "stsz").AsSpan(12)));
+ var offset = BinaryPrimitives.ReadUInt32BigEndian(Child(stbl, "stco").AsSpan(8));
+ Assert.Equal(new byte[] { 0, 0, 0, 9, 0, 0, 0, 1, 0xff }, bytes[(int)offset..(int)(offset + 9)]);
+
+ var described = BinaryPrimitives.ReadUInt32BigEndian(Child(Child(track, "tref"), "cdsc"));
+ // The edit list: an empty edit up to the still (when it isn't the first frame), then the sample.
+ var elst = Child(Child(track, "edts"), "elst");
+ var edits = BinaryPrimitives.ReadUInt32BigEndian(elst.AsSpan(4));
+ var before = edits == 2 && BinaryPrimitives.ReadInt32BigEndian(elst.AsSpan(12)) == -1
+ ? BinaryPrimitives.ReadUInt32BigEndian(elst.AsSpan(8))
+ : 0;
+ return new((double)before / timescale, videoId, described);
+ }
+
+ private static byte[] Child(byte[] parent, string type) => MovieBoxes.Children(parent).Single(c => c.Type == type).Payload;
+
+ /// <summary>The JPEG's segments up to the picture data: marker, offset of the payload, its length, its signature.</summary>
+ private static List<(byte Marker, int Offset, int Length, string Name)> Segments(byte[] jpeg)
+ {
+ var segments = new List<(byte, int, int, string)>();
+ var at = 2;
+ while (at + 4 <= jpeg.Length && jpeg[at] == 0xff && jpeg[at + 1] != 0xda)
+ {
+ var length = BinaryPrimitives.ReadUInt16BigEndian(jpeg.AsSpan(at + 2)) - 2;
+ var name = Encoding.Latin1.GetString(jpeg, at + 4, Math.Min(length, 40)).Split('\0')[0];
+ segments.Add((jpeg[at + 1], at + 4, length, name));
+ at += 4 + length;
+ }
+ return segments;
+ }
+
+ private static async Task<byte[]> ReadAtAsync(string path, long offset, int count)
+ {
+ await using var file = File.OpenRead(path);
+ file.Position = offset;
+ var data = new byte[count];
+ await file.ReadExactlyAsync(data, TestContext.Current.CancellationToken);
+ return data;
+ }
+
+ /// <summary>The MP4 appended to a Motion Photo, saved on its own.</summary>
+ private async Task<string> TailAsync(string photo)
+ {
+ await using var file = File.OpenRead(photo);
+ var (offset, length) = MotionPhoto.FindVideo(file)!.Value;
+ var path = Path.Combine(fx.NewFolder(), "tail.mp4");
+ file.Position = offset;
+ await using var target = File.Create(path);
+ await MovieBoxes.CopyRangeAsync(file, target, length, TestContext.Current.CancellationToken);
+ return path;
+ }
+}