Write folder merges through LightCraft Photo Merge so the DNG keeps colour tags.
ci / rust (pull_request) Successful in 5m3s
ci / typescript (pull_request) Successful in 10m50s

A camera raw with no matrix of its own was saved as a linear DNG that other raw tools refused.
This commit is contained in:
spark committed 2026-10-24 00:50:39 +01:00
1 parent e096c6153e
commit cb67b0c329
25 files changed
+2605 -41

No files matched your search

Generated
+1702 -5
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -20,6 +20,10 @@ lightcraft-merge = { git = "https://github.com/storytold/lightcraft", rev = "5fe
lightcraft-raw = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } lightcraft-raw = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-color = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } lightcraft-color = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-meta = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" } lightcraft-meta = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
# Photo Merge only. The develop crates do not export the colour-tag step a raw without matrices
# needs before write_linear_dng. Desktop turns this on; the browser engine does not.
lightcraft-engine = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
lightcraft-catalog = { git = "https://github.com/storytold/lightcraft", rev = "5fe74557eca64638b1f9015c9769f7e52a889fa2" }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
thiserror = "2" thiserror = "2"
+5
View File
@@ -56,6 +56,8 @@ export const t = {
opening: "A abrir a pasta…", opening: "A abrir a pasta…",
close: "Fechar", close: "Fechar",
hint: "Folha de contacto desta pasta, neste computador. Não cria um evento nem envia fotografias. Estrelas e marcas ficam só nesta sessão.", hint: "Folha de contacto desta pasta, neste computador. Não cria um evento nem envia fotografias. Estrelas e marcas ficam só nesta sessão.",
mergeTitle: "Funde as exposições desta pasta num DNG ao lado delas. As originais ficam. Não envia fotografias.",
merged: (n: number) => (n === 1 ? "1 DNG ficou nesta pasta." : `${n} DNG ficaram nesta pasta.`),
empty: "Esta pasta não tem fotografias.", empty: "Esta pasta não tem fotografias.",
failed: "Não foi possível abrir esta pasta.", failed: "Não foi possível abrir esta pasta.",
count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`), count: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`),
@@ -297,6 +299,9 @@ export const t = {
missing: "Falta o ficheiro original de alguma exposição.", missing: "Falta o ficheiro original de alguma exposição.",
engine: "O motor ainda não grava o DNG. Quando a cópia do cartão acabar, atualiza a página.", engine: "O motor ainda não grava o DNG. Quando a cópia do cartão acabar, atualiza a página.",
failed: "Não fundi. Tenta outra vez.", failed: "Não fundi. Tenta outra vez.",
raw: "Não consegui ler estes RAW para os fundir.",
write: "Não consegui gravar o DNG nesta pasta.",
failedDetail: (reason: string) => `Não fundi. ${reason}`,
}, },
}, },
card: { card: {
+58 -1
View File
@@ -4,6 +4,8 @@ import { t } from "../i18n.js";
import { LABEL_COLOR } from "./Grid.js"; import { LABEL_COLOR } from "./Grid.js";
import { FOLDER_CELL_H, FOLDER_CELL_W, FOLDER_GAP, folderCols, folderWindow } from "./folder-layout.js"; import { FOLDER_CELL_H, FOLDER_CELL_W, FOLDER_GAP, folderCols, folderWindow } from "./folder-layout.js";
import type { FolderListing } from "./folderDrop.js"; import type { FolderListing } from "./folderDrop.js";
import { mergeFailureText } from "./folderMerge.js";
import { MergeError } from "./mergeExposures.js";
import { isMac, patchForKey, pmPatchForKey } from "./store.js"; import { isMac, patchForKey, pmPatchForKey } from "./store.js";
interface Mark { interface Mark {
@@ -66,8 +68,17 @@ export function FolderSheet(props: {
folder: FolderListing; folder: FolderListing;
onClose: () => void; onClose: () => void;
thumb: (path: string, edge: number) => Promise<ArrayBuffer | null>; thumb: (path: string, edge: number) => Promise<ArrayBuffer | null>;
/**
* Merges the photos on this sheet and returns how many DNG files were written beside them.
* Absent in a view that cannot edit. The library's own merge stays on the event underneath.
*/
merge?: (input: {
files: FolderListing["files"];
selectedIds: readonly string[];
onStatus: (stack: number, total: number) => void;
}) => Promise<number>;
}) { }) {
const { folder, onClose, thumb } = props; const { folder, onClose, thumb, merge } = props;
const files = folder.files; const files = folder.files;
const scroller = useRef<HTMLDivElement>(null); const scroller = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(800); const [width, setWidth] = useState(800);
@@ -78,6 +89,34 @@ export function FolderSheet(props: {
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files[0] ? [files[0].path] : [])); const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files[0] ? [files[0].path] : []));
const [marks, setMarks] = useState<ReadonlyMap<string, Mark>>(() => new Map()); const [marks, setMarks] = useState<ReadonlyMap<string, Mark>>(() => new Map());
const [loupe, setLoupe] = useState(false); const [loupe, setLoupe] = useState(false);
const [mergeStatus, setMergeStatus] = useState<string | null>(null);
const [mergeFailed, setMergeFailed] = useState(false);
const [merging, setMerging] = useState(false);
const mergePending = useRef(false);
const runMerge = () => {
if (!merge || mergePending.current) return;
mergePending.current = true;
setMerging(true);
setMergeFailed(false);
setMergeStatus(t.merge.reading);
void merge({
files,
selectedIds: [...selected],
onStatus: (stack, total) => setMergeStatus(t.merge.working(stack, total)),
}).then(
(made) => setMergeStatus(t.folderSheet.merged(made)),
(err: unknown) => {
const code = err instanceof MergeError ? err.code : "failed";
const detail = err instanceof MergeError ? err.detail : undefined;
setMergeStatus(mergeFailureText(code, detail));
setMergeFailed(true);
},
).finally(() => {
mergePending.current = false;
setMerging(false);
});
};
useEffect(() => { useEffect(() => {
const el = scroller.current; const el = scroller.current;
@@ -221,6 +260,24 @@ export function FolderSheet(props: {
</span> </span>
<span className="font-mono text-[11px] text-faint">{t.folderSheet.count(files.length)}</span> <span className="font-mono text-[11px] text-faint">{t.folderSheet.count(files.length)}</span>
<span className="hidden text-[11px] text-faint sm:inline">{t.folderSheet.hint}</span> <span className="hidden text-[11px] text-faint sm:inline">{t.folderSheet.hint}</span>
{merge && files.length > 0 && (
<span className="inline-flex items-center gap-2">
<button
type="button"
title={t.folderSheet.mergeTitle}
disabled={merging}
onClick={runMerge}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{t.merge.button}
</button>
{mergeStatus && (
<span role="status" title={mergeStatus} className={`max-w-xl text-[12px] ${mergeFailed ? "text-danger" : "text-muted"}`}>
{mergeStatus}
</span>
)}
</span>
)}
<button type="button" onClick={onClose} className="ml-auto h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"> <button type="button" onClick={onClose} className="ml-auto h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.folderSheet.close} {t.folderSheet.close}
</button> </button>
+13
View File
@@ -116,6 +116,19 @@ export async function openFolder(path: string, invoke: Invoke = desktopInvoke):
} }
} }
/** Capture metadata of one photo on the open sheet, read in the desktop process. */
export function folderMeta(path: string, invoke: Invoke = desktopInvoke): Promise<string> {
return invoke<string>("folder_meta", { path });
}
/**
* Merges these photos in the desktop process and writes the DNG beside the middle one.
* The raws never cross into the page: a folder of CR3 does not fit in the browser engine.
*/
export function mergeFolderDng(paths: readonly string[], maxEdge: number, invoke: Invoke = desktopInvoke): Promise<string> {
return invoke<string>("folder_merge_dng", { paths, maxEdge });
}
export async function folderThumb(path: string, edge: number, invoke?: Invoke): Promise<ArrayBuffer | null> { export async function folderThumb(path: string, edge: number, invoke?: Invoke): Promise<ArrayBuffer | null> {
if (!invoke && !isDesktop()) return null; if (!invoke && !isDesktop()) return null;
try { try {
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from "vitest";
import { mergeFailureText, mergeFolderExposures, mergeFolderNative } from "./folderMerge.js";
import { MergeError } from "./mergeExposures.js";
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
function tags(bias: number, ms: number, exposureTime = 1 / 125): string {
return JSON.stringify({
capturedAt: at(ms),
cameraModel: "EOS R5",
focalLength: 16,
aperture: 8,
iso: 100,
width: 4000,
height: 3000,
exposureBias: bias,
exposureTime,
});
}
function files() {
return [
{ path: "/job/sala/dark.cr3", name: "dark.cr3" },
{ path: "/job/sala/mid.cr3", name: "mid.cr3" },
{ path: "/job/sala/bright.cr3", name: "bright.cr3" },
{ path: "/job/sala/mid-fundido.dng", name: "mid-fundido.dng" },
];
}
const meta = new Map([
["/job/sala/dark.cr3", tags(-2, 0)],
["/job/sala/mid.cr3", tags(0, 200)],
["/job/sala/bright.cr3", tags(2, 400)],
]);
describe("merge a contact sheet", () => {
it("writes one DNG beside the bracket when only the focused photo is selected", async () => {
const saved: { dir: string; name: string; bytes: Uint8Array }[] = [];
const made = await mergeFolderExposures({
files: files(),
selectedIds: ["/job/sala/dark.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: (bytes) => meta.get(new TextDecoder().decode(bytes)) ?? "{}",
mergeDng: () => new Uint8Array([1, 2, 3]),
saveDng: async (dir, name, bytes) => {
saved.push({ dir, name, bytes });
},
});
expect(made).toBe(1);
expect(saved).toEqual([{ dir: "/job/sala", name: "mid-fundido.dng", bytes: new Uint8Array([1, 2, 3]) }]);
});
it("merges the photos the user selected even when they are not a detected bracket", async () => {
const saved: string[] = [];
const made = await mergeFolderExposures({
files: files(),
selectedIds: ["/job/sala/dark.cr3", "/job/sala/mid.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: () => tags(0, 0, 1 / 125),
mergeDng: (frames) => new Uint8Array([frames.length]),
saveDng: async (_dir, name) => {
saved.push(name);
},
});
expect(made).toBe(1);
expect(saved).toEqual(["dark-fundido.dng"]);
});
it("says there is no set when a single photo is not part of a bracket", async () => {
const run = mergeFolderExposures({
files: [{ path: "/job/a.cr3", name: "a.cr3" }, { path: "/job/b.cr3", name: "b.cr3" }],
selectedIds: ["/job/a.cr3"],
readFile: async (path) => new TextEncoder().encode(path),
readMeta: () => tags(0, 0),
mergeDng: () => new Uint8Array([1]),
saveDng: async () => {},
});
await expect(run).rejects.toBeInstanceOf(MergeError);
await expect(run).rejects.toMatchObject({ code: "none" });
});
});
describe("merge a contact sheet on this computer", () => {
const pair = [
{ path: "/job/dark.cr3", name: "dark.cr3" },
{ path: "/job/mid.cr3", name: "mid.cr3" },
];
it("asks the desktop to merge the stack and keeps its reason when that fails", async () => {
const stacks: string[][] = [];
const run = mergeFolderNative({
files: pair,
selectedIds: pair.map((file) => file.path),
metaOf: async () => tags(0, 0),
mergePaths: async (paths) => {
stacks.push([...paths]);
throw new Error("cannot read the photo: cr3");
},
});
await expect(run).rejects.toMatchObject({ code: "failed", detail: "cannot read the photo: cr3" });
expect(stacks).toEqual([["/job/dark.cr3", "/job/mid.cr3"]]);
expect(mergeFailureText("failed", "cannot read the photo: cr3")).toBe("Não consegui ler estes RAW para os fundir.");
});
});
+206
View File
@@ -0,0 +1,206 @@
import { loadEngine, type EngineModule } from "../develop/engine.js";
import { t } from "../i18n.js";
import { frameFromCapture } from "../realestate/readFrame.js";
import { MergeError } from "./mergeExposures.js";
import { MERGE_EDGE, isMergedName, stacksOfFrames } from "./mergeStacks.js";
export interface FolderExposure {
path: string;
name: string;
}
function parentDir(path: string): string {
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
if (slash <= 0) throw new MergeError("failed");
return path.slice(0, slash);
}
function stemOf(name: string): string {
const dot = name.lastIndexOf(".");
return dot > 0 ? name.slice(0, dot) : name;
}
/**
* Merges the contact sheet on this computer. A selection of two or more is that set; otherwise every
* bracket in the folder. The DNG is written beside the middle frame. Nothing is uploaded.
* Metadata is read first and the bytes dropped, then each stack is read again to merge: a folder of
* raws must not all sit in memory at once.
*/
export async function mergeFolderExposures(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
readFile: (path: string) => Promise<Uint8Array>;
readMeta: (bytes: Uint8Array) => string | Promise<string>;
mergeDng: (files: Uint8Array[]) => Uint8Array;
saveDng: (dir: string, name: string, bytes: Uint8Array) => Promise<void>;
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
const candidates = opts.files.filter((file) => !isMergedName(file.name));
const selected = new Set(opts.selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? candidates.filter((file) => selected.has(file.path)) : candidates;
if (pool.length < 2) throw new MergeError("none");
const frames = [];
for (const file of pool) {
const bytes = await readOrMissing(opts.readFile, file.path);
frames.push(await frameOfFile(file, bytes, opts.readMeta));
}
const stacks = stacksOfFrames(frames, opts.selectedIds);
if (stacks.length === 0) throw new MergeError("none");
const byPath = new Map(pool.map((file) => [file.path, file]));
let made = 0;
for (let index = 0; index < stacks.length; index++) {
opts.onStatus?.(index + 1, stacks.length);
const members = (stacks[index] ?? []).map((id) => byPath.get(id)).filter((file): file is FolderExposure => !!file);
if (members.length < 2) throw new MergeError("none");
const files: Uint8Array[] = [];
for (const member of members) files.push(await readOrMissing(opts.readFile, member.path));
const dng = mergedOrFailed(opts.mergeDng, files);
const mid = members[Math.floor((members.length - 1) / 2)]!;
try {
await opts.saveDng(parentDir(mid.path), `${stemOf(mid.name)}-fundido.dng`, dng);
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
}
made += 1;
}
return made;
}
async function readOrMissing(readFile: (path: string) => Promise<Uint8Array>, path: string): Promise<Uint8Array> {
try {
const bytes = await readFile(path);
if (bytes.byteLength === 0) throw new MergeError("missing");
return bytes;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("missing");
}
}
async function frameOfFile(
file: FolderExposure,
bytes: Uint8Array,
readMeta: (bytes: Uint8Array) => string | Promise<string>,
) {
try {
const tags = JSON.parse(await readMeta(bytes)) as Record<string, unknown>;
return frameFromCapture(file.path, file.name, tags);
} catch {
return { id: file.path, fileName: file.name };
}
}
function mergedOrFailed(mergeDng: (files: Uint8Array[]) => Uint8Array, files: Uint8Array[]): Uint8Array {
try {
const dng = mergeDng(files);
if (dng.byteLength === 0) throw new MergeError("failed");
return dng;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
}
}
/**
* Merges the contact sheet in the desktop process. Metadata and the DNG stay there: sending every
* raw into the browser engine is what made a folder of CR3 fail with no reason.
*/
export async function mergeFolderNative(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
metaOf: (path: string) => Promise<string>;
mergePaths: (paths: readonly string[]) => Promise<void>;
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
const candidates = opts.files.filter((file) => !isMergedName(file.name));
const selected = new Set(opts.selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? candidates.filter((file) => selected.has(file.path)) : candidates;
if (pool.length < 2) throw new MergeError("none");
const frames = [];
for (const file of pool) {
try {
const tags = JSON.parse(await opts.metaOf(file.path)) as Record<string, unknown>;
frames.push(frameFromCapture(file.path, file.name, tags));
} catch (err) {
if (err instanceof MergeError) throw err;
frames.push({ id: file.path, fileName: file.name });
}
}
const stacks = stacksOfFrames(frames, opts.selectedIds);
if (stacks.length === 0) throw new MergeError("none");
let made = 0;
for (let index = 0; index < stacks.length; index++) {
opts.onStatus?.(index + 1, stacks.length);
const ids = stacks[index] ?? [];
if (ids.length < 2) throw new MergeError("none");
try {
await opts.mergePaths(ids);
} catch (err) {
if (err instanceof MergeError) throw err;
const detail = err instanceof Error ? err.message : String(err);
throw new MergeError("failed", detail);
}
made += 1;
}
return made;
}
/** The sentence under the button. An unknown failure keeps the desktop's reason, so the next try is not a guess. */
export function mergeFailureText(code: MergeError["code"], detail?: string): string {
if (code !== "failed" || !detail) return t.merge.errors[code];
const lower = detail.toLowerCase();
if (lower.includes("permission") || lower.includes("read-only") || lower.includes("operation not permitted")) {
return t.merge.errors.write;
}
if (lower.includes("cannot read the photo") || lower.includes("cannot be reduced")) {
return t.merge.errors.raw;
}
return t.merge.errors.failedDetail(detail);
}
/** The desktop merge: capture metadata and the linear DNG come from the develop engine. */
export async function mergeFolderOnDisk(opts: {
files: readonly FolderExposure[];
selectedIds: readonly string[];
readFile: (path: string) => Promise<Uint8Array>;
saveDng: (dir: string, name: string, bytes: Uint8Array) => Promise<void>;
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
let engine: EngineModule;
try {
engine = await loadEngine();
} catch {
throw new MergeError("engine");
}
return mergeFolderExposures({
...opts,
readMeta: (bytes) => engine.readCaptureMeta(bytes),
mergeDng: (files) => dngOf(engine, files),
});
}
function dngOf(engine: EngineModule, files: Uint8Array[]): Uint8Array {
const job = new engine.BracketJob();
try {
for (const file of files) job.push(file);
if (!job.mergeDng) throw new MergeError("engine");
const dng = job.mergeDng(MERGE_EDGE);
const copy = new Uint8Array(dng.byteLength);
copy.set(dng);
return copy;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
} finally {
job.free();
}
}
+33
View File
@@ -37,6 +37,39 @@ describe("contact sheet", () => {
expect(onClose).toHaveBeenCalledOnce(); expect(onClose).toHaveBeenCalledOnce();
}); });
it("merges the photos on the sheet", async () => {
const user = userEvent.setup();
const merge = vi.fn(
async (_input: {
files: { path: string; name: string }[];
selectedIds: readonly string[];
onStatus: (stack: number, total: number) => void;
}) => 1,
);
render(
<FolderSheet
folder={{
path: "/job",
name: "Sala",
files: [
{ path: "/job/a.jpg", name: "a.jpg" },
{ path: "/job/b.jpg", name: "b.jpg" },
{ path: "/job/c.jpg", name: "c.jpg" },
],
}}
onClose={() => {}}
thumb={thumb}
merge={merge}
/>,
);
await user.click(screen.getByRole("button", { name: "Fundir exposições" }));
expect(merge).toHaveBeenCalledOnce();
const input = merge.mock.calls[0]![0];
expect(input.files.map((file) => file.name)).toEqual(["a.jpg", "b.jpg", "c.jpg"]);
expect(input.selectedIds).toEqual(["/job/a.jpg"]);
expect((await screen.findByRole("status")).textContent).toBe("1 DNG ficou nesta pasta.");
});
it("does not mount a thumbnail button for every file", () => { it("does not mount a thumbnail button for every file", () => {
const files = Array.from({ length: 200 }, (_, i) => ({ path: `/job/${i}.jpg`, name: `${i}.jpg` })); const files = Array.from({ length: 200 }, (_, i) => ({ path: `/job/${i}.jpg`, name: `${i}.jpg` }));
render(<FolderSheet folder={{ path: "/job", name: "job", files }} onClose={() => {}} thumb={thumb} />); render(<FolderSheet folder={{ path: "/job", name: "job", files }} onClose={() => {}} thumb={thumb} />);
+5 -2
View File
@@ -5,8 +5,11 @@ import { localOriginal } from "../platform.js";
import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js"; import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js";
export class MergeError extends Error { export class MergeError extends Error {
constructor(readonly code: "none" | "missing" | "engine" | "failed") { constructor(
super(code); readonly code: "none" | "missing" | "engine" | "failed",
readonly detail?: string,
) {
super(detail ? `${code}: ${detail}` : code);
} }
} }
+25 -17
View File
@@ -4,12 +4,14 @@ import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
/** The engine's long-side cap for a merge. The DNG is this photo, not the full sensor. */ /** The engine's long-side cap for a merge. The DNG is this photo, not the full sensor. */
export const MERGE_EDGE = 4096; export const MERGE_EDGE = 4096;
/** A DNG this merge already wrote is not another exposure. */
export function isMergedName(name: string): boolean {
const lower = name.toLowerCase();
return lower.endsWith(".dng") || lower.includes("-fundido");
}
function isMergedFile(photo: PhotoSummary): boolean { function isMergedFile(photo: PhotoSummary): boolean {
const names = [photo.originalName, photo.name]; return isMergedName(photo.originalName) || isMergedName(photo.name);
return names.some((name) => {
const lower = name.toLowerCase();
return lower.endsWith(".dng") || lower.includes("-fundido");
});
} }
export function frameOf(photo: PhotoSummary): BracketFrame { export function frameOf(photo: PhotoSummary): BracketFrame {
@@ -27,25 +29,31 @@ export function frameOf(photo: PhotoSummary): BracketFrame {
}; };
} }
function byCapture(a: PhotoSummary, b: PhotoSummary): number { function byFrame(a: BracketFrame, b: BracketFrame): number {
const time = (a.capturedAt ?? "").localeCompare(b.capturedAt ?? ""); const time = (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "");
if (time !== 0) return time; if (time !== 0) return time;
return (a.originalName || a.name).localeCompare(b.originalName || b.name, undefined, { numeric: true, sensitivity: "base" }); return (a.fileName ?? a.id).localeCompare(b.fileName ?? b.id, undefined, { numeric: true, sensitivity: "base" });
} }
/** /**
* Stacks to merge. A selection of two or more is that set (detected into angles when they are brackets, * Stacks to merge. A selection of two or more is that set (detected into angles when they are brackets,
* otherwise one stack in capture order). With nothing selected, every bracket in the folder is a stack. * otherwise one stack in capture order). With fewer than two selected, every bracket in the folder is a stack.
* A DNG already produced here is not an exposure. */
export function stacksOfFrames(frames: readonly BracketFrame[], selectedIds: readonly string[]): string[][] {
const selected = new Set(selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? frames.filter((frame) => selected.has(frame.id)) : [...frames];
if (pool.length < 2) return [];
const grouped = groupBrackets(pool);
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
if (!chosen) return [];
return [[...pool].sort(byFrame).map((frame) => frame.id)];
}
/**
* Stacks in a library collection. A DNG already produced here is not an exposure.
*/ */
export function stacksToMerge(photos: readonly PhotoSummary[], selectedIds: readonly string[]): string[][] { export function stacksToMerge(photos: readonly PhotoSummary[], selectedIds: readonly string[]): string[][] {
const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo)); const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo));
const selected = new Set(selectedIds); return stacksOfFrames(ready.map(frameOf), selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? ready.filter((photo) => selected.has(photo.id)) : ready;
if (pool.length < 2) return [];
const grouped = groupBrackets(pool.map(frameOf));
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
if (!chosen) return [];
return [[...pool].sort(byCapture).map((photo) => photo.id)];
} }
+34 -3
View File
@@ -13,7 +13,9 @@ import { useFolderScan } from "../library/folderScan.js";
import { FacesView } from "../library/FacesView.js"; import { FacesView } from "../library/FacesView.js";
import { LookupBanner } from "../library/PhotoLookup.js"; import { LookupBanner } from "../library/PhotoLookup.js";
import { FolderSheet } from "../library/FolderSheet.js"; import { FolderSheet } from "../library/FolderSheet.js";
import { beginDropWait, folderDropPath, htmlDropIsFolder, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js"; import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js";
import { mergeFolderNative } from "../library/folderMerge.js";
import { MERGE_EDGE } from "../library/mergeStacks.js";
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js"; import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
import { InfoPanel } from "../library/InfoPanel.js"; import { InfoPanel } from "../library/InfoPanel.js";
import { IptcInfo } from "../library/IptcInfo.js"; import { IptcInfo } from "../library/IptcInfo.js";
@@ -577,7 +579,7 @@ export function LibraryPage() {
))} ))}
</select> </select>
)} )}
{canCull && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && ( {canCull && !sheet && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={state.scope === "inbox" ? null : state.scope} photos={state.photos} selectedIds={[...state.selected]} /> <MergeButton api={api} orgId={orgId} eventId={state.scope === "inbox" ? null : state.scope} photos={state.photos} selectedIds={[...state.selected]} />
)} )}
{canCull && ( {canCull && (
@@ -707,7 +709,36 @@ export function LibraryPage() {
/> />
)} )}
{sheet ? ( {sheet ? (
<FolderSheet folder={sheet} onClose={() => setSheet(null)} thumb={folderThumb} /> <FolderSheet
folder={sheet}
onClose={() => setSheet(null)}
thumb={folderThumb}
{...(canCull
? {
merge: async (input: {
files: FolderListing["files"];
selectedIds: readonly string[];
onStatus: (stack: number, total: number) => void;
}) => {
const made = await mergeFolderNative({
files: input.files,
selectedIds: input.selectedIds,
onStatus: input.onStatus,
metaOf: folderMeta,
mergePaths: (paths) => mergeFolderDng(paths, MERGE_EDGE).then(() => undefined),
});
const folderPath = sheet.path;
try {
const listing = await openFolder(folderPath);
setSheet((current) => (current?.path === folderPath ? listing : current));
} catch {
// The DNG is already beside the frames. Reopening the folder shows it.
}
return made;
},
}
: {})}
/>
) : openingFolder ? ( ) : openingFolder ? (
<p className="p-8 text-center text-[13px] text-faint">{t.folderSheet.opening}</p> <p className="p-8 text-center text-[13px] text-faint">{t.folderSheet.opening}</p>
) : view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? ( ) : view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? (
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@photoreport/desktop", "name": "@photoreport/desktop",
"version": "0.3.23", "version": "0.3.24",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "photoreport-desktop" name = "photoreport-desktop"
version = "0.3.23" version = "0.3.24"
edition = "2024" edition = "2024"
publish = false publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine." description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
@@ -31,7 +31,7 @@ sha2 = "0.10"
libc = "0.2" libc = "0.2"
image = { version = "0.25", default-features = false, features = ["jpeg"] } image = { version = "0.25", default-features = false, features = ["jpeg"] }
# Capture time and filmstrip thumbnails. The embedded-preview feature reads the camera JPEG; the browser build leaves it off. # Capture time and filmstrip thumbnails. The embedded-preview feature reads the camera JPEG; the browser build leaves it off.
photoreport-engine = { path = "../../../engine/core", features = ["embedded-preview"] } photoreport-engine = { path = "../../../engine/core", features = ["embedded-preview", "photo-merge"] }
photoreport-faces = { path = "../../../workers/faces" } photoreport-faces = { path = "../../../workers/faces" }
tauri-plugin-dialog = "2" tauri-plugin-dialog = "2"
tauri-plugin-updater = "2" tauri-plugin-updater = "2"
+4
View File
@@ -22,6 +22,10 @@ fn main() {
"folder_drop", "folder_drop",
"folder_open", "folder_open",
"folder_thumb", "folder_thumb",
"folder_read",
"folder_meta",
"folder_merge_dng",
"folder_save_dng",
"ftp_preview", "ftp_preview",
"ftp_info", "ftp_info",
"catalog_folders", "catalog_folders",
@@ -37,6 +37,10 @@
"allow-folder-drop", "allow-folder-drop",
"allow-folder-open", "allow-folder-open",
"allow-folder-thumb", "allow-folder-thumb",
"allow-folder-read",
"allow-folder-meta",
"allow-folder-merge-dng",
"allow-folder-save-dng",
"allow-ftp-preview", "allow-ftp-preview",
"allow-ftp-info", "allow-ftp-info",
"allow-catalog-folders", "allow-catalog-folders",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-merge-dng"
description = "Enables the folder_merge_dng command without any pre-configured scope."
commands.allow = ["folder_merge_dng"]
[[permission]]
identifier = "deny-folder-merge-dng"
description = "Denies the folder_merge_dng command without any pre-configured scope."
commands.deny = ["folder_merge_dng"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-meta"
description = "Enables the folder_meta command without any pre-configured scope."
commands.allow = ["folder_meta"]
[[permission]]
identifier = "deny-folder-meta"
description = "Denies the folder_meta command without any pre-configured scope."
commands.deny = ["folder_meta"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-read"
description = "Enables the folder_read command without any pre-configured scope."
commands.allow = ["folder_read"]
[[permission]]
identifier = "deny-folder-read"
description = "Denies the folder_read command without any pre-configured scope."
commands.deny = ["folder_read"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-folder-save-dng"
description = "Enables the folder_save_dng command without any pre-configured scope."
commands.allow = ["folder_save_dng"]
[[permission]]
identifier = "deny-folder-save-dng"
description = "Denies the folder_save_dng command without any pre-configured scope."
commands.deny = ["folder_save_dng"]
+250 -2
View File
@@ -1,8 +1,8 @@
//! A folder dropped on the window, shown as a contact sheet. //! A folder dropped on the window, shown as a contact sheet.
//! //!
//! The page only learns the path because the operating system delivered it to this window. `folder_open` refuses //! The page only learns the path because the operating system delivered it to this window. `folder_open` refuses
//! any other path, and a thumbnail is only read for a file inside a folder that was opened that way. Nothing is //! any other path, and a file is only read inside a folder that was opened that way. Nothing is uploaded.
//! uploaded, moved or deleted: the sheet is a view of the folder on this computer. //! The one write is a merged `-fundido.dng` beside the frames of an open sheet.
use std::collections::HashSet; use std::collections::HashSet;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -80,6 +80,63 @@ impl OpenFolders {
} }
Ok(canon) Ok(canon)
} }
/// Where a merged DNG may be written: a single `-fundido.dng` name, inside an opened folder, never through a
/// symlink that leaves it. Replacing an earlier merge of the same name is allowed.
pub fn allow_save_dng(&self, dir: &Path, name: &str, len: usize) -> Result<PathBuf, String> {
if len == 0 || len > MAX_DNG_BYTES {
return Err("bad_file".to_string());
}
if !is_fundido_dng(name) {
return Err("not_a_merge".to_string());
}
let dir = dir.canonicalize().map_err(|e| e.to_string())?;
if !dir.is_dir() {
return Err("not_a_folder".to_string());
}
let open = self.open.lock().unwrap();
if !open.iter().any(|root| dir.starts_with(root)) {
return Err("not_allowed".to_string());
}
let dest = dir.join(name);
match std::fs::symlink_metadata(&dest) {
Ok(meta) if meta.file_type().is_symlink() || !meta.is_file() => {
return Err("not_allowed".to_string());
}
_ => {}
}
Ok(dest)
}
}
/// A merged DNG is tens of megabytes. Anything larger is not this merge.
const MAX_DNG_BYTES: usize = 512 * 1024 * 1024;
fn is_fundido_dng(name: &str) -> bool {
if name.contains('/') || name.contains('\\') || name.contains('\0') || name.starts_with('.') {
return false;
}
let lower = name.to_ascii_lowercase();
lower.ends_with(".dng") && lower.contains("-fundido")
}
fn percent_decode(value: &str) -> String {
let bytes = value.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let Ok(v) = u8::from_str_radix(&value[i + 1..i + 3], 16)
{
out.push(v);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
} }
fn sort_names(paths: &mut [PathBuf]) { fn sort_names(paths: &mut [PathBuf]) {
@@ -181,6 +238,113 @@ pub async fn folder_thumb(
Ok(tauri::ipc::Response::new(jpeg)) Ok(tauri::ipc::Response::new(jpeg))
} }
/// The original of one photo on the open sheet, so a merge can read the exposures.
#[tauri::command]
pub async fn folder_read(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<tauri::ipc::Response, String> {
let file = folders.allow_file(Path::new(&path))?;
let bytes = tokio::fs::read(&file).await.map_err(|e| e.to_string())?;
Ok(tauri::ipc::Response::new(bytes))
}
/// Capture metadata of one photo on the open sheet. The bytes stay in this process.
#[tauri::command]
pub async fn folder_meta(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<String, String> {
let file = folders.allow_file(Path::new(&path))?;
tokio::task::spawn_blocking(move || {
let bytes = std::fs::read(&file).map_err(|e| e.to_string())?;
Ok(photoreport_engine::capture::read_capture(&bytes).to_string())
})
.await
.map_err(|e| e.to_string())?
}
/// The files of one stack, in merge order, and where the DNG is written (beside the middle frame).
pub fn merge_plan(
folders: &OpenFolders,
paths: &[String],
) -> Result<(Vec<PathBuf>, PathBuf), String> {
if paths.len() < 2 {
return Err("none".to_string());
}
let mut files = Vec::with_capacity(paths.len());
for path in paths {
files.push(folders.allow_file(Path::new(path))?);
}
let mid = &files[(files.len() - 1) / 2];
let dir = mid.parent().ok_or_else(|| "failed".to_string())?;
let stem = mid
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| "failed".to_string())?;
let dest = folders.allow_save_dng(dir, &format!("{stem}-fundido.dng"), 1)?;
Ok((files, dest))
}
fn merge_files_to(files: &[PathBuf], dest: &Path, max_edge: u32) -> Result<(), String> {
let mut bufs = Vec::with_capacity(files.len());
for file in files {
bufs.push(std::fs::read(file).map_err(|e| e.to_string())?);
}
let refs: Vec<&[u8]> = bufs.iter().map(Vec::as_slice).collect();
let dng =
photoreport_engine::merge::merge_linear_dng(&refs, max_edge).map_err(|e| e.to_string())?;
if dng.is_empty() || dng.len() > MAX_DNG_BYTES {
return Err("bad_file".to_string());
}
std::fs::write(dest, dng).map_err(|e| e.to_string())
}
/// Merges one stack and writes the DNG beside the middle frame. The raws are not sent to the page.
#[tauri::command]
pub async fn folder_merge_dng(
folders: tauri::State<'_, OpenFolders>,
paths: Vec<String>,
max_edge: u32,
) -> Result<String, String> {
let (files, dest) = merge_plan(&folders, &paths)?;
tokio::task::spawn_blocking(move || {
merge_files_to(&files, &dest, max_edge)?;
Ok(dest.to_string_lossy().into_owned())
})
.await
.map_err(|e| e.to_string())?
}
/// Writes one merged DNG into an opened folder. The bytes are the request body; `dir` and `name` are
/// percent-encoded headers, so the DNG is not sent as a JSON array.
#[tauri::command]
pub async fn folder_save_dng(
request: tauri::ipc::Request<'_>,
folders: tauri::State<'_, OpenFolders>,
) -> Result<String, String> {
let header = |name: &str| {
request
.headers()
.get(name)
.and_then(|v| v.to_str().ok())
.map(percent_decode)
.ok_or_else(|| format!("missing {name}"))
};
let dir = header("dir")?;
let name = header("name")?;
let tauri::ipc::InvokeBody::Raw(data) = request.body() else {
return Err("expected the file as the body".to_string());
};
// Copy before the write: the request does not live across the await.
let bytes = data.to_vec();
let path = folders.allow_save_dng(Path::new(&dir), &name, bytes.len())?;
tokio::fs::write(&path, &bytes)
.await
.map_err(|e| e.to_string())?;
Ok(path.to_string_lossy().into_owned())
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -278,4 +442,88 @@ mod tests {
assert!(thumb.len() < bytes.len()); assert!(thumb.len() < bytes.len());
let _ = std::fs::remove_dir_all(&root); let _ = std::fs::remove_dir_all(&root);
} }
#[test]
fn a_merge_is_only_a_fundido_dng_inside_the_open_folder() {
let root = temp_dir("save");
let nested = root.join("sala");
std::fs::create_dir_all(&nested).unwrap();
let other = temp_dir("save-other");
let folders = OpenFolders::default();
folders.note(&[root.clone()]);
folders.open(&root).unwrap();
let saved = folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 4)
.unwrap();
assert_eq!(
saved,
nested.canonicalize().unwrap().join("IMG_0002-fundido.dng")
);
assert_eq!(
folders
.allow_save_dng(&other, "IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_allowed"
);
assert_eq!(
folders
.allow_save_dng(&nested, "../IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_a_merge"
);
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002.dng", 4)
.unwrap_err(),
"not_a_merge"
);
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 0)
.unwrap_err(),
"bad_file"
);
#[cfg(unix)]
{
let link = nested.join("IMG_0002-fundido.dng");
let outside = other.join("secret.dng");
std::fs::write(&outside, b"x").unwrap();
std::os::unix::fs::symlink(&outside, &link).unwrap();
assert_eq!(
folders
.allow_save_dng(&nested, "IMG_0002-fundido.dng", 4)
.unwrap_err(),
"not_allowed"
);
}
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(&other);
}
#[test]
fn a_stack_is_named_after_its_middle_frame() {
let root = temp_dir("plan");
let names = ["dark.jpg", "mid.jpg", "bright.jpg"];
for name in names {
std::fs::write(root.join(name), b"jpeg").unwrap();
}
let folders = OpenFolders::default();
folders.note(&[root.clone()]);
folders.open(&root).unwrap();
let paths: Vec<String> = names
.iter()
.map(|name| root.join(name).to_string_lossy().into_owned())
.collect();
let (files, dest) = merge_plan(&folders, &paths).unwrap();
assert_eq!(files.len(), 3);
assert_eq!(
dest.file_name().unwrap().to_string_lossy(),
"mid-fundido.dng"
);
assert_eq!(merge_plan(&folders, &paths[..1]).unwrap_err(), "none");
let _ = std::fs::remove_dir_all(&root);
}
} }
+4
View File
@@ -145,6 +145,10 @@ pub fn run() {
browse::folder_drop, browse::folder_drop,
browse::folder_open, browse::folder_open,
browse::folder_thumb, browse::folder_thumb,
browse::folder_read,
browse::folder_meta,
browse::folder_merge_dng,
browse::folder_save_dng,
ftp::ftp_preview, ftp::ftp_preview,
ftp::ftp_info, ftp::ftp_info,
catalog::catalog_folders, catalog::catalog_folders,
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport", "productName": "PhotoReport",
"version": "0.3.23", "version": "0.3.24",
"identifier": "pt.photoreport.desktop", "identifier": "pt.photoreport.desktop",
"build": { "build": {
"devUrl": "http://localhost:5173", "devUrl": "http://localhost:5173",
+4 -2
View File
@@ -10,8 +10,10 @@ This file is the in-repo summary agents work from. Decisions dated 2026-10-11.
Final domain: `app.photoreport.pt`. Data (accounts, galleries, sales, squads) is imported, not restarted. Final domain: `app.photoreport.pt`. Data (accounts, galleries, sales, squads) is imported, not restarted.
- Desktop = Tauri around the same React SPA (replaces the Flutter Studio). - Desktop = Tauri around the same React SPA (replaces the Flutter Studio).
- Develop engine = LightCraft crates (`lightcraft-develop`, `lightcraft-pipeline`, `lightcraft-raw`, - Develop engine = LightCraft crates (`lightcraft-develop`, `lightcraft-pipeline`, `lightcraft-raw`,
`lightcraft-codecs`, `lightcraft-faces`), pinned, behind `engine/core`. Not `lightcraft-engine`/`catalog`: `lightcraft-codecs`, `lightcraft-faces`), pinned, behind `engine/core`. Not `lightcraft-engine`/`catalog`
our catalog is the API. for the library: our catalog is the API. The desktop folder merge is the exception (`photo-merge`):
it runs LightCraft Photo Merge so a raw without its own matrices still gets colour tags in the DNG.
The browser engine leaves that feature off.
- Faces: `lightcraft-faces` (YuNet detection + AuraFace v1 recognition, SFace optional; pure Rust) in - Faces: `lightcraft-faces` (YuNet detection + AuraFace v1 recognition, SFace optional; pure Rust) in
`workers/faces`, a long-running process the background worker talks to over stdin/stdout. See "Faces" below. `workers/faces`, a long-running process the background worker talks to over stdin/stdout. See "Faces" below.
Enabled for FPA (own photos, internal federation use for news and galleries); off by default elsewhere. Enabled for FPA (own photos, internal federation use for news and galleries); off by default elsewhere.
+5
View File
@@ -11,6 +11,9 @@ default = ["parallel"]
parallel = ["lightcraft-codecs/parallel"] parallel = ["lightcraft-codecs/parallel"]
# Camera JPEG inside a raw, for the desktop filmstrip. Off in the browser build. # Camera JPEG inside a raw, for the desktop filmstrip. Off in the browser build.
embedded-preview = [] embedded-preview = []
# Write a merged DNG the way LightCraft Photo Merge does, including colour tags for CR2/CR3/NEF.
# Off in the browser build: that crate is the native app engine, not the develop core.
photo-merge = ["dep:lightcraft-engine", "dep:lightcraft-catalog"]
[dependencies] [dependencies]
lightcraft-develop = { workspace = true } lightcraft-develop = { workspace = true }
@@ -22,6 +25,8 @@ lightcraft-merge = { workspace = true }
lightcraft-raw = { workspace = true } lightcraft-raw = { workspace = true }
lightcraft-color = { workspace = true } lightcraft-color = { workspace = true }
lightcraft-meta = { workspace = true } lightcraft-meta = { workspace = true }
lightcraft-engine = { workspace = true, optional = true }
lightcraft-catalog = { workspace = true, optional = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
+97 -5
View File
@@ -10,10 +10,9 @@ use std::sync::Arc;
use lightcraft_color::Xy; use lightcraft_color::Xy;
use lightcraft_develop::DevelopSettings; use lightcraft_develop::DevelopSettings;
use lightcraft_merge::frame::Frame; use lightcraft_merge::frame::Frame;
use lightcraft_merge::{ use lightcraft_merge::{Deghost, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress};
Deghost, DngSamples, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress, #[cfg(not(feature = "photo-merge"))]
write_linear_dng, use lightcraft_merge::{DngSamples, write_linear_dng};
};
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto}; use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto};
use lightcraft_raster::Rgb32f; use lightcraft_raster::Rgb32f;
use lightcraft_raster::resample::{Filter, fit}; use lightcraft_raster::resample::{Filter, fit};
@@ -233,7 +232,63 @@ pub fn merge_linear_dng(files: &[&[u8]], max_edge: u32) -> Result<Vec<u8>, Engin
"a bracket needs at least two exposures".into(), "a bracket needs at least two exposures".into(),
)); ));
} }
let edge = clamped_edge(max_edge); write_merged_dng(files, clamped_edge(max_edge))
}
/// LightCraft Photo Merge (`MergeJob`) reads each raw with `starting_colour_tags` before
/// `write_linear_dng`. A CR3 has no colour matrix of its own; without that step the file is a
/// linear DNG other raw tools refuse. The develop crates do not export the step.
#[cfg(feature = "photo-merge")]
fn write_merged_dng(files: &[&[u8]], edge: usize) -> Result<Vec<u8>, EngineError> {
use std::sync::Arc;
use lightcraft_catalog::PhotoId;
use lightcraft_engine::merge::{MergeFinish, MergeJob, MergeKind};
let owned: Vec<Vec<u8>> = files.iter().map(|file| (*file).to_vec()).collect();
let count = owned.len();
let read = Arc::new(move |path: &str| -> Result<Vec<u8>, String> {
let index: usize = path
.parse()
.map_err(|_| format!("bad frame index {path}"))?;
owned
.get(index)
.cloned()
.ok_or_else(|| format!("missing frame {index}"))
});
let sources = (0..count)
.map(|index| (PhotoId(index as u64), index.to_string()))
.collect();
let job = MergeJob {
kind: MergeKind::Hdr {
hdr: HdrOptions {
align: true,
deghost: Deghost::None,
},
},
finish: MergeFinish {
auto_settings: false,
stack: false,
show_overlay: false,
},
sources,
preview: Some(edge),
read,
};
let out = job
.run(&|_done, _stage| true)
.map_err(EngineError::Decode)?;
let raw = lightcraft_raw::decode(&out.dng).map_err(|e| EngineError::Decode(e.to_string()))?;
if !lightcraft_raw::color::has_matrix(&raw.color) {
return Err(EngineError::Decode(
"the merged file has no colour matrix, so other raw tools cannot open it".into(),
));
}
Ok(out.dng)
}
#[cfg(not(feature = "photo-merge"))]
fn write_merged_dng(files: &[&[u8]], edge: usize) -> Result<Vec<u8>, EngineError> {
let mut frames = Vec::with_capacity(files.len()); let mut frames = Vec::with_capacity(files.len());
for file in files { for file in files {
frames.push(load_bracket_frame(file, edge)?); frames.push(load_bracket_frame(file, edge)?);
@@ -360,6 +415,11 @@ mod tests {
let files = [dark.as_slice(), mid.as_slice(), bright.as_slice()]; let files = [dark.as_slice(), mid.as_slice(), bright.as_slice()];
let dng = merge_linear_dng(&files, 256).expect("dng"); let dng = merge_linear_dng(&files, 256).expect("dng");
assert!(dng.len() > 64); assert!(dng.len() > 64);
let raw = lightcraft_raw::decode(&dng).expect("colour tags");
assert!(
lightcraft_raw::color::has_matrix(&raw.color),
"a merged DNG without ColorMatrix is refused by other raw tools"
);
let source = crate::render::Source::decode(&dng, 256).expect("decode"); let source = crate::render::Source::decode(&dng, 256).expect("decode");
let (w, h) = source.size(); let (w, h) = source.size();
assert!(w >= 64 && h >= 64, "{w}x{h}"); assert!(w >= 64 && h >= 64, "{w}x{h}");
@@ -370,6 +430,38 @@ mod tests {
); );
} }
/// Three camera raws in `PHOTOREPORT_MERGE_SAMPLES` (comma-separated paths). Confirms the
/// Photo Merge colour tags, which a synthetic linear DNG already has on its own.
#[cfg(feature = "photo-merge")]
#[test]
#[ignore = "local camera raws via PHOTOREPORT_MERGE_SAMPLES"]
fn a_camera_raw_merge_carries_lightcraft_colour_tags() {
let spec = std::env::var("PHOTOREPORT_MERGE_SAMPLES")
.expect("PHOTOREPORT_MERGE_SAMPLES is three raw paths separated by commas");
let paths: Vec<&str> = spec
.split(',')
.map(str::trim)
.filter(|path| !path.is_empty())
.collect();
assert!(paths.len() >= 2, "need at least two raws");
let mut owned = Vec::new();
for path in &paths {
let bytes = std::fs::read(path).unwrap_or_else(|err| panic!("{path}: {err}"));
owned.push(bytes);
}
let refs: Vec<&[u8]> = owned.iter().map(Vec::as_slice).collect();
let dng = merge_linear_dng(&refs, 4096).expect("dng");
let raw = lightcraft_raw::decode(&dng).expect("decode");
assert!(
lightcraft_raw::color::has_matrix(&raw.color),
"ColorMatrix missing"
);
assert!(
!raw.color.profile.is_empty(),
"matrix without the fitted camera look"
);
}
#[test] #[test]
fn one_photo_is_not_a_bracket() { fn one_photo_is_not_a_bracket() {
let mid = exposure_dng(0.0); let mid = exposure_dng(0.0);