diff --git a/apps/api/src/autopilot/look.ts b/apps/api/src/autopilot/look.ts index e070097..7ee81b3 100644 --- a/apps/api/src/autopilot/look.ts +++ b/apps/api/src/autopilot/look.ts @@ -56,6 +56,37 @@ export function toneApplied(key: string, measured: number, strength: number, rep return measured * strength; } +/** Local contrast and sharpening. Their kernel is a fraction of the whole frame, so a tight crop shows them enlarged. */ +export const DETAIL_KEYS = ["effects.clarity", "effects.texture", "detail.sharpenAmount"] as const; + +/** + * How much of the frame's long edge the crop keeps. Structure and sharpen are applied as on the whole frame; + * this is the share a crop must scale them by so a tight frame does not exaggerate them. + */ +export function cropLongFraction(crop: { x0: number; y0: number; x1: number; y1: number }, width: number, height: number): number { + const cw = Math.max(0, crop.x1 - crop.x0) * width; + const ch = Math.max(0, crop.y1 - crop.y0) * height; + return Math.min(1, Math.max(cw, ch) / Math.max(width, height, 1)); +} + +/** + * Clarity, texture and sharpening, scaled to the crop. A crop that keeps the whole frame leaves them as they are. + * A tighter one keeps the same proportion of the frame, and never less than a third, so a close portrait stays + * sharp without the halo a whole-frame kernel leaves on it. + */ +export function detailForCrop(values: Record, crop: { x0: number; y0: number; x1: number; y1: number } | null, width: number, height: number): Record { + if (!crop) return values; + const kept = cropLongFraction(crop, width, height); + if (kept >= 0.98) return values; + const scale = Math.max(kept, 1 / 3); + const out = { ...values }; + for (const key of DETAIL_KEYS) { + const value = out[key]; + if (value) out[key] = Math.round(value * scale * 100) / 100; + } + return out; +} + /** The look's values for one photo (empty for "none"). */ export function lookValues(look: Look, iso?: number | null): Record { if (look === "none") return {}; diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index 6a74e41..b83ce7e 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -18,7 +18,7 @@ import { sequenceWeights } from "./sequence.js"; import { bestOf, FOCUS_SHARP, groupBursts, reportagePickCount } from "./bursts.js"; import { curate, matchMinutes } from "./curate.js"; import { type LearntStyle, learntStyle, TONE_KEYS, WB_KEYS } from "./learning.js"; -import { lookValues, toneApplied } from "./look.js"; +import { detailForCrop, lookValues, toneApplied } from "./look.js"; const STALE_RUNNING_MS = 10 * 60_000; /** A burst is decided once no new frame of it has arrived for this long. */ @@ -118,11 +118,12 @@ export class AutopilotService { // White balance and tone (a measured amount), and the level angle. let angle = 0; + let values: Record | null = null; // What this photographer's corrections taught it (none until there are enough that agree). const style = await learntStyle(db, photo.organizationId, photo.uploaderId, photo.event?.venue).catch(() => null); if (engine && (settings.tone || settings.whiteBalance || settings.level)) { const auto = await engine.auto(preview, null); - const values: Record = {}; + values = {}; if (settings.whiteBalance) for (const k of WB_KEYS) if (auto.values[k] !== undefined) values[k] = auto.values[k]! + (style?.offsets[k] ?? 0); if (settings.tone) for (const k of TONE_KEYS) { @@ -130,8 +131,8 @@ export class AutopilotService { if (v) values[k] = Math.round(v * 100) / 100; } // The finishing look (colour, local contrast, sharpening, noise by ISO): never over what was measured. + // Structure and sharpening are scaled to the crop below, once the crop exists: they belong to the whole frame. for (const [k, v] of Object.entries(lookValues(settings.look, photo.iso))) if (values[k] === undefined) values[k] = v; - if (Object.keys(values).length) ops.push({ command: "develop.set", params: { values } } as EditCommand); if (settings.level && auto.angle !== null && Math.abs(auto.angle) >= MIN_LEVEL && Math.abs(auto.angle) <= MAX_LEVEL) angle = auto.angle; } @@ -155,6 +156,10 @@ export class AutopilotService { } const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(wideComposition.rect, angle, W, H) : null; if (!crop && angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H); + if (values) { + const tuned = detailForCrop(values, crop, W, H); + if (Object.keys(tuned).length) ops.push({ command: "develop.set", params: { values: tuned } } as EditCommand); + } if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } } as EditCommand); // Someone already edited it (on the desktop app without a network, before it was uploaded): their edit @@ -206,7 +211,7 @@ export class AutopilotService { if (busy) continue; const photos = await db.photo.findMany({ where: { eventId, autopilotStatus: "DONE" }, - select: { id: true, capturedAt: true, cameraSerial: true, cameraModel: true, uploaderId: true, createdAt: true, flag: true, autopilot: true, width: true, height: true, sha256: true, facesStatus: true }, + select: { id: true, capturedAt: true, cameraSerial: true, cameraModel: true, uploaderId: true, createdAt: true, flag: true, autopilot: true, width: true, height: true, sha256: true, facesStatus: true, iso: true }, }); const reportageEvent = isReportage(event); const look = await sequenceWeights( @@ -256,10 +261,11 @@ export class AutopilotService { const edited = await db.photoEdit.count({ where: { photoId: framePick.id, NOT: { clientId: "autopilot" } } }); if (edited) continue; const rect = constrainRotated(planned, framePick.rec?.angle ?? 0, framePick.width ?? 3, framePick.height ?? 2); + const aspect = settings.aspect ?? [framePick.width ?? 3, framePick.height ?? 2]; await develop .append(framePick.id, framePick.uploaderId ?? event.createdById ?? null, { clientId: "autopilot", - ops: [{ opId: `autopilot-${framePick.id}-plan-${key}`, command: { command: "crop.set", params: { rect, angle: framePick.rec?.angle ?? 0, aspect: settings.aspect ?? [framePick.width ?? 3, framePick.height ?? 2] } } as EditCommand }], + ops: cropOps(framePick.id, `plan-${key}`, rect, framePick.rec?.angle ?? 0, aspect, detailForCrop(lookValues(settings.look, framePick.iso), rect, framePick.width ?? 3, framePick.height ?? 2)), }) .catch((err: unknown) => log.warn({ err }, "autopilot: plan crop failed")); } @@ -272,10 +278,11 @@ export class AutopilotService { const wider = crop2 && second.rec?.wide && (second.rec.wide.x1 - second.rec.wide.x0) / (crop2.x1 - crop2.x0) > 1.12 ? second.rec.wide : null; if (crop2 && second.rec?.subject && settings.crop && !secondEdited) { const rect = wider ?? constrainRotated(tighter(crop2, second.rec.subject, 0.88), second.rec.angle, second.width ?? 3, second.height ?? 2); + const aspect = settings.aspect ?? [second.width ?? 3, second.height ?? 2]; await develop .append(second.id, second.uploaderId ?? event.createdById ?? null, { clientId: "autopilot", - ops: [{ opId: `autopilot-${second.id}-variant`, command: { command: "crop.set", params: { rect, angle: second.rec.angle, aspect: settings.aspect ?? [second.width ?? 3, second.height ?? 2] } } as EditCommand }], + ops: cropOps(second.id, "variant", rect, second.rec.angle, aspect, detailForCrop(lookValues(settings.look, second.iso), rect, second.width ?? 3, second.height ?? 2)), }) .catch((err: unknown) => log.warn({ err }, "autopilot: variant crop failed")); } @@ -381,6 +388,14 @@ function subjectFocus(d: { people: { x0: number; y0: number; x1: number; y1: num return values.length ? Math.max(...values) : 0; } +/** A tighter plan keeps the crop and the structure scaled to that crop, so the halo does not grow with the tighter frame. */ +function cropOps(photoId: string, key: string, rect: Box, angle: number, aspect: readonly number[], detail: Record): { opId: string; command: EditCommand }[] { + const ops: { opId: string; command: EditCommand }[] = []; + if (Object.keys(detail).length) ops.push({ opId: `autopilot-${photoId}-${key}-look`, command: { command: "develop.set", params: { values: detail } } as EditCommand }); + ops.push({ opId: `autopilot-${photoId}-${key}`, command: { command: "crop.set", params: { rect, angle, aspect } } as EditCommand }); + return ops; +} + /** A plan is worth applying when its height is clearly different from the crop already on the photo. */ function distinctPlan(a: Box, b: Box): boolean { const ah = a.y1 - a.y0; diff --git a/apps/api/src/composition/detect.ts b/apps/api/src/composition/detect.ts index 5bd4c66..64e65ad 100644 --- a/apps/api/src/composition/detect.ts +++ b/apps/api/src/composition/detect.ts @@ -13,14 +13,14 @@ const SIZE = 640; const PERSON = 0; const BALL = 32; // COCO "sports ball" -/** Loads the detector on first use from the downloaded models (null while the model isn't there). */ -export function lazyDetector(storageRoot: string): () => Promise | null { +/** Loads the detector on first use from the downloaded models (null while the model isn't there). `sessions` run side by side. */ +export function lazyDetector(storageRoot: string, sessions = 1): () => Promise | null { let loading: Promise | null = null; return () => { const dir = modelsDir(storageRoot); const file = dir && join(dir, "yolox_s.onnx"); if (!file || !existsSync(file)) return null; - loading ??= SubjectDetector.load(file).catch((err: unknown) => { + loading ??= SubjectDetector.load(file, sessions).catch((err: unknown) => { loading = null; throw err; }); @@ -28,11 +28,35 @@ export function lazyDetector(storageRoot: string): () => Promise void)[] = []; - static async load(file: string): Promise { - return new SubjectDetector(await ort.InferenceSession.create(file, { intraOpNumThreads: 2 })); + constructor(sessions: ort.InferenceSession[]) { + this.idle.push(...sessions); + } + + acquire(): Promise { + const session = this.idle.pop(); + if (session) return Promise.resolve(session); + return new Promise((resolve) => this.waiters.push(resolve)); + } + + release(session: ort.InferenceSession): void { + const waiter = this.waiters.shift(); + if (waiter) waiter(session); + else this.idle.push(session); + } +} + +export class SubjectDetector { + private constructor(private readonly pool: SessionPool) {} + + static async load(file: string, sessions = 1): Promise { + const count = Math.max(1, Math.min(Math.floor(sessions), 16)); + const created = await Promise.all(Array.from({ length: count }, () => ort.InferenceSession.create(file, { intraOpNumThreads: 1 }))); + return new SubjectDetector(new SessionPool(created)); } /** Detections in `file` (any JPEG/PNG), upright, as fractions of the photo. */ @@ -59,9 +83,15 @@ export class SubjectDetector { input[plane + i] = data[i * 3 + 1]!; input[2 * plane + i] = data[i * 3]!; } - const name = this.session.inputNames[0]!; - const out = await this.session.run({ [name]: new ort.Tensor("float32", input, [1, 3, SIZE, SIZE]) }); - const raw = out[this.session.outputNames[0]!]!.data as Float32Array; + const session = await this.pool.acquire(); + let raw: Float32Array; + try { + const name = session.inputNames[0]!; + const out = await session.run({ [name]: new ort.Tensor("float32", input, [1, 3, SIZE, SIZE]) }); + raw = out[session.outputNames[0]!]!.data as Float32Array; + } finally { + this.pool.release(session); + } const all = decode(raw, scale, width, height); const people = nms(all.filter((d) => d.cls === PERSON)); await addSharpness(file, people); diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index 37d2daa..03d5af3 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -86,6 +86,8 @@ const Env = z.object({ /** Stripe API base; only changed for local end-to-end runs against a stand-in. */ STRIPE_API_URL: z.string().url().default("https://api.stripe.com"), RENDER_PROCESSES: z.coerce.number().int().positive().optional(), + /** Photos the autopilot edits at once. Unset: sized from the container, like the renders. */ + AUTOPILOT_CONCURRENCY: z.coerce.number().int().positive().optional(), /** Desktop shell updates: the Gitea API base of this repository and a read-only token for its releases. Unset: none. */ DESKTOP_RELEASES_API: z.string().url().optional(), DESKTOP_RELEASES_TOKEN: z.string().min(10).optional(), diff --git a/apps/api/src/lib/capacity.ts b/apps/api/src/lib/capacity.ts index fa5b472..f170e80 100644 --- a/apps/api/src/lib/capacity.ts +++ b/apps/api/src/lib/capacity.ts @@ -23,6 +23,8 @@ export interface Capacity { archiveDownloads: number; faces: number; render: number; + /** Photos the autopilot analyses and edits at once. */ + autopilot: number; delivery: number; } @@ -32,7 +34,7 @@ const MEMORY_PER = { faces: 0.8, render: 0.6, ingest: 0.4, archive: 0.4 }; const clamp = (n: number, min: number, max: number) => Math.max(min, Math.min(max, Math.floor(n))); export function planCapacity( - set: { ingest?: number | undefined; archive?: number | undefined; faces?: number | undefined; render?: number | undefined; delivery?: number | undefined }, + set: { ingest?: number | undefined; archive?: number | undefined; faces?: number | undefined; render?: number | undefined; autopilot?: number | undefined; delivery?: number | undefined }, machine: { cpus: number; memoryBytes: number } = { cpus: availableParallelism(), memoryBytes: totalmem() }, ): Capacity { const cpus = Math.max(1, machine.cpus); @@ -54,7 +56,10 @@ export function planCapacity( // database too), and many more images in flight, which mostly wait for the cloud. archiveBurst: Math.max(set.archive ?? 0, clamp(Math.min(cpus * 3, byMemory("archive", 0.6)), 2, 192)), archiveDownloads: clamp(Math.max(16, cpus * 20), 16, 1000), - render: set.render ?? clamp(Math.min(cpus * 0.15, byMemory("render", 0.15)), 2, 12), + // A render used to take a small slice of the machine, so a backlog of edits crawled. Use the cores, and stop + // when memory (a decoded photo) runs short. + render: set.render ?? clamp(Math.min(cpus * 0.5, byMemory("render", 0.45)), 2, 16), + autopilot: set.autopilot ?? clamp(Math.min(cpus * 0.75, byMemory("render", 0.35)), 2, 16), delivery: set.delivery ?? clamp(cpus * 0.25, 4, 16), }; } diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 0e61d45..6732b0b 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -60,13 +60,14 @@ const capacity = planCapacity({ archive: config.ARCHIVE_CONCURRENCY, faces: config.FACES_PROCESSES, render: config.RENDER_PROCESSES, + autopilot: config.AUTOPILOT_CONCURRENCY, delivery: config.DELIVERY_CONCURRENCY, }); log.info(capacity, "capacity"); // Enough connections for everything running at once, within what's left of Postgres' max_connections once the // API's cluster (Prisma pool and realtime connections), the superuser-reserved slots, the realtime broadcaster // and ad hoc connections (migrations, scripts, psql) have theirs. -const wanted = 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2); +const wanted = 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest + capacity.autopilot + capacity.render) / 2); const db = createDb( config.DATABASE_URL, dbConnectionBudget(wanted, { @@ -140,8 +141,8 @@ if (!faces) log.warn("FACES_BIN/FACES_MODELS_DIR not set: face analysis is off i // Autopilot: edits and picks what arrives at events that have it switched on (docs/photo-editing-rules.md). const autopilot = new AutopilotWorker( - new AutopilotService({ db, storage, broadcaster, log, develop, engine: renderEngine, detector: lazyDetector(config.STORAGE_ROOT), deliveries: deliveryService }), - { concurrency: 2, intervalMs: 1000, log }, + new AutopilotService({ db, storage, broadcaster, log, develop, engine: renderEngine, detector: lazyDetector(config.STORAGE_ROOT, capacity.autopilot), deliveries: deliveryService }), + { concurrency: capacity.autopilot, intervalMs: 200, log }, ); const sports = config.SPORTS_SYNC === "on" ? new SportsWorker(sportsService, { log }) : undefined; diff --git a/apps/api/test/capacity.test.ts b/apps/api/test/capacity.test.ts index 8bbabcc..170b6a7 100644 --- a/apps/api/test/capacity.test.ts +++ b/apps/api/test/capacity.test.ts @@ -7,8 +7,8 @@ describe("capacity", () => { it("does more at once on a bigger container", () => { const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB }); const big = planCapacity({}, { cpus: 32, memoryBytes: 64 * GB }); - expect(small).toMatchObject({ faces: 3, ingest: 4, archive: 2, render: 2, delivery: 4 }); - expect(big).toMatchObject({ cpus: 32, faces: 6, ingest: 8, archive: 9, archiveBurst: 91, render: 4, delivery: 8 }); + expect(small).toMatchObject({ faces: 3, ingest: 4, archive: 2, render: 2, autopilot: 2, delivery: 4 }); + expect(big).toMatchObject({ cpus: 32, faces: 6, ingest: 8, archive: 9, archiveBurst: 91, render: 16, autopilot: 16, delivery: 8 }); expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 6, archiveBurst: 91, archiveDownloads: 960 }); // A fixed ARCHIVE_CONCURRENCY never holds a backlog back; downloads run many at once even on a small machine. expect(planCapacity({ archive: 2 }, { cpus: 4, memoryBytes: 8 * GB })).toMatchObject({ archive: 2, archiveBurst: 7, archiveDownloads: 80 }); diff --git a/apps/api/test/look.test.ts b/apps/api/test/look.test.ts index 38a37b0..0f02caa 100644 --- a/apps/api/test/look.test.ts +++ b/apps/api/test/look.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { lookValues, noiseReduction, toneApplied } from "../src/autopilot/look.js"; +import { cropLongFraction, detailForCrop, lookValues, noiseReduction, toneApplied } from "../src/autopilot/look.js"; describe("autopilot look", () => { it("gives the agency look punchier colour than the natural one, and nothing for none", () => { @@ -22,6 +22,22 @@ describe("autopilot look", () => { expect(toneApplied("light.highlights", -40, 0.75, false)).toBe(-30); }); + it("keeps structure and sharpen in proportion to the frame a crop keeps", () => { + const whole = { x0: 0, y0: 0, x1: 1, y1: 1 }; + const tight = { x0: 0.3, y0: 0.2, x1: 0.7, y1: 0.7 }; + const look = lookValues("agency", 400); + expect(detailForCrop(look, whole, 6000, 4000)["detail.sharpenAmount"]).toBe(40); + expect(detailForCrop(look, null, 6000, 4000)["effects.clarity"]).toBe(8); + const kept = cropLongFraction(tight, 6000, 4000); + expect(kept).toBeCloseTo(0.4); + const scaled = detailForCrop(look, tight, 6000, 4000); + expect(scaled["detail.sharpenAmount"]).toBeCloseTo(16); + expect(scaled["effects.clarity"]).toBeCloseTo(3.2); + expect(scaled["color.vibrance"]).toBe(18); + const close = detailForCrop(look, { x0: 0.4, y0: 0.4, x1: 0.5, y1: 0.5 }, 6000, 4000); + expect(close["detail.sharpenAmount"]).toBeCloseTo(40 / 3, 1); + }); + it("reduces noise more as the ISO climbs", () => { expect(noiseReduction(800)["detail.nrLuminance"]).toBeUndefined(); expect(noiseReduction(3200)["detail.nrLuminance"]!).toBeLessThan(noiseReduction(12800)["detail.nrLuminance"]!); diff --git a/docs/photo-editing-rules.md b/docs/photo-editing-rules.md index e5d656f..284e62f 100644 --- a/docs/photo-editing-rules.md +++ b/docs/photo-editing-rules.md @@ -107,7 +107,9 @@ every photo of a match. They never go over a measured control. - **"natural"**: Getty's more natural colour. - **"none"**: no look. - **Both looks** add capture sharpening (40, radius 1, masking 35), colour noise reduction, and luminance noise - reduction by ISO (from ISO 1600). There is never a vignette or a local change (§1). + reduction by ISO (from ISO 1600). Clarity, texture and sharpening are sized for the whole frame and applied + with the tone, before the crop takes effect: a crop that keeps half the frame keeps half of that strength + (never under a third), so a tight portrait does not grow a halo. There is never a vignette or a local change (§1). Defaults follow the agencies: white balance on (neutral whites) and 75% of the automatic tone (full range, pure blacks). In reportage the measured highlights and whites are pulled in full when they are too bright, and diff --git a/workers/render/src/main.rs b/workers/render/src/main.rs index 68d83bc..fc44b37 100644 --- a/workers/render/src/main.rs +++ b/workers/render/src/main.rs @@ -108,6 +108,24 @@ fn default_quality() -> u8 { 100 } +/// How much of the frame the crop keeps, on its larger side. A whole frame is 1. +fn kept_fraction(settings: &DevelopSettings) -> f64 { + let rect = settings.crop.geometry.rect; + let width = (rect.x1 - rect.x0).clamp(0.0, 1.0); + let height = (rect.y1 - rect.y0).clamp(0.0, 1.0); + width.max(height).clamp(0.05, 1.0) +} + +/// Longest side to decode. The crop only needs enough pixels for the output, not the whole file. +/// `max_edge == 0` stays full size. A little extra covers a straighten. +fn decode_edge(settings: &DevelopSettings, max_edge: u32) -> u32 { + if max_edge == 0 { + return 0; + } + let need = (max_edge as f64 / kept_fraction(settings)).ceil() as u32; + need.saturating_add(need / 8).max(max_edge) +} + fn run(job: &Job) -> Result<(u32, u32), String> { let settings = if job.settings.is_null() { DevelopSettings::default() @@ -115,8 +133,8 @@ fn run(job: &Job) -> Result<(u32, u32), String> { DevelopSettings::from_json(&job.settings).map_err(|e| e.to_string())? }; let bytes = std::fs::read(&job.input).map_err(|e| format!("{}: {e}", job.input))?; - // Decode at full size: the crop is taken from the original, then the result is fitted. - let source = Source::decode(&bytes, 0).map_err(|e| e.to_string())?; + let source = + Source::decode(&bytes, decode_edge(&settings, job.max_edge)).map_err(|e| e.to_string())?; drop(bytes); let edge = if job.max_edge == 0 { u32::MAX @@ -198,3 +216,22 @@ fn main() { let _ = out.flush(); } } + +#[cfg(test)] +mod tests { + use super::{DevelopSettings, decode_edge}; + + #[test] + fn a_tight_crop_decodes_enough_for_the_output() { + let mut settings = DevelopSettings::default(); + settings.crop.geometry.rect.x0 = 0.2; + settings.crop.geometry.rect.x1 = 0.6; + settings.crop.geometry.rect.y0 = 0.1; + settings.crop.geometry.rect.y1 = 0.9; + // The taller side is 0.8 of the frame: 2048 / 0.8 = 2560, plus an eighth. + assert_eq!(decode_edge(&settings, 2048), 2880); + assert_eq!(decode_edge(&settings, 0), 0); + // A whole frame still decodes a little above the output, never the full file. + assert_eq!(decode_edge(&DevelopSettings::default(), 4000), 4500); + } +}