diff --git a/apps/api/src/autopilot/sequence.test.ts b/apps/api/src/autopilot/sequence.test.ts index 3861d73..0da9069 100644 --- a/apps/api/src/autopilot/sequence.test.ts +++ b/apps/api/src/autopilot/sequence.test.ts @@ -61,4 +61,15 @@ describe("sequence choice", () => { const pool = rankForPick(frames, weights, (frame) => frame.score >= 8); expect(pool.map((frame) => frame.id)).toEqual(["b"]); }); + + it("prefers a sharp clear face over an occluded one when the burst has a choice", () => { + const weights = sequenceWeight([ + { facing: 1, eyes: 0.7, faceSharp: true, occluded: true }, + { facing: 1, eyes: 0.7, faceSharp: true, occluded: false }, + ]); + expect(weights[0]!).toBeLessThan(0.1); + expect(weights[1]).toBe(1); + const onlyOccluded = sequenceWeight([{ facing: 1, eyes: null, faceSharp: true, occluded: true }]); + expect(onlyOccluded[0]).toBe(1); + }); }); diff --git a/apps/api/src/autopilot/sequence.ts b/apps/api/src/autopilot/sequence.ts index 6bd0336..67499d8 100644 --- a/apps/api/src/autopilot/sequence.ts +++ b/apps/api/src/autopilot/sequence.ts @@ -47,6 +47,37 @@ function subjectOf(autopilot: unknown): Box | null { return s; } +function ballOf(autopilot: unknown): Box | null { + const b = (autopilot as { ball?: Box } | null)?.ball; + if (!b || typeof b.x0 !== "number" || typeof b.y0 !== "number" || typeof b.x1 !== "number" || typeof b.y1 !== "number") return null; + return b; +} + +function peopleOf(autopilot: unknown): Box[] { + const raw = (autopilot as { peopleBoxes?: Box[] } | null)?.peopleBoxes; + if (!Array.isArray(raw)) return []; + return raw.filter((p) => p && typeof p.x0 === "number" && typeof p.y0 === "number" && typeof p.x1 === "number" && typeof p.y1 === "number"); +} + +/** Face covered by another body or the ball (docs/photo-editing-rules.md §3). */ +function faceOccluded(face: Box, subject: Box | null, people: Box[], ball: Box | null): boolean { + const faceArea = area(face); + if (faceArea <= 0) return false; + if (ball) { + const share = overlap(face, ball) / faceArea; + if (share > 0.18) return true; + } + for (const p of people) { + if (subject && overlap(p, subject) / Math.max(area(subject), 1e-9) > 0.7) continue; + const share = overlap(face, p) / faceArea; + if (share < 0.2) continue; + // Covering the centre of the face, not just brushing the cheek in a duel. + const mid = { x0: face.x0 + 0.25 * (face.x1 - face.x0), y0: face.y0 + 0.25 * (face.y1 - face.y0), x1: face.x1 - 0.25 * (face.x1 - face.x0), y1: face.y1 - 0.25 * (face.y1 - face.y0) }; + if (overlap(mid, p) / Math.max(area(mid), 1e-9) > 0.35) return true; + } + return false; +} + function facingOf(subject: Box | null, faces: FaceBox[], done: boolean): 0 | 1 | null { if (!done) return null; const clear = faces.filter((f) => f.sharpness == null || f.sharpness >= MIN_SHARPNESS); @@ -119,11 +150,21 @@ export async function sequenceWeights(db: Db, photos: readonly LookPhoto[], gapM const own = byPhoto.get(frame.id) ?? []; const subject = subjectOf(frame.autopilot); const facing = facingOf(subject, own, frame.facesStatus === "DONE"); - looks.set(frame.id, { facing, eyes: null }); + const face = faceForEyes(subject, own); + let faceSharp: boolean | null = null; + let occluded: boolean | null = null; + if (facing === 1 && face) { + faceSharp = face.sharpness == null || face.sharpness >= MIN_SHARPNESS; + occluded = faceOccluded(face, subject, peopleOf(frame.autopilot), ballOf(frame.autopilot)); + } else if (facing === 0) { + faceSharp = false; + occluded = null; + } + looks.set(frame.id, { facing, eyes: null, faceSharp, occluded }); if (!preview || facing !== 1) continue; // Reportage: the most closed face in the group. A match: the sharpest face on the subject. - const chosen = reportage ? facesOnSubject(subject, own) : [faceForEyes(subject, own)].filter((f): f is FaceBox => !!f); - for (const face of chosen) jobs.push({ photo: frame, face }); + const chosen = reportage ? facesOnSubject(subject, own) : [face].filter((f): f is FaceBox => !!f); + for (const f of chosen) jobs.push({ photo: frame, face: f }); } } const eyes = new Map(); @@ -142,8 +183,13 @@ export async function sequenceWeights(db: Db, photos: readonly LookPhoto[], gapM for (const burst of groupBursts(frames, gapMs)) { if (burst.length < 2) continue; const rows = burst.map((frame) => { - const look = looks.get(frame.id) ?? { facing: null, eyes: null }; - return { facing: look.facing, eyes: eyes.get(frame.id) ?? null }; + const look = looks.get(frame.id) ?? { facing: null, eyes: null, faceSharp: null, occluded: null }; + return { + facing: look.facing, + eyes: eyes.get(frame.id) ?? null, + faceSharp: look.faceSharp ?? null, + occluded: look.occluded ?? null, + }; }); const weights = sequenceWeight(rows, reportage); burst.forEach((frame, i) => out.set(frame.id, weights[i] ?? 1)); diff --git a/apps/api/src/autopilot/sequenceScore.ts b/apps/api/src/autopilot/sequenceScore.ts index 01c842f..4458e35 100644 --- a/apps/api/src/autopilot/sequenceScore.ts +++ b/apps/api/src/autopilot/sequenceScore.ts @@ -1,6 +1,7 @@ /** * Which frame of a sequence to keep when the eyes can be compared (docs/photo-editing-rules.md §3). * Pure: the desktop and the server both call this. Shut eyes lose when the burst has an open pair. + * A sharp clear face beats a soft or occluded one when the burst has a choice. */ export interface SequenceLook { @@ -8,6 +9,10 @@ export interface SequenceLook { facing: 0 | 1 | null; /** Higher means the eyes look more open. null: not measured. */ eyes: number | null; + /** Face on the subject is sharp enough. null: unknown. */ + faceSharp?: boolean | null; + /** Face covered by another body or the ball. null: unknown. */ + occluded?: boolean | null; } /** Below this, eyes count as shut when another frame in the burst is clearly more open. */ @@ -24,11 +29,16 @@ export function sequenceWeight(frames: readonly SequenceLook[], reportage = fals const known = frames.map((f) => f.eyes).filter((v): v is number => v !== null); const best = known.length ? Math.max(...known) : 0; const hasOpen = known.some((v) => v >= EYES_OPEN); + const hasClearSharp = frames.some((f) => f.facing === 1 && f.faceSharp === true && f.occluded !== true); // A blink loses hard whenever the burst has a clearer open-eye frame. Match and reportage both refuse it. const shut = reportage ? 0.05 : 0.08; return frames.map((f) => { let w = 1; if (front && f.facing === 0) w *= 0.05; + if (hasClearSharp && f.facing === 1) { + if (f.occluded === true) w *= shut; + else if (f.faceSharp === false) w *= 0.2; + } if (f.eyes === null || !known.length) return w; const gap = best - f.eyes; const clearlyShut = hasOpen && f.eyes < EYES_SHUT && gap >= EYES_GAP; diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index 97eb67d..90be1a8 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -61,6 +61,10 @@ export interface AutopilotRecord { picked?: boolean; /** People in the subject (a duel, a celebration). */ people?: number; + /** Detection boxes for occlusion checks in a burst (not only the subject count). */ + peopleBoxes?: Box[]; + /** Ball in play, when the frame is about one. */ + ball?: Box | null; /** "reportage" keeps a whole person; "sport" is a ball in play. */ context?: "sport" | "reportage"; /** Laplacian variance of the subject, for telling a sharp sequence from a blurred one. */ @@ -151,6 +155,7 @@ export class AutopilotService { values = measuredValues(auto.values, settings, photo.iso, style?.offsets ?? {}); } // The sensor's roll beats the lines in the picture (a brick wall is not a horizon). + // Prefer LevelInfo on the preview, then the original (R1 often keeps roll on the CR3), then EXIF JSON. let cameraAngle: number | null = null; if (settings.level) { try { @@ -158,6 +163,20 @@ export class AutopilotService { } catch { cameraAngle = null; } + if (cameraAngle === null && photo.originalStored) { + const original = storage.resolve(photo.storageKey); + if (existsSync(original)) { + try { + cameraAngle = cameraLevelAngle(readFileSync(original)); + } catch { + cameraAngle = null; + } + } + } + if (cameraAngle === null) { + const fromExif = rollAngleFromExif(photo.exif); + if (fromExif !== null) cameraAngle = fromExif; + } } const angle = cameraAngle !== null ? levelAngle(cameraAngle, true) : levelAngle(rawAngle, settings.level); const load = this.deps.detector(); @@ -172,6 +191,13 @@ export class AutopilotService { x1: f.x1, y1: f.y1, })); + let edgeClutter: ((rect: Box) => number) | undefined; + try { + const { edgeClutterOf } = await import("../composition/edgeClutter.js"); + edgeClutter = await edgeClutterOf(preview, { x0: 0, y0: 0, x1: 1, y1: 1 }); + } catch { + edgeClutter = undefined; + } const planned = planFrame({ detections, width: W, @@ -185,6 +211,7 @@ export class AutopilotService { cropBias: style?.cropBias ?? null, sport: photo.event?.sport ?? null, lens: lensHintFromExif(photo.exif, photo.focalLength, photo.lens), + edgeClutter, settings, }); const ops = planned.ops; @@ -198,6 +225,8 @@ export class AutopilotService { const record: AutopilotRecord = { score: detections ? frameScore(detections, composition) : 0, people: detections && composition ? peopleIn(detections, composition.subject) : 0, + peopleBoxes: detections?.people.map((p) => ({ x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y1 })) ?? [], + ball: composition?.ball ?? null, reason: composition?.reason ?? null, subject: composition?.subject ?? null, crop, @@ -597,6 +626,15 @@ function photoAspect(width: number | null | undefined, height: number | null | u return [3, 2]; } +/** Canon RollAngle from ingest EXIF JSON (degrees). Sign matches crop straighten (cancels clockwise roll). */ +export function rollAngleFromExif(exif: unknown): number | null { + if (!exif || typeof exif !== "object") return null; + const raw = (exif as { rollAngle?: unknown }).rollAngle; + if (typeof raw !== "number" || !Number.isFinite(raw)) return null; + if (Math.abs(raw) > 8) return null; + return Math.round(-raw * 100) / 100; +} + /** 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 }[] = []; diff --git a/apps/api/src/composition/cameraLevel.ts b/apps/api/src/composition/cameraLevel.ts index ceccb1c..ed89f85 100644 --- a/apps/api/src/composition/cameraLevel.ts +++ b/apps/api/src/composition/cameraLevel.ts @@ -2,8 +2,9 @@ * The camera's own level, when the file still has it. * Some Canon bodies (EOS R5 from firmware 1.5, and others) write LevelInfo in the maker note: * roll and pitch from the sensor, the same numbers as the electronic level in the viewfinder. - * The maker note sits in the Exif IFD, not in IFD0. The EOS R1 JPEG does not write this tag, - * and Nikon keeps its roll inside an encrypted block, so those stay with the line-based level. + * The maker note sits in the Exif IFD, not in IFD0. The EOS R1 JPEG often omits this tag; the + * autopilot then tries the original CR3 and ingest `rollAngle` EXIF before the line-based level. + * Nikon keeps its roll inside an encrypted block, so those stay with the line-based level. * * The returned number is the crop angle (LightCraft's sign): it cancels a clockwise roll. * 0 means the camera was level. Null means the file has no usable roll. diff --git a/apps/api/src/composition/compose.ts b/apps/api/src/composition/compose.ts index ecec929..aaa3bd9 100644 --- a/apps/api/src/composition/compose.ts +++ b/apps/api/src/composition/compose.ts @@ -98,6 +98,14 @@ export const TUNING = { wJoint: 0.8, /** A hand or a foot of someone who is not the subject, left in the frame. */ wStray: 4, + /** Horizontal lead room: how hard to pull the subject off-centre toward their back. */ + wLead: 1.4, + /** Where the subject sits in the crop when facing right (more space on the right). */ + leadRight: 0.38, + /** Where the subject sits in the crop when facing left. */ + leadLeft: 0.62, + /** Bright / ad clutter on a crop edge relative to the interior. */ + wEdgeClutter: 2.2, }; /** @@ -173,6 +181,11 @@ export interface ComposeOptions { * A zoom, or an unknown lens, does not: the photographer could have zoomed, so the space is the picture. */ lens?: LensHint | null; + /** + * How much brighter/more saturated a crop's edge bands are than its interior (0 = clean). + * Used to prefer a cleaner frame without changing the photograph's aspect. + */ + edgeClutter?: (rect: Box) => number; } /** What the file says about the lens. `range` equal at both ends is a prime. */ @@ -216,6 +229,57 @@ export function isLongPrime(lens: LensHint | null | undefined): boolean { return false; } +/** + * A zoom parked at (or very near) its wide end: the photographer chose the wide plan on purpose + * (e.g. 15–35 at 15). Aggressive sports reframe is wrong — typically only straighten. + */ +export function isWideZoomOpen(lens: LensHint | null | undefined): boolean { + if (!lens) return false; + const focal = lens.focalLength; + if (focal == null || !Number.isFinite(focal)) return false; + const range = lens.range; + if (range && range[0] > 0 && range[1] > range[0] + 1) { + const span = range[1] - range[0]; + const nearWide = focal <= range[0] + Math.max(2, 0.08 * span); + return nearWide; + } + const name = lens.name ?? ""; + const m = name.match(/(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)/); + if (!m) return false; + const lo = Number(m[1]); + const hi = Number(m[2]); + if (!(hi > lo + 1)) return false; + return focal <= lo + Math.max(2, 0.08 * (hi - lo)); +} + +/** + * Horizontal facing for lead room: -1 left, +1 right, 0 unknown. + * Face offset on the body wins; otherwise the ball side relative to the subject. + */ +export function facingSide(subject: Box, faces: readonly Box[], ball: Box | null | undefined): -1 | 0 | 1 { + const head = { x0: subject.x0, y0: subject.y0, x1: subject.x1, y1: subject.y0 + 0.5 * (subject.y1 - subject.y0) }; + let best: Box | null = null; + let bestO = 0; + for (const f of faces) { + const o = overlap(f, head) / Math.max(area(f), 1e-9); + if (o > 0.2 && o > bestO) { + best = f; + bestO = o; + } + } + if (best) { + const bias = cx(best) - cx(subject); + if (bias > 0.03) return 1; + if (bias < -0.03) return -1; + } + if (ball) { + const bias = cx(ball) - cx(subject); + if (bias > 0.04) return 1; + if (bias < -0.04) return -1; + } + return 0; +} + /** A generic event: no opponent and no fixture. The crop is a person, not a match. */ export function isReportage(event: { away?: string | null; fixtureId?: string | null } | null): boolean { if (!event) return false; @@ -427,9 +491,17 @@ export function findSubject( return held(a) - held(b) || dist(a) - dist(b); })[0]; if (ball) { - // Everyone big and close to the ball is in the duel, in focus or not (the goalkeeper facing the shot). - // Not someone the frame has already cut in half: they are background, and the crop leaves them out. - const contest = people.filter((p) => p === main || (!cutOff(p) && h(p) >= 0.6 * h(main) && Math.abs(cx(p) - cx(ball)) <= 0.9 * h(main) && overlap(p, { x0: 0, y0: 0, x1: 1, y1: 1 }) > 0.7 * area(p))); + // Sharp people big and close to the ball are in the duel. Soft / OOF bodies near the ball are scenery — + // they must not expand the subject box (docs/photo-editing-rules.md). + const contest = people.filter( + (p) => + p === main || + (!cutOff(p) && + sharp(p) >= withMain * sharp(main) && + h(p) >= 0.6 * h(main) && + Math.abs(cx(p) - cx(ball)) <= 0.9 * h(main) && + overlap(p, { x0: 0, y0: 0, x1: 1, y1: 1 }) > 0.7 * area(p)), + ); if (!contest.includes(main)) contest.push(main); const box = contest.reduce((u, p) => union(u, p), { x0: ball.x0, y0: ball.y0, x1: ball.x1, y1: ball.y1 }); return { box, reason: "ball", people: contest, ball }; @@ -490,7 +562,11 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo // A long prime is the exception on one full-length: the lens could not zoom, so one step closer is allowed. const primeFigure = reportage && isLongPrime(opts.lens) && shotIntent(inSubject) === "figure"; if (reportage && framedOnPurpose(inSubject, others) && !primeFigure) return null; + // Zoom at the wide end: the photographer opened on purpose — do not reframe (level only later). + if (isWideZoomOpen(opts.lens)) return null; const headroom = 0.04 * tallest; + const lead = reportage ? 0 : facingSide(s, faces, ball ?? null); + const edgeClutter = opts.edgeClutter; const minWidth = opts.minWidth ?? 0; const balls = d.balls.filter((b) => b.score >= MIN_BALL); const feetIn = s.y1 < FEET_IN_FRAME; @@ -503,8 +579,8 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo if (open) { const bottom = Math.min(1, feetIn ? sole : s.y1); return finish( - frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, false, false, true, balls) ?? - frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, true, balls), + frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, false, false, true, balls, false, 0, edgeClutter) ?? + frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, true, balls, false, 0, edgeClutter), ); } // A person, not a ball: reportage, or a match photo where nobody is playing the ball. The sports cut stays @@ -515,27 +591,27 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo if (feetIn) { // Headroom gives way before a complete foot does. If the players do not fit in a tighter frame, the // photograph stays: cutting the legs is not the way out. - const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, true, false, false, balls) - ?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls) - ?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls); + const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter) + ?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter) + ?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter); return finish(whole); } // The foot already leaves the photo: end mid-shin or mid-thigh, not on the sock. - const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, true, false, ball, balls); + const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, true, false, ball, balls, lead, edgeClutter); if (cut) return finish(cut); return null; } // The foot already leaves the photo. Stopping on the sock is the same as cutting the ankle. if (!feetIn) { - const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, false, reportage, ball, balls); + const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, false, reportage, ball, balls, lead, edgeClutter); if (cut) return finish(cut); } // Whole bodies, feet included. A little headroom gives way before a complete foot does. - const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure) - ?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure) - ?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure); + const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter) + ?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter) + ?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter); if (whole || feetIn) return finish(whole); - return finish(frame(s, ratio, s.y0 + MID_THIGH * tallest, headroom, tallest, others, inSubject, reason, minWidth, false, true, reportage, balls)); + return finish(frame(s, ratio, s.y0 + MID_THIGH * tallest, headroom, tallest, others, inSubject, reason, minWidth, false, true, reportage, balls, false, lead, edgeClutter)); } /** @@ -543,7 +619,7 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo * so it cannot slide down onto the sock. A ball in the hands stays below the cut. The hip, the knee and the * ankle are never the line. */ -function cutAboveTheAnkle(s: Box, ratio: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight: boolean, reportage: boolean, ball?: Box, balls: readonly Box[] = []): (Composition & { cost: number }) | null { +function cutAboveTheAnkle(s: Box, ratio: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight: boolean, reportage: boolean, ball?: Box, balls: readonly Box[] = [], lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number): (Composition & { cost: number }) | null { // The line is on the person. The subject box can start higher, at a ball held overhead, and that must not // pull the cut up onto the hip. const body = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a)); @@ -556,7 +632,7 @@ function cutAboveTheAnkle(s: Box, ratio: number, headroom: number, tallest: numb return !JOINTS.some((j) => Math.abs(at - j) < JOINT_BAND); }); const tries = lines - .map((bottom) => frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, tight, true, reportage, balls)) + .map((bottom) => frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, tight, true, reportage, balls, false, lead, edgeClutter)) .filter((c): c is Composition & { cost: number } => !!c); return tries.reduce<(Composition & { cost: number }) | null>((a, b) => (!a || b.cost < a.cost ? b : a), null); } @@ -573,7 +649,7 @@ export function minCropWidth(width: number, height: number, minLongEdge = 2400): return Math.min(1, Math.max(floor, minLongEdge / long) * (width >= height ? 1 : height / width)); } -function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false, pinBottom = false, reportage = false, balls: readonly Box[] = [], closer = false): (Composition & { cost: number }) | null { +function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false, pinBottom = false, reportage = false, balls: readonly Box[] = [], closer = false, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number): (Composition & { cost: number }) | null { const mainSharp = Math.max(...inSubject.map(sharp)); const keep = requiredBox(s, inSubject); let best: { rect: Box; cost: number } | null = null; @@ -609,12 +685,14 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall // Reportage: a person who is in the crop is in whole. A plan may end at the waist; it may not take the head // off, and it may not cut someone down the side. The primary crop keeps their feet too. if (reportage && slicesOther(r, others, mainSharp, tallest, pinBottom)) continue; - if (reportage && overlapsStray(r, others, tallest)) continue; + // Soft scraps and stray limbs: out of the crop in sport and reportage when possible. + if (overlapsStray(r, others, tallest)) continue; + if (overlapsSoftScrap(r, others, mainSharp, tallest)) continue; if (reportage && overlapsEdgeCut(r, others, tallest)) continue; // A player the photographer left in the picture stays in it. Cutting them out, or through the body, - // is not a crop. A sliver, a blurred figure and someone the frame already cut off may still go. + // is not a crop. Soft scenery may still go. if (dropsPlayer(r, others, mainSharp, tallest)) continue; - const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight, reportage, closer) + jointCost(r, inSubject, others, mainSharp); + const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight, reportage, closer, lead, edgeClutter) + jointCost(r, inSubject, others, mainSharp); if (!best || c < best.cost) best = { rect: r, cost: c }; } } @@ -623,20 +701,24 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall return { rect: best.rect, subject: s, reason, people: inSubject.length, cost: best.cost }; } -function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[], tight = false, trustFrame = false, closer = false): number { +function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[], tight = false, trustFrame = false, closer = false, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number): number { let c = 0; - // Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter. + // Sharp people cut in half by the crop's edge look wrong. Soft scraps still cost when they sit in the frame. for (const p of others) { const f = overlap(r, p) / Math.max(area(p), 1e-9); // Only a hand or a foot of someone who is not being photographed: leave it out. A whole other person stays // on the rule below (in, or out, never sliced). - if (strayLimb(p, tallest)) { + if (strayLimb(p, tallest) || softScrap(p, mainSharp, tallest)) { if (f > 0.02) c += TUNING.wStray * f; continue; } if (f <= 0.03 || f >= 0.95) continue; const focus = Math.min(1, sharp(p) / Math.max(mainSharp, 1e-6)); - if (focus < TUNING.inFocus) continue; + if (focus < TUNING.inFocus) { + // Soft body left partly in: dirty frame — prefer the crop that puts them out. + c += TUNING.wStray * 0.6 * Math.min(f, 1 - f); + continue; + } const size = Math.min(1, h(p) / tallest); c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f)); } @@ -662,8 +744,14 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, // The subject fills a good part of the height (people tall in the frame). c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch); } - // Centred across. - c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r)); + // Lead room when facing is known; otherwise centre. + let anchor = 0.5; + if (lead > 0) anchor = TUNING.leadRight; + else if (lead < 0) anchor = TUNING.leadLeft; + const subjectAt = (cx(s) - r.x0) / Math.max(w(r), 1e-6); + if (lead) c += TUNING.wLead * Math.abs(subjectAt - anchor); + else c += TUNING.wCentre * Math.abs(subjectAt - 0.5); + if (edgeClutter) c += TUNING.wEdgeClutter * edgeClutter(r); // Heads a little below the top: not touching it, not floating in empty space. const head = (s.y0 - r.y0) / ch; c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - (tight ? TIGHT.headMax : TUNING.headMax))); @@ -821,15 +909,34 @@ function strayLimb(p: Detection, tallest: number): boolean { return p.x0 < 0.02 || p.x1 > 0.98 || p.y0 < 0.02 || p.y1 > 0.98; } +/** Soft / tiny non-subject: scenery that should leave the crop when possible. */ +function softScrap(p: Detection, mainSharp: number, tallest: number): boolean { + if (strayLimb(p, tallest) || sliver(p)) return true; + if (h(p) < 0.28 * tallest) return true; + if (sharp(p) < TUNING.inFocus * Math.max(mainSharp, 1e-6)) return true; + return false; +} + function overlapsStray(r: Box, others: Detection[], tallest: number): boolean { for (const p of others) { - if (!strayLimb(p, tallest)) continue; + if (!strayLimb(p, tallest) && !sliver(p)) continue; const share = overlap(r, p) / Math.max(area(p), 1e-9); if (share > 0.02) return true; } return false; } +/** Soft or tiny body left only partly in the crop — prefer the tighter clean frame. */ +function overlapsSoftScrap(r: Box, others: Detection[], mainSharp: number, tallest: number): boolean { + for (const p of others) { + if (!softScrap(p, mainSharp, tallest)) continue; + if (strayLimb(p, tallest) || sliver(p)) continue; + const share = overlap(r, p) / Math.max(area(p), 1e-9); + if (share > 0.04 && share < 0.85) return true; + } + return false; +} + function overlapsEdgeCut(r: Box, others: Detection[], tallest: number): boolean { for (const p of others) { if (!edgeAccident(p, tallest)) continue; @@ -877,7 +984,7 @@ export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: numbe const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); const others = detected.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p)); const balls = d.balls.filter((b) => b.score >= MIN_BALL); - const made = frame(s, ratio, bottom, 0.04 * tallest, tallest, others, inSubject, reason, opts.minWidth ?? 0, true, true, reportage, balls); + const made = frame(s, ratio, bottom, 0.04 * tallest, tallest, others, inSubject, reason, opts.minWidth ?? 0, true, true, reportage, balls, false, 0, opts.edgeClutter); if (!made) return null; if (made.rect.y1 > bottom + 0.025) return null; return made.rect; @@ -913,5 +1020,13 @@ export function frameScore(d: Detections, c: Composition | null): number { const subject = d.people.filter((p) => p.x0 >= c.subject.x0 - 1e-9 && p.x1 <= c.subject.x1 + 1e-9 && p.y0 >= c.subject.y0 - 1e-9 && p.y1 <= c.subject.y1 + 1e-9); const focus = Math.max(0, ...subject.map((p) => p.focus ?? 0)); const tallest = Math.max(0, ...subject.map(h)); - return Math.log10(1 + focus) * (0.6 + Math.min(1, tallest / 0.5)) * (c.reason === "ball" ? 1.15 : 1); + let peak = 1; + if (c.reason === "ball" && c.ball && subject.length) { + // Closer ball-to-body = peak contact; approach / follow-through lose. + const body = subject.reduce((a, b) => (h(b) > h(a) ? b : a)); + const dist = Math.hypot(cx(c.ball) - cx(body), cy(c.ball) - cy(body)) / Math.max(h(body), 1e-6); + const touch = overlap(c.ball, body) > 0; + peak = touch ? 1.35 : Math.max(0.75, 1.25 - dist); + } + return Math.log10(1 + focus) * (0.6 + Math.min(1, tallest / 0.5)) * (c.reason === "ball" ? 1.15 : 1) * peak; } diff --git a/apps/api/src/composition/edgeClutter.ts b/apps/api/src/composition/edgeClutter.ts new file mode 100644 index 0000000..cdcf925 --- /dev/null +++ b/apps/api/src/composition/edgeClutter.ts @@ -0,0 +1,51 @@ +import sharp from "sharp"; +import type { Box } from "./compose.js"; + +/** + * How much brighter a crop's edge bands are than its interior (ads, boards, blown highlights). + * 0 = clean; higher = prefer another crop. Best-effort sample of the upright preview. + */ +export async function edgeClutterOf(file: string, rect: Box): Promise<(r: Box) => number> { + const img = sharp(file).rotate().resize(128, 128, { fit: "fill" }).removeAlpha().raw(); + const { data, info } = await img.toBuffer({ resolveWithObject: true }); + const w = info.width; + const h = info.height; + const ch = info.channels; + const lum = (x: number, y: number): number => { + const i = (Math.min(h - 1, Math.max(0, y)) * w + Math.min(w - 1, Math.max(0, x))) * ch; + return (data[i]! + data[i + 1]! + data[i + 2]!) / 3; + }; + const mean = (x0: number, y0: number, x1: number, y1: number): number => { + const xa = Math.floor(x0 * w); + const ya = Math.floor(y0 * h); + const xb = Math.max(xa + 1, Math.ceil(x1 * w)); + const yb = Math.max(ya + 1, Math.ceil(y1 * h)); + let sum = 0; + let n = 0; + for (let y = ya; y < yb; y++) { + for (let x = xa; x < xb; x++) { + sum += lum(x, y); + n += 1; + } + } + return n ? sum / n : 0; + }; + // Capture a baseline for the whole photo so the returned function is sync and cheap. + void rect; + return (r: Box): number => { + const band = 0.08 * Math.min(r.x1 - r.x0, r.y1 - r.y0); + if (band <= 0.01) return 0; + const inner = mean(r.x0 + band, r.y0 + band, r.x1 - band, r.y1 - band); + if (inner < 1) return 0; + const edges = [ + mean(r.x0, r.y0, r.x1, r.y0 + band), + mean(r.x0, r.y1 - band, r.x1, r.y1), + mean(r.x0, r.y0, r.x0 + band, r.y1), + mean(r.x1 - band, r.y0, r.x1, r.y1), + ]; + const hot = Math.max(...edges); + const ratio = hot / inner; + if (ratio < 1.25) return 0; + return Math.min(2, (ratio - 1.25) * 2); + }; +} diff --git a/apps/api/src/composition/planFrame.test.ts b/apps/api/src/composition/planFrame.test.ts index bbb2502..b7bb210 100644 --- a/apps/api/src/composition/planFrame.test.ts +++ b/apps/api/src/composition/planFrame.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { keepPhotoAspect } from "./geometry.js"; -import { planFrame, type PlanSettings } from "./planFrame.js"; +import { levelWithoutChopping, planFrame, type PlanSettings } from "./planFrame.js"; const settings: PlanSettings = { crop: true, @@ -107,4 +107,35 @@ describe("planFrame", () => { }); expect(planned.ops.some((op) => op.command === "crop.set")).toBe(false); }); + + it("reduces the straighten angle when leveling would chop the subject's feet", () => { + // Subject nearly fills the frame — rotating then re-fitting about centre + // shrinks past the feet unless we drop the angle. + const subject = { x0: 0.05, y0: 0.02, x1: 0.95, y1: 0.98 }; + const rect = { x0: 0, y0: 0, x1: 1, y1: 1 }; + const out = levelWithoutChopping(rect, subject, 8, 6000, 4000); + expect(Math.abs(out.angle)).toBeLessThan(8); + expect(out.rect.y1).toBeGreaterThanOrEqual(subject.y1 - 0.03); + expect(out.rect.y0).toBeLessThanOrEqual(subject.y0 + 0.03); + }); + + it("does not reframe when the zoom is at its wide end", () => { + const planned = planFrame({ + detections: { + width: 6000, + height: 4000, + people: [{ x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.92, score: 0.9, sharpness: 1 }], + balls: [{ x0: 0.5, y0: 0.7, x1: 0.54, y1: 0.75, score: 0.9 }], + }, + width: 6000, + height: 4000, + reportage: false, + values: null, + angle: 0, + lens: { focalLength: 15, range: [15, 35], name: "RF15-35mm F2.8 L IS USM" }, + settings, + }); + expect(planned.composition).toBeNull(); + expect(planned.ops.some((op) => op.command === "crop.set")).toBe(false); + }); }); diff --git a/apps/api/src/composition/planFrame.ts b/apps/api/src/composition/planFrame.ts index dd46021..10ef079 100644 --- a/apps/api/src/composition/planFrame.ts +++ b/apps/api/src/composition/planFrame.ts @@ -37,6 +37,20 @@ function chopsKeptPlayer(original: Box, placed: Box, subject: Box): boolean { return false; } +/** + * Apply straighten while keeping the photograph's aspect. If the rotated crop would chop a head, foot or + * side the unrotated crop had kept, reduce the angle (half → quarter → zero). Subject intact beats a level horizon. + */ +export function levelWithoutChopping(rect: Box, subject: Box, angle: number, w: number, h: number): { rect: Box; angle: number } { + if (!angle) return { rect, angle: 0 }; + const tries = [angle, angle / 2, angle / 4, 0]; + for (const tryAngle of tries) { + const shaped = constrainRotated(rect, tryAngle, w, h); + if (!chopsKeptPlayer(rect, shaped, subject)) return { rect: shaped, angle: tryAngle }; + } + return { rect, angle: 0 }; +} + export interface PlanSettings { crop: boolean; tone: boolean; @@ -108,6 +122,8 @@ export function planFrame(input: { sport?: string | null; /** Prime versus zoom. A long prime may step closer on one full-length; the framing still names the shot. */ lens?: LensHint | null; + /** Bright edge clutter score for a crop candidate (same aspect). */ + edgeClutter?: (rect: Box) => number; settings: PlanSettings; }): PlannedFrame { const { detections, settings, width: W, height: H, reportage } = input; @@ -119,9 +135,10 @@ export function planFrame(input: { const focus = input.focus ?? null; const sport = input.sport ?? null; const lens = input.lens ?? null; - const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context, faces, sport, lens }) : null; - const wideComposition = detections && !reportage && settings.framing === "tight" ? compose(detections, aspect, { minWidth, focus, framing: "full", context: "sport", sport }) : null; - const plans = reportage && detections ? { half: planCrop(detections, "half", aspect, { minWidth, focus, context, faces }), threeQuarter: planCrop(detections, "threeQuarter", aspect, { minWidth, focus, context, faces }) } : null; + const edgeClutter = input.edgeClutter; + const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context, faces, sport, lens, edgeClutter }) : null; + const wideComposition = detections && !reportage && settings.framing === "tight" ? compose(detections, aspect, { minWidth, focus, framing: "full", context: "sport", sport, edgeClutter }) : null; + const plans = reportage && detections ? { half: planCrop(detections, "half", aspect, { minWidth, focus, context, faces, edgeClutter }), threeQuarter: planCrop(detections, "threeQuarter", aspect, { minWidth, focus, context, faces, edgeClutter }) } : null; let crop: Box | null = null; let angle = input.angle; if (settings.crop && composition) { @@ -154,13 +171,26 @@ export function planFrame(input: { // A learnt crop must not slice a ball the frame had kept whole, or leave that ball outside. const balls = detections?.balls ?? []; if (clipsBall(rect, balls) || losesBall(rect, composition.ball)) rect = composition.rect; - let shaped: Box | null = constrainRotated(keepPhotoAspect(rect), angle, W, H); - if (losesBall(shaped, composition.ball)) shaped = constrainRotated(keepPhotoAspect(composition.rect), angle, W, H); + const base = keepPhotoAspect(rect); + const leveled = levelWithoutChopping(base, composition.subject, angle, W, H); + angle = leveled.angle; + let shaped: Box | null = leveled.rect; + if (losesBall(shaped, composition.ball)) { + const again = levelWithoutChopping(keepPhotoAspect(composition.rect), composition.subject, angle, W, H); + angle = again.angle; + shaped = again.rect; + } if (losesBall(shaped, composition.ball)) shaped = null; if (shaped && !clipsBall(shaped, balls) && shaped.x1 - shaped.x0 < KEEP_WHOLE) crop = shaped; } - const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(keepPhotoAspect(wideComposition.rect), angle, W, H) : null; - if (!crop && angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H); + const wideBase = wideComposition ? keepPhotoAspect(wideComposition.rect) : null; + const wideLeveled = wideBase ? levelWithoutChopping(wideBase, wideComposition!.subject, angle, W, H) : null; + const wide = settings.crop && wideLeveled && wideLeveled.rect.x1 - wideLeveled.rect.x0 < KEEP_WHOLE ? wideLeveled.rect : null; + if (!crop && angle) { + const full = levelWithoutChopping({ x0: 0, y0: 0, x1: 1, y1: 1 }, { x0: 0.1, y0: 0.1, x1: 0.9, y1: 0.9 }, angle, W, H); + angle = full.angle; + crop = full.rect; + } const lockedPlans = plans ? { half: plans.half ? keepPhotoAspect(plans.half) : null, diff --git a/apps/api/src/ingest/exif.ts b/apps/api/src/ingest/exif.ts index 9ee9f05..4fe1c18 100644 --- a/apps/api/src/ingest/exif.ts +++ b/apps/api/src/ingest/exif.ts @@ -42,6 +42,11 @@ export type CameraExtra = Pick< focusY0?: number; focusX1?: number; focusY1?: number; + /** + * Canon electronic-level roll in degrees (MakerNotes RollAngle / LevelInfo), clockwise positive as the + * camera wrote it. Used when the JPEG preview has no LevelInfo (common on EOS R1). + */ + rollAngle?: number; }; export interface CameraInfo { @@ -191,6 +196,7 @@ function extraOf(tags: Record): CameraExtra { whiteBalance: wb === undefined ? undefined : wb === 0 ? "Auto" : "Manual", focalLength35: num(tags.FocalLengthIn35mmFormat), lensRange: lensInfo[0] && lensInfo[1] ? [lensInfo[0], lensInfo[1]] : undefined, + rollAngle: num(tags.RollAngle) ?? num(tags.CameraRollAngle) ?? num((tags as { rollAngle?: unknown }).rollAngle), software, // Canon and Nikon write the firmware as the Software ("Firmware Version 1.8.1", "Ver.1.10"). firmware: software && /firmware|^ver\.?\s*\d/i.test(software) ? software.replace(/^firmware\s*version\s*/i, "") : undefined, @@ -236,6 +242,8 @@ export async function readCameraInfo(file: string | Buffer): Promise iptc: false, xmp: true, icc: false, + // Canon LevelInfo / RollAngle for bodies that keep the electronic level in MakerNotes (R1 often only on CR3). + mergeOutput: true, reviveValues: false, translateValues: false, })) as Record | undefined; diff --git a/apps/api/test/compose.test.ts b/apps/api/test/compose.test.ts index a744f62..5ee3023 100644 --- a/apps/api/test/compose.test.ts +++ b/apps/api/test/compose.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { clipsBall, compose, type Detection, findSubject, isHandball, isLongPrime, isReportage, minCropWidth, planCrop, sendBlockedByBall, shotIntent } from "../src/composition/compose.js"; +import { clipsBall, compose, facingSide, findSubject, frameScore, isHandball, isLongPrime, isReportage, isWideZoomOpen, minCropWidth, planCrop, sendBlockedByBall, shotIntent, type Detection } from "../src/composition/compose.js"; const person = (x0: number, y0: number, x1: number, y1: number, score = 0.9): Detection => ({ x0, y0, x1, y1, score }); const inside = (r: { x0: number; y0: number; x1: number; y1: number }, b: { x0: number; y0: number; x1: number; y1: number }) => r.x0 <= b.x0 + 1e-9 && r.y0 <= b.y0 + 1e-9 && r.x1 >= b.x1 - 1e-9 && r.y1 >= b.y1 - 1e-9; @@ -54,10 +54,14 @@ describe("automatic crop", () => { const c = compose({ ...frame, people: [blurred, referee], balls: [] })!; expect(c.reason).toBe("person"); expect(referee).toMatchObject(c.subject); - // About two thirds of the frame, with the referee in the middle. + // About two thirds of the frame; soft foreground is left out when possible, so the crop may sit off-centre. expect(c.rect.x1 - c.rect.x0).toBeGreaterThan(0.55); expect(c.rect.x1 - c.rect.x0).toBeLessThan(0.85); - expect(Math.abs((c.rect.x0 + c.rect.x1) / 2 - 0.5)).toBeLessThan(0.05); + expect(inside(c.rect, referee)).toBe(true); + const softShare = + Math.max(0, Math.min(c.rect.x1, blurred.x1) - Math.max(c.rect.x0, blurred.x0)) * + Math.max(0, Math.min(c.rect.y1, blurred.y1) - Math.max(c.rect.y0, blurred.y0)); + expect(softShare / ((blurred.x1 - blurred.x0) * (blurred.y1 - blurred.y0))).toBeLessThan(0.5); }); it("never crops across a knee or an ankle, and keeps the delivery's resolution", () => { @@ -440,3 +444,51 @@ describe("hands, feet, the ball and an open plan", () => { for (const p of crowd) expect(inside(c.rect, p)).toBe(true); }); }); + +describe("clean framing, lead room, wide zoom, peak contact", () => { + it("does not expand the subject with a soft body near the ball", () => { + const sharp = { ...person(0.4, 0.2, 0.52, 0.85), sharpness: 1 }; + const soft = { ...person(0.2, 0.05, 0.45, 0.95), sharpness: 0.2 }; + const ball = { x0: 0.45, y0: 0.72, x1: 0.5, y1: 0.78, score: 0.9 }; + const s = findSubject({ ...frame, people: [sharp, soft], balls: [ball] }, null, { sport: "futebol" })!; + expect(s.reason).toBe("ball"); + expect(s.people).toEqual([sharp]); + expect(s.box.x0).toBeGreaterThan(soft.x0 + 0.05); + }); + + it("leaves a tiny soft scrap out of a sport crop when a cleaner frame fits", () => { + const main = { ...person(0.4, 0.15, 0.58, 0.9), sharpness: 1 }; + const scrap = { ...person(0.05, 0.7, 0.12, 0.85), sharpness: 0.2 }; + const c = compose({ ...frame, people: [main, scrap], balls: [] }, null, { framing: "full", context: "sport" })!; + const share = Math.max(0, Math.min(c.rect.x1, scrap.x1) - Math.max(c.rect.x0, scrap.x0)) * Math.max(0, Math.min(c.rect.y1, scrap.y1) - Math.max(c.rect.y0, scrap.y0)); + expect(share / ((scrap.x1 - scrap.x0) * (scrap.y1 - scrap.y0))).toBeLessThan(0.05); + }); + + it("puts lead room on the facing side of the subject", () => { + const body = { ...person(0.35, 0.15, 0.55, 0.9), sharpness: 1 }; + const face = { x0: 0.48, y0: 0.16, x1: 0.54, y1: 0.28 }; + expect(facingSide(body, [face], null)).toBe(1); + const c = compose({ ...frame, people: [body], balls: [] }, null, { framing: "full", context: "sport", faces: [face] })!; + const at = ((body.x0 + body.x1) / 2 - c.rect.x0) / (c.rect.x1 - c.rect.x0); + expect(at).toBeLessThan(0.48); + }); + + it("treats a zoom at its wide end as intentional framing", () => { + expect(isWideZoomOpen({ focalLength: 15, range: [15, 35] })).toBe(true); + expect(isWideZoomOpen({ focalLength: 35, range: [15, 35] })).toBe(false); + expect(isWideZoomOpen({ focalLength: 135, range: [70, 200] })).toBe(false); + const main = { ...person(0.4, 0.15, 0.58, 0.9), sharpness: 1 }; + expect(compose({ ...frame, people: [main], balls: [] }, null, { lens: { focalLength: 15, range: [15, 35] } })).toBeNull(); + }); + + it("scores peak ball contact higher than a distant ball", () => { + const body = { ...person(0.4, 0.2, 0.55, 0.85), sharpness: 1, focus: 400 }; + const near = { x0: 0.48, y0: 0.7, x1: 0.52, y1: 0.76, score: 0.9 }; + const far = { x0: 0.75, y0: 0.3, x1: 0.79, y1: 0.36, score: 0.9 }; + const dNear = { ...frame, people: [body], balls: [near] }; + const dFar = { ...frame, people: [body], balls: [far] }; + const cNear = compose(dNear, null, { sport: "futebol" })!; + const cFar = { ...cNear, ball: far, reason: "ball" as const }; + expect(frameScore(dNear, cNear)).toBeGreaterThan(frameScore(dFar, cFar)); + }); +}); diff --git a/apps/api/vitest.unit.config.ts b/apps/api/vitest.unit.config.ts index 49ea637..61f61bf 100644 --- a/apps/api/vitest.unit.config.ts +++ b/apps/api/vitest.unit.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from "vitest/config"; /** Pure tests. The default config migrates a database, which these do not need. */ export default defineConfig({ test: { - include: ["src/**/*.test.ts"], + include: ["src/**/*.test.ts", "test/compose.test.ts"], fileParallelism: false, }, }); diff --git a/docs/photo-editing-rules.md b/docs/photo-editing-rules.md index 53af323..aeedd09 100644 --- a/docs/photo-editing-rules.md +++ b/docs/photo-editing-rules.md @@ -19,12 +19,17 @@ Following the AP and NPPA codes: ## 2. Crop +- **Best effort, original aspect:** every crop rule below is "when possible". The autopilot **never** changes the + photograph's aspect ratio. Lead room, cleaning edges, and tightening stay inside that ratio; if they cannot be + met without another format, keep the best crop in the original aspect (or leave the photo as shot). - **Who:** the subject is the person the camera focused on, when the file has a focus point (EXIF SubjectArea: the autofocus point, shown by Photo Mechanic) **and that person is sharp with a fully visible face**. A soft or - faceless body in the foreground (AF landed on the jump in front) is scenery — never the crop — when a sharp - face sits behind. With no usable point, the subject is the sharp person with a face, not the biggest one. With - a ball in play, the ball and everyone contesting it come along. Without one, the subject and the sharp people - with them (a duel, a celebration, a line-up). Non-person photos (empty pitch, kit detail) are unchanged. + faceless body in the foreground or background (AF landed on the jump in front, or a blur behind) is scenery — + never the crop's subject and never used to expand the framing — when a sharp face sits in focus. With no usable + point, the subject is the sharp person with a face, not the biggest one. With a ball in play, the ball and the + **sharp** people contesting it come along (soft bodies near the ball stay out of the subject box). Without one, + the subject and the sharp people with them (a duel, a celebration, a line-up). Non-person photos (empty pitch, + kit detail) are unchanged. - **Who is not the subject:** they are in whole, or they are out. A player who is large in the frame (close to the camera, or nearly as tall as the subject) is part of the photograph: the crop does not throw them out and does not cut through them. If keeping those players means there is nothing to crop, the photo stays as @@ -36,9 +41,15 @@ Following the AP and NPPA codes: below the knee is on the floor: it does not frame the photo, even when it overlaps the player's legs and sits closer to the middle of the body. Football plays the ball on the ground, so the ball at the feet is the one that stays. A spare ball that nobody is playing never wins, in either sport. -- **Shape:** the autopilot keeps the photograph's own aspect. The crop may move anywhere across the frame, - including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a portrait - crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect. +- **Shape:** the autopilot keeps the photograph's own aspect (non-negotiable). The crop may move anywhere across + the frame, including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a + portrait crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect. +- **Lead room (sport):** leave space in the direction the player looks or runs; put their back nearer the opposite + edge. Dead space behind the facing direction is wrong. Without a reliable facing signal (face on the body, or + the ball in play), keep the subject centred as before. Reportage and open team frames do not force lead room. +- **Wide end of a zoom:** when the file shows a zoom and the focal length is at (or very near) the wide end + (e.g. 15–35 mm at 15 mm), the wide plan is intentional. Do not reframe aggressively — typically only straighten. + A tele zoom (70–200 at 135 mm) may still be cropped; the photographer could have zoomed in. - **Context:** a generic event (no opponent, no fixture) is reportage. A match is sport, and a photo of that match with no ball in play is cropped as a person. Reportage does not use the handball cut. - **Framing** (per event, sport only): @@ -66,10 +77,12 @@ Following the AP and NPPA codes: ground under the sole. Cutting the shoe, the ankle or a hand just to fill the frame is not allowed. When the foot already leaves the photo, the crop ends mid-shin or mid-thigh. It does not stop on the sock. Never at a joint, and never through the ball. -- **Edges:** no slivers of other in-focus people at the crop edge: either in, or out. Blurred foreground and - background people don't count. In reportage this is absolute for anyone still reasonably sharp: the crop - keeps their head, and the primary crop keeps their feet when those feet are in the photo. A half or a - three-quarter may end at the waist, and it still starts above the head. A band through the chest is never a crop. +- **Edges:** no slivers of other people at the crop edge: either in, or out — including soft / out-of-focus + fragments and a finger or tiny body part of another athlete. Prefer a tighter clean frame to leaving that scrap + in. Soft people are scenery to remove when possible, not framing anchors. In reportage this is absolute for + anyone still reasonably sharp: the crop keeps their head, and the primary crop keeps their feet when those feet + are in the photo. A half or a three-quarter may end at the waist, and it still starts above the head. A band + through the chest is never a crop. - **A bust is not the subject.** A head in a window, or a torso the detector stopped at the chest, does not beat a whole figure standing in the same photo. The taller person, closer to the camera, stays in the frame even when someone behind them is a little sharper. @@ -80,8 +93,10 @@ Following the AP and NPPA codes: - **Vertical placement:** the upper body (chest, faces) a little above the middle of the crop, never the knees. Little or no empty pitch or floor under the feet: when the crop is taller than the subject, the spare height goes above them (crowd, stands), not below. -- **Distractions:** prefer the crop that leaves out half-bodies, empty floor and bright clutter at the edges, - as long as nothing that matters goes with them. +- **Distracted:** prefer the crop that leaves out half-bodies, empty floor, advertising boards and bright clutter + at the edges, as long as nothing that matters goes with them (same aspect). A cleaner alternative wins. +- **Level vs subject:** prefer not to straighten (or reduce the angle) if leveling would chop a foot, hand or + head of the subject that the crop had kept. The subject intact beats a perfectly level horizon. - **Resolution:** never crop below what the delivery needs. Default: the crop keeps at least 2400 px on its long edge of the original (configurable per organisation; agencies often ask for more). On a large file the floor is 3000 px, not 35% of the frame (that held a modern body near 4000 px). An export at 4000 px enlarges @@ -97,13 +112,17 @@ A camera at 10–30 frames per second sends several photos of the same moment. - **A burst** is a run of photos from the same camera with less than 1 s between frames (configurable; was 1.5 s). - **Score** of each frame: sharpness of the subject (focus landed on them, no motion blur), subject size, ball in - frame and near the subject, faces visible. Ties go to the earliest frame (usually the peak of the action). + frame and near the subject (peak contact preferred: ball closest to the body), faces visible. Ties go to the + earliest frame (usually the peak of the action). - **Facing and eyes:** inside one burst, a frame of a player from behind loses to a frame where the face is visible, and shut eyes lose to open ones. Open eyes always win when the burst has both — including a shot or a grimace, and including when the blink is sharper: if another frame of the same moment has the eyes open, that one is kept. If every frame is a back, or the eyes cannot be told apart, the sharpest frame stays. A back is not dropped from the match when it is the only picture of that moment. One closed face in a group is enough to lose the frame in reportage. +- **Clear face:** prefer a frame whose subject's face is sharp and unobstructed. When the same burst has one with + a clear focused face, do not pick a frame where an arm, another player or the ball covers that face. Only the + occluded / soft-face frame may stay when it is the only picture of that moment. - **No usable face:** do not pick a frame whose subject has no clear face when the same burst has one that does. A photo that is not of a person (empty pitch, kit detail) is unchanged. - **Keep:** the best 1–2 frames per burst (configurable), flagged as picks. The rest stay unflagged (never @@ -130,12 +149,13 @@ is, in order: as picks; 3. **only the picks** are edited: white balance, tone, level (horizon or verticals, at most a few degrees), crop, and the finishing look. The rest of the sequence stays as shot (and need not be uploaded for that decision). - The level uses the camera's own roll when the file still has it (Canon LevelInfo, the viewfinder level). - A level camera stays level: a brick wall must not tilt the frame. With no roll in the file, the level reads - the advertising boards, stands, posts and railings, never the pitch markings (lines on grass), which - perspective tilts; when those disagree it falls back to a general Level; when nothing agrees the photo is - left as it is. A ball in play stays inside the crop, including one in an outstretched hand. Leaving it - outside is the same as cutting it; + The level prefers the camera's own electronic level (Canon LevelInfo / RollAngle — the viewfinder level, + including when it lives on the original CR3 rather than the JPEG). A level camera stays level: a brick wall + must not tilt the frame. Straightening must not chop a foot, hand or head the crop had kept — reduce or skip + the angle first. With no roll in the file, the level reads the advertising boards, stands, posts and railings, + never the pitch markings (lines on grass), which perspective tilts; when those disagree it falls back to a + general Level; when nothing agrees the photo is left as it is. A ball in play stays inside the crop, including + one in an outstretched hand. Leaving it outside is the same as cutting it; 4. optionally delivered (rendered with the edits, IPTC from the event) to the event's delivery target. When the desktop already edited a pick offline, those edits sync with the photo; the server does not overwrite them. @@ -205,5 +225,7 @@ the best frames left when the windows' shares fall short); without the autopilot - AP and NPPA codes, summarised by the CUNY Newmark J-School: https://photo.journalism.cuny.edu/?p=201 - Cropping at mid-limb, not at joints; keep meaning; avoid clutter: https://www.walsworthyearbooks.com/top-10-essential-rules-for-good-photo-cropping/ - Burst culling criteria (subject sharpness, eyes, ball, peak action, 1–3 per burst): https://filterpixel.com/blog/sports-photography-burst-mode-culling +- Sports composition (lead room, face, fill the frame): https://www.ttlsports.com/composition-techniques-for-sport-photography +- Sports burst culling (occlusion, peak contact, clear face): https://imagen-ai.com/valuable-tips/how-to-do-photo-culling-for-sports-photographers/ - Peter's own Lightroom crops (65 picked photos, handball, October 2026): crops in the photo's aspect, often exactly two thirds of the frame, straightening of 0.5–3.3°.