Read capture metadata with LightCraft, including Canon CR3.
The property page used exifr, which never sees a CR3, so every frame and its XMP sidecar looked unexposed. JPEG sports ingest still uses exifr for the Photo Mechanic pad, the Lisbon clock and the focus point. Fixes #77
This commit is contained in:
1 parent
1c12ead5a1
commit
3b8cf24974
16 files changed
+515
-128
No files matched your search
@@ -5,6 +5,10 @@ import exifr from "exifr";
|
||||
* IPTC already in an incoming file (camera presets, or a photo captioned in Lightroom/Photo Mechanic).
|
||||
* XMP is read first: it is always UTF-8. IIM is the fallback, and Lightroom and Photo Mechanic on the Mac write
|
||||
* it in Mac Roman without saying so ("Pavilh‹o" for "Pavilhão"), which is repaired here.
|
||||
*
|
||||
* LightCraft's metadata reader is what the engine uses for capture (time, exposure, camera). It does not
|
||||
* keep the Photo Mechanic pad (headline, event, credit, people, contacts, job id and the rest), so this
|
||||
* reader stays for those fields.
|
||||
*/
|
||||
|
||||
// Mac Roman 0x80–0x9F (the range that betrays it: in Latin-1 these are control characters).
|
||||
|
||||
@@ -6,6 +6,12 @@ import { type FocusHint, focusFromTags } from "./focus.js";
|
||||
* The camera details Photo Mechanic shows beyond the ones with their own column (stored in `photos.exif`), for
|
||||
* its variables: {comp}, {flash}, {meteringmode}, {program}, {white}, {lens35}, {owner}, {artist}... Readable
|
||||
* strings, as Photo Mechanic writes them.
|
||||
*
|
||||
* Capture time and exposure are also read by the develop engine through LightCraft (`photoreport_engine::capture`:
|
||||
* EXIF, then IPTC, then XMP, including CR3). JPEG ingest stays on this reader: it runs in process, event routing
|
||||
* assumes Lisbon when the camera wrote no UTC offset, and these variables include owner, firmware, colour space,
|
||||
* resolution and the focus SubjectArea, which that metadata struct does not carry. Its focus point covers two
|
||||
* Sony bodies only.
|
||||
*/
|
||||
export type CameraExtra = Pick<
|
||||
PmPhoto,
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
"@photoreport/sdk": "workspace:*",
|
||||
"@tauri-apps/api": "^2.12.3",
|
||||
"@tauri-apps/plugin-opener": "^2.7.1",
|
||||
"exifr": "^7.1.3",
|
||||
"onnxruntime-web": "1.29.0",
|
||||
"qrcode": "1.5.4",
|
||||
"react": "^19.3.0",
|
||||
|
||||
@@ -34,6 +34,8 @@ export interface BracketMerge {
|
||||
|
||||
export interface EngineModule {
|
||||
default(init?: { module_or_path: string }): Promise<unknown>;
|
||||
/** Capture metadata JSON from LightCraft. `{}` when the file has none. */
|
||||
readCaptureMeta(bytes: Uint8Array): string;
|
||||
controls(): string;
|
||||
defaultSettings(): string;
|
||||
apply(settings: string, command: string): string;
|
||||
|
||||
@@ -220,8 +220,12 @@ export const t = {
|
||||
fuseFailed: "Não deu para fundir este ângulo.",
|
||||
previewAlt: (n: number) => `Ângulo ${n} fundido`,
|
||||
choose: "Escolher ficheiros",
|
||||
chooseFolder: "Escolher pasta",
|
||||
dropHint: "ou larga uma pasta aqui",
|
||||
reading: "A ler as exposições…",
|
||||
reading: (done: number, total: number) => `A ler ${done} de ${total}…`,
|
||||
noPhotos: "Não há fotografias nesta seleção. Um ficheiro XMP só acompanha o raw.",
|
||||
support: (n: number) => (n === 1 ? "1 ficheiro de apoio (XMP e semelhantes) não é uma fotografia." : `${n} ficheiros de apoio (XMP e semelhantes) não são fotografias.`),
|
||||
asideMore: (n: number) => `e mais ${n}`,
|
||||
stacks: (n: number) => (n === 1 ? "1 ângulo" : `${n} ângulos`),
|
||||
aside: (n: number) => (n === 1 ? "1 fotografia fica de fora" : `${n} fotografias ficam de fora`),
|
||||
asideHelp: "Não entram num bracket de pelo menos três exposições, com a luz e a sombra afastadas.",
|
||||
|
||||
@@ -16,9 +16,13 @@ vi.mock("../realestate/fuse.js", () => ({
|
||||
|
||||
const staged = vi.hoisted(() => ({ frames: new Map<string, BracketFrame>() }));
|
||||
|
||||
vi.mock("../realestate/readFrame.js", () => ({
|
||||
readBracketFile: (file: File) => Promise.resolve(staged.frames.get(file.name) ?? { id: file.name, fileName: file.name }),
|
||||
}));
|
||||
vi.mock("../realestate/readFrame.js", async () => {
|
||||
const actual = await vi.importActual<typeof import("../realestate/readFrame.js")>("../realestate/readFrame.js");
|
||||
return {
|
||||
...actual,
|
||||
readBracketFile: (file: File) => Promise.resolve(staged.frames.get(file.name) ?? { id: file.name, fileName: file.name }),
|
||||
};
|
||||
});
|
||||
|
||||
const org = (realEstateEnabled: boolean): Organization => ({ id: "o1", slug: "fpa", name: "FPA", mode: "AGENCY", realEstateEnabled });
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { fuseBracket } from "../realestate/fuse.js";
|
||||
import { readBracketFile } from "../realestate/readFrame.js";
|
||||
import { fillFromSidecar, pairKey, partitionBracketFiles, readBracketFile } from "../realestate/readFrame.js";
|
||||
import { PageHeader } from "./Shell.js";
|
||||
|
||||
const READ_AT_ONCE = 4;
|
||||
@@ -23,32 +23,58 @@ export function RealEstatePage() {
|
||||
const [frames, setFrames] = useState<BracketFrame[]>([]);
|
||||
const [files, setFiles] = useState<Map<string, File>>(new Map());
|
||||
const [result, setResult] = useState<RealEstateGrouping | null>(null);
|
||||
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
|
||||
const [support, setSupport] = useState(0);
|
||||
|
||||
const take = async (list: File[]) => {
|
||||
const files = list.filter((file) => file.name !== "" && !file.name.startsWith("."));
|
||||
if (files.length === 0 || busyRef.current || !organization) return;
|
||||
const split = partitionBracketFiles(list);
|
||||
if ((split.images.length === 0 && split.sidecars.length === 0 && split.other === 0) || busyRef.current || !organization) return;
|
||||
busyRef.current = true;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
setFrames([]);
|
||||
setFiles(new Map());
|
||||
setSupport(split.sidecars.length + split.other);
|
||||
setProgress({ done: 0, total: split.images.length + split.sidecars.length });
|
||||
try {
|
||||
const read = await mapPool(files, READ_AT_ONCE, (file) => readBracketFile(file));
|
||||
setFrames(read);
|
||||
if (split.images.length === 0) {
|
||||
setError(t.realEstate.noPhotos);
|
||||
return;
|
||||
}
|
||||
let done = 0;
|
||||
const total = split.images.length + split.sidecars.length;
|
||||
const readOne = async (file: File) => {
|
||||
try {
|
||||
return await readBracketFile(file);
|
||||
} finally {
|
||||
done += 1;
|
||||
setProgress({ done, total });
|
||||
}
|
||||
};
|
||||
const read = await mapPool(split.images, READ_AT_ONCE, readOne);
|
||||
const sidecars = await mapPool(split.sidecars, READ_AT_ONCE, readOne);
|
||||
const byKey = new Map(split.sidecars.map((file, index) => [pairKey(file.webkitRelativePath || file.name), sidecars[index]!]));
|
||||
const merged = read.map((frame, index) => {
|
||||
const image = split.images[index];
|
||||
const extra = image ? byKey.get(pairKey(image.webkitRelativePath || image.name)) : undefined;
|
||||
return extra ? fillFromSidecar(frame, extra) : frame;
|
||||
});
|
||||
setFrames(merged);
|
||||
const paired = new Map<string, File>();
|
||||
read.forEach((frame, index) => {
|
||||
const file = files[index];
|
||||
merged.forEach((frame, index) => {
|
||||
const file = split.images[index];
|
||||
if (file) paired.set(frame.id, file);
|
||||
});
|
||||
setFiles(paired);
|
||||
setResult(await api.groupRealEstate(organization.id, read));
|
||||
setResult(await api.groupRealEstate(organization.id, merged));
|
||||
} catch (err) {
|
||||
const code = err instanceof ApiError ? err.code : "";
|
||||
setError(t.realEstate.errors[code] ?? t.unexpectedError);
|
||||
} finally {
|
||||
busyRef.current = false;
|
||||
setBusy(false);
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -70,25 +96,44 @@ export function RealEstatePage() {
|
||||
void filesFromDrop(event.dataTransfer).then((files) => take(files));
|
||||
}}
|
||||
>
|
||||
<label className="inline-flex h-9 cursor-pointer items-center bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong">
|
||||
{t.realEstate.choose}
|
||||
<input
|
||||
aria-label={t.realEstate.choose}
|
||||
className="sr-only"
|
||||
type="file"
|
||||
multiple
|
||||
disabled={busy}
|
||||
onChange={(event) => {
|
||||
const list = event.target.files ? [...event.target.files] : [];
|
||||
event.target.value = "";
|
||||
void take(list);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center justify-center gap-3">
|
||||
<label className="inline-flex h-9 cursor-pointer items-center bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong">
|
||||
{t.realEstate.choose}
|
||||
<input
|
||||
aria-label={t.realEstate.choose}
|
||||
className="sr-only"
|
||||
type="file"
|
||||
multiple
|
||||
disabled={busy}
|
||||
onChange={(event) => {
|
||||
const list = event.target.files ? [...event.target.files] : [];
|
||||
event.target.value = "";
|
||||
void take(list);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="inline-flex h-9 cursor-pointer items-center border border-line bg-panel px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-ink hover:border-faint">
|
||||
{t.realEstate.chooseFolder}
|
||||
<input
|
||||
aria-label={t.realEstate.chooseFolder}
|
||||
className="sr-only"
|
||||
type="file"
|
||||
multiple
|
||||
disabled={busy}
|
||||
{...{ webkitdirectory: "", directory: "" }}
|
||||
onChange={(event) => {
|
||||
const list = event.target.files ? [...event.target.files] : [];
|
||||
event.target.value = "";
|
||||
void take(list);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<p className="mt-3 text-[13px] text-faint">{t.realEstate.dropHint}</p>
|
||||
</div>
|
||||
{busy && <p className="mt-4 text-sm text-muted">{t.realEstate.reading}</p>}
|
||||
{busy && progress && <p className="mt-4 text-sm text-muted">{t.realEstate.reading(progress.done, progress.total)}</p>}
|
||||
{error && <p className="mt-4 text-sm text-danger">{error}</p>}
|
||||
{support > 0 && <p className="mt-4 text-sm text-muted">{t.realEstate.support(support)}</p>}
|
||||
{result && <Grouping frames={frames} files={files} result={result} />}
|
||||
</>
|
||||
)}
|
||||
@@ -121,9 +166,10 @@ function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Ma
|
||||
<p className="text-sm text-ink">{t.realEstate.aside(result.aside.length)}</p>
|
||||
<p className="mt-1 text-[13px] text-faint">{t.realEstate.asideHelp}</p>
|
||||
<ul className="mt-2 text-[13px] text-muted">
|
||||
{result.aside.map((id) => (
|
||||
{result.aside.slice(0, 12).map((id) => (
|
||||
<li key={id}>{line(byId.get(id), id)}</li>
|
||||
))}
|
||||
{result.aside.length > 12 && <li>{t.realEstate.asideMore(result.aside.length - 12)}</li>}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { frameFromTags } from "./readFrame.js";
|
||||
import { bracketFileRole, fileStem, fillFromSidecar, frameFromCapture, pairKey, partitionBracketFiles, readBracketFile } from "./readFrame.js";
|
||||
|
||||
describe("frameFromTags", () => {
|
||||
it("reads a bracket header, including a rational shutter and an EXIF clock", () => {
|
||||
const frame = frameFromTags("id", "IMG_0001.CR3", {
|
||||
Make: "Canon",
|
||||
Model: "EOS R5",
|
||||
BodySerialNumber: "123",
|
||||
FocalLength: 16,
|
||||
FNumber: 8,
|
||||
ISO: [100],
|
||||
ExifImageWidth: 8192,
|
||||
ExifImageHeight: 5464,
|
||||
ExposureCompensation: -2,
|
||||
ExposureTime: { numerator: 1, denominator: 100 },
|
||||
DateTimeOriginal: "2026:10:21 10:00:00",
|
||||
describe("frameFromCapture", () => {
|
||||
it("reads the engine's capture JSON, including a zero compensation", () => {
|
||||
const frame = frameFromCapture("id", "IMG_0001.CR3", {
|
||||
cameraMake: "Canon",
|
||||
cameraModel: "EOS R5",
|
||||
cameraSerial: "123",
|
||||
focalLength: 16,
|
||||
aperture: 8,
|
||||
iso: 100,
|
||||
width: 8192,
|
||||
height: 5464,
|
||||
exposureBias: 0,
|
||||
exposureTime: 0.01,
|
||||
capturedAt: "2026-10-21T10:00:00",
|
||||
});
|
||||
expect(frame).toMatchObject({
|
||||
id: "id",
|
||||
@@ -27,13 +27,45 @@ describe("frameFromTags", () => {
|
||||
iso: 100,
|
||||
width: 8192,
|
||||
height: 5464,
|
||||
exposureBias: -2,
|
||||
exposureBias: 0,
|
||||
exposureTime: 0.01,
|
||||
capturedAt: "2026-10-21T10:00:00.000Z",
|
||||
capturedAt: "2026-10-21T10:00:00",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the name when the file has no header", () => {
|
||||
expect(frameFromTags("id", "IMG_0002.CR3", undefined)).toEqual({ id: "id", fileName: "IMG_0002.CR3" });
|
||||
expect(frameFromCapture("id", "IMG_0002.CR3", undefined)).toEqual({ id: "id", fileName: "IMG_0002.CR3" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("bracket files", () => {
|
||||
it("treats an XMP next to a CR3 as a sidecar, not a photo", () => {
|
||||
expect(bracketFileRole("PSR10071.CR3")).toBe("image");
|
||||
expect(bracketFileRole("PSR10071.XMP")).toBe("sidecar");
|
||||
expect(bracketFileRole("notes.txt")).toBe("other");
|
||||
expect(fileStem("folder/PSR10071.XMP")).toBe("psr10071");
|
||||
expect(pairKey("Imovel/PSR10071.CR3")).toBe(pairKey("Imovel/PSR10071.XMP"));
|
||||
expect(pairKey("Sala/PSR10071.CR3")).not.toBe(pairKey("Quarto/PSR10071.CR3"));
|
||||
const cr3 = new File(["r"], "PSR10071.CR3");
|
||||
const xmp = new File(["x"], "PSR10071.XMP");
|
||||
const note = new File(["n"], "notes.txt");
|
||||
const split = partitionBracketFiles([cr3, xmp, note]);
|
||||
expect(split.images).toEqual([cr3]);
|
||||
expect(split.sidecars).toEqual([xmp]);
|
||||
expect(split.other).toBe(1);
|
||||
});
|
||||
|
||||
it("lets the sidecar fill an exposure the raw did not carry", () => {
|
||||
const raw = frameFromCapture("raw", "PSR10071.CR3", { cameraMake: "Canon", exposureTime: 0.01 });
|
||||
const side = frameFromCapture("side", "PSR10071.XMP", { cameraMake: "Other", exposureBias: -2, exposureTime: 0.5 });
|
||||
expect(fillFromSidecar(raw, side)).toMatchObject({ cameraMake: "Canon", exposureBias: -2, exposureTime: 0.01 });
|
||||
});
|
||||
|
||||
it("uses the reader it is given", async () => {
|
||||
const file = new File(["raw"], "PSR10071.CR3");
|
||||
const frame = await readBracketFile(file, () => JSON.stringify({ exposureBias: -2, exposureTime: 1 / 125 }));
|
||||
expect(frame.fileName).toBe("PSR10071.CR3");
|
||||
expect(frame.exposureBias).toBe(-2);
|
||||
expect(frame.exposureTime).toBeCloseTo(0.008);
|
||||
});
|
||||
});
|
||||
@@ -1,89 +1,154 @@
|
||||
import type { BracketFrame } from "@photoreport/metadata";
|
||||
import exifr from "exifr";
|
||||
import { loadEngine } from "../develop/engine.js";
|
||||
|
||||
/**
|
||||
* Reads only the header. A RAW stays on this computer; the grouping request sends this metadata.
|
||||
* A file exifr cannot read still comes back, with nothing but its name, so the grouper sets it aside.
|
||||
* How a dropped file participates in a bracket. Sidecars are not frames: an XMP next to a raw only
|
||||
* fills exposure the raw itself did not carry. Anything else (notes, previews) is ignored.
|
||||
*/
|
||||
export async function readBracketFile(file: File): Promise<BracketFrame> {
|
||||
const id = `${file.name}\u0000${file.size}\u0000${file.lastModified}`;
|
||||
export type BracketFileRole = "image" | "sidecar" | "other";
|
||||
|
||||
const IMAGE_EXTENSIONS = new Set([
|
||||
"cr2",
|
||||
"cr3",
|
||||
"crw",
|
||||
"nef",
|
||||
"nrw",
|
||||
"arw",
|
||||
"srf",
|
||||
"sr2",
|
||||
"raf",
|
||||
"orf",
|
||||
"rw2",
|
||||
"pef",
|
||||
"srw",
|
||||
"x3f",
|
||||
"3fr",
|
||||
"iiq",
|
||||
"erf",
|
||||
"kdc",
|
||||
"mrw",
|
||||
"dng",
|
||||
"raw",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"tif",
|
||||
"tiff",
|
||||
"png",
|
||||
"webp",
|
||||
"heic",
|
||||
"heif",
|
||||
]);
|
||||
|
||||
export function fileStem(name: string): string {
|
||||
const base = name.split(/[/\\]/).pop() ?? name;
|
||||
const dot = base.lastIndexOf(".");
|
||||
return (dot <= 0 ? base : base.slice(0, dot)).toLowerCase();
|
||||
}
|
||||
|
||||
/** Same folder and stem, so `Imovel/PSR10071.CR3` pairs with `Imovel/PSR10071.XMP`. */
|
||||
export function pairKey(name: string): string {
|
||||
const normalized = name.replaceAll("\\", "/");
|
||||
const slash = normalized.lastIndexOf("/");
|
||||
const dir = slash < 0 ? "" : normalized.slice(0, slash).toLowerCase();
|
||||
return `${dir}/${fileStem(normalized)}`;
|
||||
}
|
||||
|
||||
export function bracketFileRole(name: string): BracketFileRole {
|
||||
const base = name.split(/[/\\]/).pop() ?? name;
|
||||
if (base === "" || base.startsWith(".")) return "other";
|
||||
const dot = base.lastIndexOf(".");
|
||||
const ext = dot <= 0 ? "" : base.slice(dot + 1).toLowerCase();
|
||||
if (ext === "xmp") return "sidecar";
|
||||
if (IMAGE_EXTENSIONS.has(ext)) return "image";
|
||||
return "other";
|
||||
}
|
||||
|
||||
export function partitionBracketFiles(files: readonly File[]): { images: File[]; sidecars: File[]; other: number } {
|
||||
const images: File[] = [];
|
||||
const sidecars: File[] = [];
|
||||
let other = 0;
|
||||
for (const file of files) {
|
||||
const name = file.webkitRelativePath || file.name;
|
||||
const role = bracketFileRole(name);
|
||||
if (role === "image") images.push(file);
|
||||
else if (role === "sidecar") sidecars.push(file);
|
||||
else other += 1;
|
||||
}
|
||||
return { images, sidecars, other };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills only the fields the raw left empty. The camera's own header wins over the sidecar.
|
||||
*/
|
||||
export function fillFromSidecar(frame: BracketFrame, extra: BracketFrame): BracketFrame {
|
||||
const next: BracketFrame = { ...frame };
|
||||
if (next.capturedAt == null && extra.capturedAt != null) next.capturedAt = extra.capturedAt;
|
||||
if (next.cameraSerial == null && extra.cameraSerial != null) next.cameraSerial = extra.cameraSerial;
|
||||
if (next.cameraMake == null && extra.cameraMake != null) next.cameraMake = extra.cameraMake;
|
||||
if (next.cameraModel == null && extra.cameraModel != null) next.cameraModel = extra.cameraModel;
|
||||
if (next.focalLength == null && extra.focalLength != null) next.focalLength = extra.focalLength;
|
||||
if (next.aperture == null && extra.aperture != null) next.aperture = extra.aperture;
|
||||
if (next.iso == null && extra.iso != null) next.iso = extra.iso;
|
||||
if (next.width == null && extra.width != null) next.width = extra.width;
|
||||
if (next.height == null && extra.height != null) next.height = extra.height;
|
||||
if (next.exposureBias == null && extra.exposureBias != null) next.exposureBias = extra.exposureBias;
|
||||
if (next.exposureTime == null && extra.exposureTime != null) next.exposureTime = extra.exposureTime;
|
||||
return next;
|
||||
}
|
||||
|
||||
export function frameFromCapture(id: string, fileName: string, tags: Record<string, unknown> | undefined): BracketFrame {
|
||||
const frame: BracketFrame = { id, fileName };
|
||||
if (!tags) return frame;
|
||||
const captured = text(tags.capturedAt);
|
||||
if (captured && Number.isFinite(Date.parse(captured))) frame.capturedAt = captured;
|
||||
const serial = text(tags.cameraSerial);
|
||||
if (serial) frame.cameraSerial = serial;
|
||||
const make = text(tags.cameraMake);
|
||||
if (make) frame.cameraMake = make;
|
||||
const model = text(tags.cameraModel);
|
||||
if (model) frame.cameraModel = model;
|
||||
const focal = num(tags.focalLength);
|
||||
if (focal !== null && focal > 0) frame.focalLength = focal;
|
||||
const aperture = num(tags.aperture);
|
||||
if (aperture !== null && aperture > 0) frame.aperture = aperture;
|
||||
const iso = num(tags.iso);
|
||||
if (iso !== null && iso > 0) frame.iso = Math.round(iso);
|
||||
const width = num(tags.width);
|
||||
if (width !== null && width > 0) frame.width = Math.round(width);
|
||||
const height = num(tags.height);
|
||||
if (height !== null && height > 0) frame.height = Math.round(height);
|
||||
const bias = num(tags.exposureBias);
|
||||
if (bias !== null) frame.exposureBias = bias;
|
||||
const time = num(tags.exposureTime);
|
||||
if (time !== null && time > 0) frame.exposureTime = time;
|
||||
return frame;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads capture metadata with the develop engine (LightCraft). The bytes stay in this browser.
|
||||
* A file the engine cannot read still comes back, with nothing but its name, so the grouper sets it aside.
|
||||
* `readMeta` is the engine's `readCaptureMeta`; tests pass their own.
|
||||
*/
|
||||
export async function readBracketFile(file: File, readMeta?: (bytes: Uint8Array) => string | Promise<string>): Promise<BracketFrame> {
|
||||
const name = file.webkitRelativePath || file.name;
|
||||
const id = `${name}\u0000${file.size}\u0000${file.lastModified}`;
|
||||
try {
|
||||
const tags = (await exifr.parse(file, {
|
||||
tiff: true,
|
||||
exif: true,
|
||||
gps: false,
|
||||
iptc: false,
|
||||
xmp: false,
|
||||
icc: false,
|
||||
reviveValues: true,
|
||||
translateValues: false,
|
||||
})) as Record<string, unknown> | undefined;
|
||||
return frameFromTags(id, file.name, tags);
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const json = readMeta ? await readMeta(bytes) : (await loadEngine()).readCaptureMeta(bytes);
|
||||
const tags = JSON.parse(json) as Record<string, unknown>;
|
||||
return frameFromCapture(id, file.name, tags);
|
||||
} catch {
|
||||
return { id, fileName: file.name };
|
||||
}
|
||||
}
|
||||
|
||||
export function frameFromTags(id: string, fileName: string, tags: Record<string, unknown> | undefined): BracketFrame {
|
||||
const frame: BracketFrame = { id, fileName };
|
||||
if (!tags) return frame;
|
||||
const captured = capturedAt(tags.DateTimeOriginal ?? tags.CreateDate);
|
||||
if (captured) frame.capturedAt = captured;
|
||||
const serial = text(tags.BodySerialNumber) ?? text(tags.InternalSerialNumber) ?? text(tags.SerialNumber);
|
||||
if (serial) frame.cameraSerial = serial;
|
||||
const make = text(tags.Make);
|
||||
if (make) frame.cameraMake = make;
|
||||
const model = text(tags.Model);
|
||||
if (model) frame.cameraModel = model;
|
||||
const focal = num(tags.FocalLength);
|
||||
if (focal !== null && focal > 0) frame.focalLength = focal;
|
||||
const aperture = num(tags.FNumber);
|
||||
if (aperture !== null && aperture > 0) frame.aperture = aperture;
|
||||
const iso = num(tags.ISO) ?? num(tags.ISOSpeedRatings);
|
||||
if (iso !== null && iso > 0) frame.iso = Math.round(iso);
|
||||
const width = num(tags.ExifImageWidth) ?? num(tags.ImageWidth);
|
||||
if (width !== null && width > 0) frame.width = Math.round(width);
|
||||
const height = num(tags.ExifImageHeight) ?? num(tags.ImageHeight);
|
||||
if (height !== null && height > 0) frame.height = Math.round(height);
|
||||
const bias = num(tags.ExposureCompensation) ?? num(tags.ExposureBiasValue);
|
||||
if (bias !== null) frame.exposureBias = bias;
|
||||
const time = num(tags.ExposureTime);
|
||||
if (time !== null && time > 0) frame.exposureTime = time;
|
||||
return frame;
|
||||
}
|
||||
|
||||
/** EXIF wall time, stored so the gap between frames is the gap the camera recorded. */
|
||||
function capturedAt(value: unknown): string | null {
|
||||
if (value instanceof Date && !Number.isNaN(value.getTime())) return value.toISOString();
|
||||
if (typeof value !== "string") return null;
|
||||
const wall = /^(\d{4}):(\d{2}):(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/.exec(value.trim());
|
||||
if (wall) {
|
||||
const parsed = Date.parse(`${wall[1]}-${wall[2]}-${wall[3]}T${wall[4]}:${wall[5]}:${wall[6]}Z`);
|
||||
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
|
||||
}
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
|
||||
}
|
||||
|
||||
function num(value: unknown): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) return value;
|
||||
if (Array.isArray(value)) return num(value[0]);
|
||||
if (value && typeof value === "object" && "numerator" in value && "denominator" in value) {
|
||||
const ratio = value as { numerator: unknown; denominator: unknown };
|
||||
if (typeof ratio.numerator === "number" && typeof ratio.denominator === "number" && ratio.denominator !== 0) {
|
||||
const result = ratio.numerator / ratio.denominator;
|
||||
return Number.isFinite(result) ? result : null;
|
||||
}
|
||||
}
|
||||
if (typeof value === "string" && value.trim() !== "") {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function text(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim().replace(/\0+$/, "");
|
||||
const trimmed = value.trim();
|
||||
return trimmed === "" ? null : trimmed;
|
||||
}
|
||||
@@ -31,6 +31,8 @@ sha2 = "0.10"
|
||||
libc = "0.2"
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg"] }
|
||||
photoreport-faces = { path = "../../../workers/faces" }
|
||||
# Capture time (EXIF / IPTC / XMP, including CR3) comes from the engine's LightCraft reader.
|
||||
photoreport-engine = { path = "../../../engine/core" }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
# New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates.
|
||||
|
||||
@@ -164,14 +164,29 @@ fn sibling_jpeg(path: &Path) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The capture day of a photo: EXIF DateTimeOriginal when it can be read (a JPEG, or a RAW's paired JPEG), else
|
||||
/// the file's modification time — on a card straight from the camera that is when the frame was shot. RAW-only
|
||||
/// formats with no EXIF reader yet (e.g. CR3) fall back to the modification time.
|
||||
/// Year, month, day from the engine's capture clock (`YYYY-MM-DD...`), when the file recorded one.
|
||||
fn ymd_from_capture(bytes: &[u8]) -> Option<(i32, u32, u32)> {
|
||||
let value = photoreport_engine::capture::read_capture(bytes);
|
||||
let text = value.get("capturedAt")?.as_str()?;
|
||||
let year: i32 = text.get(0..4)?.parse().ok()?;
|
||||
let month: u32 = text.get(5..7)?.parse().ok()?;
|
||||
let day: u32 = text.get(8..10)?.parse().ok()?;
|
||||
if (1..=12).contains(&month) && (1..=31).contains(&day) && year > 1900 {
|
||||
Some((year, month, day))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The capture day of a photo. LightCraft reads EXIF, then IPTC, then XMP, including a CR3 with no JPEG
|
||||
/// beside it. A JPEG whose header the engine cannot read still tries the short EXIF scan. Otherwise the
|
||||
/// file's modification time — on a card straight from the camera that is when the frame was shot.
|
||||
fn capture_day(path: &Path, ext: &str) -> chrono::DateTime<Local> {
|
||||
let from_engine = || std::fs::read(path).ok().and_then(|bytes| ymd_from_capture(&bytes));
|
||||
let ymd = if is_jpeg(ext) {
|
||||
crate::preview::exif_date(&read_head(path))
|
||||
} else if is_raw(ext) {
|
||||
sibling_jpeg(path).and_then(|j| crate::preview::exif_date(&read_head(&j)))
|
||||
from_engine().or_else(|| crate::preview::exif_date(&read_head(path)))
|
||||
} else if is_image(ext) {
|
||||
from_engine().or_else(|| sibling_jpeg(path).and_then(|j| crate::preview::exif_date(&read_head(&j))))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Capture metadata for one photo, read by LightCraft (`lightcraft-meta`).
|
||||
//!
|
||||
//! EXIF first, then IPTC fills whatever is still empty, then XMP overrides the user fields and fills the
|
||||
//! rest. That covers JPEG, PNG, WebP, TIFF, DNG and the raws LightCraft opens, including Canon CR3.
|
||||
//! A loose XMP sidecar (the XML file next to a raw) is read the same way.
|
||||
|
||||
use lightcraft_meta::Metadata;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Capture {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
camera_make: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
camera_model: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
camera_serial: Option<String>,
|
||||
/// ISO 8601. The offset is included when the file recorded one.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
captured_at: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
focal_length: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
aperture: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
iso: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
width: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
height: Option<u32>,
|
||||
/// EV. Zero is a real compensation and is kept.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
exposure_bias: Option<f64>,
|
||||
/// Seconds.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
exposure_time: Option<f64>,
|
||||
}
|
||||
|
||||
fn positive(value: Option<f64>) -> Option<f64> {
|
||||
value.filter(|n| n.is_finite() && *n > 0.0)
|
||||
}
|
||||
|
||||
fn finite(value: Option<f64>) -> Option<f64> {
|
||||
value.filter(|n| n.is_finite())
|
||||
}
|
||||
|
||||
fn text(value: Option<String>) -> Option<String> {
|
||||
value
|
||||
.map(|s| s.trim().trim_end_matches('\0').to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
fn from_meta(meta: &Metadata) -> Capture {
|
||||
Capture {
|
||||
camera_make: text(meta.make.clone()),
|
||||
camera_model: text(meta.model.clone()),
|
||||
camera_serial: text(meta.serial_number.clone()),
|
||||
captured_at: meta
|
||||
.capture_time
|
||||
.filter(|t| t.year > 1900)
|
||||
.map(|t| t.to_iso()),
|
||||
focal_length: positive(meta.focal_length),
|
||||
aperture: positive(meta.f_number),
|
||||
iso: meta.iso.filter(|n| *n > 0),
|
||||
width: meta.width.filter(|n| *n > 0),
|
||||
height: meta.height.filter(|n| *n > 0),
|
||||
exposure_bias: finite(meta.exposure_bias),
|
||||
exposure_time: positive(meta.exposure_time),
|
||||
}
|
||||
}
|
||||
|
||||
fn present(capture: &Capture) -> bool {
|
||||
capture.camera_make.is_some()
|
||||
|| capture.camera_model.is_some()
|
||||
|| capture.camera_serial.is_some()
|
||||
|| capture.captured_at.is_some()
|
||||
|| capture.focal_length.is_some()
|
||||
|| capture.aperture.is_some()
|
||||
|| capture.iso.is_some()
|
||||
|| capture.width.is_some()
|
||||
|| capture.height.is_some()
|
||||
|| capture.exposure_bias.is_some()
|
||||
|| capture.exposure_time.is_some()
|
||||
}
|
||||
|
||||
fn value_of(capture: &Capture) -> Value {
|
||||
serde_json::to_value(capture).unwrap_or_else(|_| json!({}))
|
||||
}
|
||||
|
||||
/// Capture fields as a JSON object. A file with none of them yields `{}`.
|
||||
pub fn read_capture(bytes: &[u8]) -> Value {
|
||||
let from_file = from_meta(&lightcraft_meta::extract(bytes));
|
||||
if present(&from_file) {
|
||||
return value_of(&from_file);
|
||||
}
|
||||
// A sidecar is not a container. `extract` finds nothing; the packet itself is the metadata.
|
||||
if let Ok(text) = std::str::from_utf8(bytes) {
|
||||
let trimmed = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if trimmed.starts_with('<')
|
||||
&& let Ok(xmp) = lightcraft_meta::parse_xmp(trimmed)
|
||||
{
|
||||
let from_xmp = from_meta(&xmp.metadata);
|
||||
if present(&from_xmp) {
|
||||
return value_of(&from_xmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
value_of(&from_file)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_meta::{DateTime, Metadata, write_exif, write_xmp};
|
||||
|
||||
fn sample() -> Metadata {
|
||||
Metadata {
|
||||
make: Some("Canon".into()),
|
||||
model: Some("EOS R5".into()),
|
||||
serial_number: Some("123".into()),
|
||||
capture_time: DateTime::parse_iso("2026-10-21T10:00:00"),
|
||||
focal_length: Some(16.0),
|
||||
f_number: Some(8.0),
|
||||
iso: Some(100),
|
||||
exposure_bias: Some(-2.0),
|
||||
exposure_time: Some(0.01),
|
||||
..Metadata::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exif_block_round_trips_the_bracket_fields() {
|
||||
let meta = sample();
|
||||
let json = read_capture(&write_exif(&meta));
|
||||
assert_eq!(json["cameraMake"], "Canon");
|
||||
assert_eq!(json["cameraModel"], "EOS R5");
|
||||
assert_eq!(json["capturedAt"], meta.capture_time.unwrap().to_iso());
|
||||
assert_eq!(json["focalLength"], 16.0);
|
||||
assert_eq!(json["aperture"], 8.0);
|
||||
assert_eq!(json["iso"], 100);
|
||||
assert_eq!(json["exposureBias"], -2.0);
|
||||
let shutter = json["exposureTime"].as_f64().unwrap();
|
||||
assert!((shutter - 0.01).abs() < 1e-6, "{shutter}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xmp_sidecar_round_trips_the_bracket_fields() {
|
||||
let meta = sample();
|
||||
let json = read_capture(write_xmp(&meta, None).as_bytes());
|
||||
assert_eq!(json["cameraMake"], "Canon");
|
||||
assert_eq!(json["exposureBias"], -2.0);
|
||||
assert_eq!(json["capturedAt"], meta.capture_time.unwrap().to_iso());
|
||||
let shutter = json["exposureTime"].as_f64().unwrap();
|
||||
assert!((shutter - 0.01).abs() < 1e-6, "{shutter}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_bytes_are_empty() {
|
||||
assert_eq!(read_capture(b"not a photo"), json!({}));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
//! small JSON edit commands addressed by LightCraft control ids (`light.exposure`, `effects.clarity`, ...).
|
||||
//! Updating LightCraft should only ever require changes in this crate.
|
||||
|
||||
pub mod capture;
|
||||
pub mod level;
|
||||
pub mod merge;
|
||||
pub mod render;
|
||||
|
||||
@@ -18,6 +18,13 @@ fn settings_from(json: &str) -> Result<DevelopSettings, JsError> {
|
||||
DevelopSettings::from_json(&v).map_err(js_err)
|
||||
}
|
||||
|
||||
/// Capture metadata (camera, clock, exposure) as JSON. LightCraft reads EXIF, then IPTC, then XMP,
|
||||
/// including Canon CR3 and a loose XMP sidecar. A file with none of those fields yields `{}`.
|
||||
#[wasm_bindgen(js_name = readCaptureMeta)]
|
||||
pub fn read_capture_meta(bytes: &[u8]) -> String {
|
||||
photoreport_engine::capture::read_capture(bytes).to_string()
|
||||
}
|
||||
|
||||
/// Every develop control of the pinned LightCraft version (id, module, label, range, default, step).
|
||||
#[wasm_bindgen]
|
||||
pub fn controls() -> Result<String, JsError> {
|
||||
|
||||
Generated
-3
@@ -156,9 +156,6 @@ importers:
|
||||
'@tauri-apps/plugin-opener':
|
||||
specifier: ^2.7.1
|
||||
version: 2.7.1
|
||||
exifr:
|
||||
specifier: ^7.1.3
|
||||
version: 7.1.3
|
||||
onnxruntime-web:
|
||||
specifier: 1.29.0
|
||||
version: 1.29.0
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
//! Settings from an op log:
|
||||
//! in: {"id": "...", "base": {..settings..} | null, "commands": [{"command": "develop.set", "params": {..}}, ..]}
|
||||
//! out: {"id": "...", "settings": {..}, "skipped": [indexes of commands that were refused], "unedited": bool}
|
||||
//! Capture metadata (LightCraft: EXIF, then IPTC, then XMP, including CR3 and a loose XMP sidecar):
|
||||
//! in: {"id": "...", "meta": {"input": "/abs/photo.cr3"}}
|
||||
//! out: {"id": "...", "capture": { "cameraMake": "..", "exposureTime": 0.01, "exposureBias": -2, .. }}
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
@@ -149,6 +152,23 @@ fn run(job: &Job) -> Result<(u32, u32), String> {
|
||||
Ok((px.width, px.height))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MetaRequest {
|
||||
id: String,
|
||||
meta: MetaJob,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MetaJob {
|
||||
input: String,
|
||||
}
|
||||
|
||||
/// Capture metadata of one file. The same JSON the browser engine returns.
|
||||
fn capture_file(path: &str) -> Result<serde_json::Value, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
Ok(photoreport_engine::capture::read_capture(&bytes))
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let stdout = std::io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
@@ -171,6 +191,20 @@ fn main() {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if value.get("meta").is_some() {
|
||||
let reply = match serde_json::from_value::<MetaRequest>(value) {
|
||||
Ok(req) => match capture_file(&req.meta.input) {
|
||||
Ok(capture) => serde_json::json!({ "id": req.id, "capture": capture }),
|
||||
Err(error) => serde_json::json!({ "id": req.id, "error": error }),
|
||||
},
|
||||
Err(e) => {
|
||||
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
|
||||
}
|
||||
};
|
||||
let _ = writeln!(out, "{reply}");
|
||||
let _ = out.flush();
|
||||
continue;
|
||||
}
|
||||
if value.get("auto").is_some() {
|
||||
let reply = match serde_json::from_value::<AutoRequest>(value) {
|
||||
Ok(req) => match auto(&req.auto) {
|
||||
@@ -219,7 +253,13 @@ fn main() {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{DevelopSettings, decode_edge};
|
||||
use super::{DevelopSettings, capture_file, decode_edge};
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_is_an_error() {
|
||||
let err = capture_file("/no/such/photo.cr3").unwrap_err();
|
||||
assert!(err.contains("photo.cr3"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tight_crop_decodes_enough_for_the_output() {
|
||||
|
||||
Reference in new issue
Block a user