diff --git a/apps/api/src/autopilot/best.ts b/apps/api/src/autopilot/best.ts index f9d6b6a..a5d4ab0 100644 --- a/apps/api/src/autopilot/best.ts +++ b/apps/api/src/autopilot/best.ts @@ -1,7 +1,7 @@ import type { Db } from "../db.js"; import { bestOf, groupBursts } from "./bursts.js"; import { type Candidate, type WindowDecision, actionScore, curate, matchMinutes } from "./curate.js"; -import { sequenceWeights } from "./sequence.js"; +import { rankForPick, sequenceWeights } from "./sequence.js"; import type { AutopilotRecord } from "./service.js"; interface PhotoRow { @@ -48,7 +48,8 @@ export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided const out: Candidate[] = []; groupBursts(frames, burstGapMs).forEach((burst, i) => { if (onlyDecided && !burst.every((f) => f.rec?.decided)) return; - const [first, second] = bestOf(burst, 2); + const pool = rankForPick(burst, burst.map((f) => f.look ?? 1), () => true); + const [first, second] = bestOf(pool, 2); const best = frame === "second" && second && second.flag !== "REJECT" ? second : first; if (!best) return; const rec = best.rec; @@ -62,6 +63,7 @@ export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided reason: rec?.reason ?? (best.score || marked ? "person" : null), people: rec?.people ?? null, subjectHeight: rec?.subject ? rec.subject.y1 - rec.subject.y0 : null, + subject: rec?.subject ?? null, rating: best.rating, rejected: best.flag === "REJECT", }); diff --git a/apps/api/src/autopilot/bursts.test.ts b/apps/api/src/autopilot/bursts.test.ts index b8018f1..f9bf5c9 100644 --- a/apps/api/src/autopilot/bursts.test.ts +++ b/apps/api/src/autopilot/bursts.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { bestOf } from "./bursts.js"; +import { bestOf, looksDifferent, othersInSequence, SEQUENCE_PICK_GAP_MS, sequenceSendRoom } from "./bursts.js"; describe("bestOf", () => { const f = (id: string, score: number) => ({ id, capturedAt: new Date(score), camera: "R1", score }); @@ -10,3 +10,33 @@ describe("bestOf", () => { expect(bestOf(burst, 2).map((x) => x.id)).toEqual(["middle", "last"]); }); }); + +describe("othersInSequence", () => { + it("counts a chain of frames a second apart and stops at a real gap", () => { + const times = [0, 2_000, 4_000, 6_000, 30_000]; + expect(othersInSequence(times, 8_000, SEQUENCE_PICK_GAP_MS)).toBe(4); + expect(othersInSequence(times, 30_000, SEQUENCE_PICK_GAP_MS)).toBe(0); + }); +}); + +describe("sequenceSendRoom", () => { + const standing = { + subject: { x0: 0.4, y0: 0.2, x1: 0.6, y1: 0.9 }, + people: 1, + reason: "person", + }; + const wide = { + subject: { x0: 0.1, y0: 0.35, x1: 0.9, y1: 0.7 }, + people: 3, + reason: "group", + }; + + it("stops on repeats of the same picture and allows a different one", () => { + expect(looksDifferent(standing, standing)).toBe(false); + expect(looksDifferent(standing, wide)).toBe(true); + expect(sequenceSendRoom(1, [standing], standing)).toBe(0); + expect(sequenceSendRoom(1, [standing], wide)).toBe(1); + expect(sequenceSendRoom(2, [standing], standing)).toBe(1); + expect(sequenceSendRoom(2, [standing, standing, wide, wide], standing)).toBe(0); + }); +}); diff --git a/apps/api/src/autopilot/bursts.ts b/apps/api/src/autopilot/bursts.ts index e9a6255..733b3a1 100644 --- a/apps/api/src/autopilot/bursts.ts +++ b/apps/api/src/autopilot/bursts.ts @@ -54,6 +54,138 @@ export function groupBursts(frames: F[], gapMs: number): F[][] /** A good reportage sequence can yield several plans. More than this of one moment is too many. */ export const REPORTAGE_SEQUENCE_CAP = 3; +/** + * A match gallery keeps at most this many frames of one sequence. The motor-drive gap splits a slow + * sequence (a coach on the touchline, a second between frames) into many bursts; those still count as one. + */ +export const SEQUENCE_PICK_CAP = 2; +/** Frames this close, on the same camera, are still the same sequence. */ +export const SEQUENCE_PICK_GAP_MS = 12_000; + +/** + * How many picks already sit in the sequence that `atMs` belongs to. Times further than `gapMs` from the + * nearest frame of that chain are another moment. + */ +export function othersInSequence(timesMs: readonly number[], atMs: number, gapMs: number): number { + const before: number[] = []; + const after: number[] = []; + for (const t of timesMs) { + if (t < atMs) before.push(t); + else if (t > atMs) after.push(t); + } + before.sort((a, b) => a - b); + after.sort((a, b) => a - b); + let count = 0; + let cursor = atMs; + for (let i = before.length - 1; i >= 0; i -= 1) { + const t = before[i]!; + if (cursor - t > gapMs) break; + count += 1; + cursor = t; + } + cursor = atMs; + for (const t of after) { + if (t - cursor > gapMs) break; + count += 1; + cursor = t; + } + return count; +} + +/** A subject box in frame units (0–1). */ +export interface LookBox { + x0: number; + y0: number; + x1: number; + y1: number; +} + +/** What a frame shows, enough to tell a repeat of the same picture from a different one. */ +export interface FrameLook { + subject: LookBox | null; + people: number | null; + reason: string | null; +} + +/** + * Same moment, different picture: the action changed, a single figure became a group, the framing jumped + * from a close-up to a wide shot, or the subject moved to another part of the frame. + */ +export function looksDifferent(a: FrameLook, b: FrameLook): boolean { + if (a.reason && b.reason && a.reason !== b.reason) return true; + const aPeople = a.people ?? 0; + const bPeople = b.people ?? 0; + if (aPeople >= 2 && bPeople < 2) return true; + if (bPeople >= 2 && aPeople < 2) return true; + if (!a.subject || !b.subject) return false; + const aHeight = a.subject.y1 - a.subject.y0; + const bHeight = b.subject.y1 - b.subject.y0; + if (aHeight > 0 && bHeight > 0) { + const ratio = aHeight > bHeight ? aHeight / bHeight : bHeight / aHeight; + if (ratio >= 1.45) return true; + } + const aCenterX = (a.subject.x0 + a.subject.x1) / 2; + const aCenterY = (a.subject.y0 + a.subject.y1) / 2; + const bCenterX = (b.subject.x0 + b.subject.x1) / 2; + const bCenterY = (b.subject.y0 + b.subject.y1) / 2; + const moved = Math.hypot(aCenterX - bCenterX, aCenterY - bCenterY); + return moved >= 0.22; +} + +/** + * Which sequence `atMs` belongs to. A gap larger than `gapMs` in the frames that were actually shot starts a + * new sequence, so a frame we did not pick still keeps the run together. + */ +export function sequenceIndex(timesMs: readonly number[], atMs: number, gapMs: number): number { + const sorted = [...timesMs].sort((a, b) => a - b); + let index = 0; + let prev = sorted[0]; + if (prev === undefined) return 0; + for (const t of sorted) { + if (t - prev > gapMs) index += 1; + if (t === atMs) return index; + prev = t; + } + return index; +} + +/** Frames of `frames` that belong to the same sequence as `atMs`. */ +export function framesInSequence(frames: readonly T[], atMs: number, gapMs: number): T[] { + const sorted = [...frames].sort((a, b) => a.atMs - b.atMs); + const before = sorted.filter((frame) => frame.atMs < atMs); + const after = sorted.filter((frame) => frame.atMs > atMs); + const out: T[] = []; + let cursor = atMs; + for (let i = before.length - 1; i >= 0; i -= 1) { + const frame = before[i]!; + if (cursor - frame.atMs > gapMs) break; + out.push(frame); + cursor = frame.atMs; + } + cursor = atMs; + for (const frame of after) { + if (frame.atMs - cursor > gapMs) break; + out.push(frame); + cursor = frame.atMs; + } + return out; +} + +/** + * Whether one more frame of this sequence may go to the destination. Repeats of a picture stop at the + * configured number. A frame that looks different may still go, up to four from the whole sequence. + */ +export const SEQUENCE_SEND_MAX = 4; + +export function sequenceSendRoom(configured: number, already: readonly FrameLook[], next: FrameLook): number { + if (configured <= 0) return 0; + const same = already.filter((frame) => !looksDifferent(frame, next)); + if (same.length >= configured) return 0; + const ceiling = Math.max(SEQUENCE_SEND_MAX, configured); + if (already.length >= ceiling) return 0; + return 1; +} + /** * Variance of the Laplacian at 1024 px above this is a sharp frame. A sequence needs three such frames before * it is worth more picks than the event asked for. diff --git a/apps/api/src/autopilot/curate.ts b/apps/api/src/autopilot/curate.ts index 745977d..649f8ae 100644 --- a/apps/api/src/autopilot/curate.ts +++ b/apps/api/src/autopilot/curate.ts @@ -1,10 +1,20 @@ +import { + SEQUENCE_PICK_CAP, + SEQUENCE_PICK_GAP_MS, + sequenceIndex, + sequenceSendRoom, + type FrameLook, +} from "./bursts.js"; + /** * "Only the best" (docs/photo-editing-rules.md §5): for clients that want a short gallery of the match, not every * usable frame. The match is cut into short windows, and each window may add its share of the gallery size, with * the share it did not use carried forward (half-time adds nothing, a busy spell may take a little more). * The asked size is a target: a rich match may pass it by about 15% (never more than 25 frames); a thin one stays under. Within a * window the frames with the most action win: the ball in play, a duel or a celebration, a subject big in the - * frame and sharp; one frame per burst, and not two from the same few seconds. Anything well below the match's + * frame and sharp; one frame per burst, and not two from the same few seconds. A longer sequence (the same + * moment, frames a second apart) sends the configured number when the pictures look the same, and up to four + * when a frame is actually different. Anything well below the match's * typical frame is left out even when the window has room. */ @@ -22,6 +32,8 @@ export interface Candidate { people: number | null; /** Height of the subject (0-1 of the frame). */ subjectHeight: number | null; + /** Subject box, when the analysis stored one. Used to tell a repeat from a different picture. */ + subject?: FrameLook["subject"]; /** The photographer's stars (0-5); a rejected frame is never chosen. */ rating: number; rejected: boolean; @@ -48,6 +60,10 @@ export interface CurateOptions { windowMs?: number; /** Frames this close in time are the same moment. */ minGapMs?: number; + /** Frames this close are one sequence and share `sequenceCap`. */ + sequenceGapMs?: number; + /** How many frames one sequence may contribute. */ + sequenceCap?: number; /** A window is decided once it ended this long ago. */ settleMs?: number; now: number; @@ -82,6 +98,8 @@ export function galleryCeiling(count: number): number { export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean; at?: number }[], opts: CurateOptions): WindowDecision[] { const windowMs = opts.windowMs ?? 5 * 60_000; const minGapMs = opts.minGapMs ?? 5_000; + const sequenceGapMs = opts.sequenceGapMs ?? SEQUENCE_PICK_GAP_MS; + const sequenceCap = opts.sequenceCap ?? SEQUENCE_PICK_CAP; const settleMs = opts.settleMs ?? 60_000; const done = new Map(decided.map((d) => [d.id, d.chosen])); // Choices already made. When each one carries its capture time, it only fills the windows up to its own, @@ -120,7 +138,26 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b const room = Math.max(0, Math.min(target - chosenSoFar, Math.ceil(3 * perWindow), opts.count - chosenSoFar)); const ranked = list.filter((x) => x.s > 0 && x.s >= floor).sort((a, b) => b.s - a.s); const chosen: Candidate[] = []; - const fits = (c: Candidate) => !chosen.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < minGapMs); + const priorLooks = priorChosen.flatMap((d) => + d.at === undefined ? [] : [{ at: d.at, look: { subject: null, people: null, reason: null } }], + ); + const shotAt = [...list.map((x) => x.c.at), ...priorLooks.map((frame) => frame.at)]; + const fits = (c: Candidate) => { + if (chosen.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < minGapMs)) return false; + const key = sequenceIndex(shotAt, c.at, sequenceGapMs); + const near = [ + ...priorLooks.filter((frame) => sequenceIndex(shotAt, frame.at, sequenceGapMs) === key), + ...chosen + .filter((o) => sequenceIndex(shotAt, o.at, sequenceGapMs) === key) + .map((o) => ({ look: { subject: o.subject ?? null, people: o.people, reason: o.reason } })), + ]; + const room = sequenceSendRoom( + sequenceCap, + near.map((frame) => frame.look), + { subject: c.subject ?? null, people: c.people, reason: c.reason }, + ); + return room > 0; + }; for (const { c } of ranked) { if (chosen.length >= room) break; if (!fits(c)) continue; diff --git a/apps/api/src/autopilot/sequence.test.ts b/apps/api/src/autopilot/sequence.test.ts index 5c6101b..3861d73 100644 --- a/apps/api/src/autopilot/sequence.test.ts +++ b/apps/api/src/autopilot/sequence.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { sequenceWeight } from "./sequence.js"; +import { rankForPick, sequenceWeight } from "./sequence.js"; describe("sequence choice", () => { it("prefers a face to a back, and open eyes to shut ones, only when there is a choice", () => { @@ -35,4 +35,30 @@ describe("sequence choice", () => { expect(weights[0]!).toBeLessThan(weights[1]!); expect(weights[0]!).toBeLessThan(weights[2]!); }); + + it("keeps the open eyes even when that frame is the softer one", () => { + const frames = [ + { id: "blink", score: 9 }, + { id: "open", score: 4 }, + ]; + const weights = sequenceWeight([ + { facing: 1, eyes: 0.2 }, + { facing: 1, eyes: 0.8 }, + ]); + const pool = rankForPick(frames, weights, (frame) => frame.score >= 8); + expect(pool.map((frame) => frame.id)).toEqual(["open"]); + }); + + it("keeps the sharpest frame when the eyes cannot be told apart", () => { + const frames = [ + { id: "a", score: 3 }, + { id: "b", score: 9 }, + ]; + const weights = sequenceWeight([ + { facing: 1, eyes: null }, + { facing: 1, eyes: null }, + ]); + const pool = rankForPick(frames, weights, (frame) => frame.score >= 8); + expect(pool.map((frame) => frame.id)).toEqual(["b"]); + }); }); diff --git a/apps/api/src/autopilot/sequence.ts b/apps/api/src/autopilot/sequence.ts index ffb1904..6bd0336 100644 --- a/apps/api/src/autopilot/sequence.ts +++ b/apps/api/src/autopilot/sequence.ts @@ -2,47 +2,10 @@ import { MIN_SHARPNESS } from "../faces/math.js"; import type { Db } from "../db.js"; import { eyeOpennessAt } from "../composition/eyes.js"; import { groupBursts } from "./bursts.js"; +import { sequenceWeight, type SequenceLook } from "./sequenceScore.js"; -/** - * Which frame of a sequence to keep (docs/photo-editing-rules.md §3). A player from behind loses to a frame - * where the face is visible, and shut eyes lose to open ones, when the difference is clear. If every frame is - * a back, or the eyes cannot be told apart, nothing changes. - * - * Open eyes always beat shut ones when both are measured in the same burst — even on a shot or a grimace. - * A clear face always beats a back when the burst has both. - */ -export interface SequenceLook { - /** 1: a face on the subject. 0: the subject was seen and has no face (a back). null: not analysed yet. */ - facing: 0 | 1 | null; - /** Higher means the eyes look more open. null: not measured. */ - eyes: number | null; -} - -/** Below this, eyes count as shut when another frame in the burst is clearly more open. */ -const EYES_SHUT = 0.45; -/** At or above this, eyes count as open enough to prefer over a blink. */ -const EYES_OPEN = 0.55; -/** Minimum gap between best and this frame before a blink penalty applies. */ -const EYES_GAP = 0.08; - -export function sequenceWeight(frames: readonly SequenceLook[], reportage = false): number[] { - const front = frames.some((f) => f.facing === 1); - 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); - // 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 (f.eyes === null || !known.length) return w; - const gap = best - f.eyes; - const clearlyShut = hasOpen && f.eyes < EYES_SHUT && gap >= EYES_GAP; - const relativelyShut = gap >= EYES_GAP && f.eyes < best * 0.85; - if (clearlyShut || relativelyShut) w *= shut; - return w; - }); -} +export { rankForPick, sequenceWeight } from "./sequenceScore.js"; +export type { SequenceLook } from "./sequenceScore.js"; interface Box { x0: number; diff --git a/apps/api/src/autopilot/sequenceScore.ts b/apps/api/src/autopilot/sequenceScore.ts new file mode 100644 index 0000000..01c842f --- /dev/null +++ b/apps/api/src/autopilot/sequenceScore.ts @@ -0,0 +1,57 @@ +/** + * 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. + */ + +export interface SequenceLook { + /** 1: a face on the subject. 0: the subject was seen and has no face (a back). null: not analysed yet. */ + facing: 0 | 1 | null; + /** Higher means the eyes look more open. null: not measured. */ + eyes: number | null; +} + +/** Below this, eyes count as shut when another frame in the burst is clearly more open. */ +const EYES_SHUT = 0.45; +/** At or above this, eyes count as open enough to prefer over a blink. */ +const EYES_OPEN = 0.55; +/** Minimum gap between best and this frame before a blink penalty applies. */ +const EYES_GAP = 0.08; +/** A frame under this is not a pick when the burst still has a frame at or above it. */ +export const LOOK_KEEP = 0.25; + +export function sequenceWeight(frames: readonly SequenceLook[], reportage = false): number[] { + const front = frames.some((f) => f.facing === 1); + 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); + // 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 (f.eyes === null || !known.length) return w; + const gap = best - f.eyes; + const clearlyShut = hasOpen && f.eyes < EYES_SHUT && gap >= EYES_GAP; + const relativelyShut = gap >= EYES_GAP && f.eyes < best * 0.85; + if (clearlyShut || relativelyShut) w *= shut; + return w; + }); +} + +/** + * The frames a sequence may keep. A blink (or a back) drops out whenever another frame of the same burst + * is usable, even if the blink is sharper. Sharpness then ranks what remains. When the eyes were not + * measured, every frame stays and sharpness decides. + */ +export function rankForPick(frames: readonly T[], weights: readonly number[], sharp: (frame: T) => boolean): T[] { + const kept: T[] = []; + for (let i = 0; i < frames.length; i++) { + const weight = weights[i] ?? 1; + if (weight >= LOOK_KEEP) kept.push(frames[i]!); + } + let base = [...frames]; + if (kept.length > 0 && kept.length < frames.length) base = kept; + const sharpOnes = base.filter((frame) => sharp(frame)); + if (sharpOnes.length > 0) return sharpOnes; + return base; +} diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index 3da4dc2..97eb67d 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -1,11 +1,12 @@ -import { existsSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { AutopilotSettings, type EditCommand } from "@photoreport/contracts"; import type { Db } from "../db.js"; import type { DeliveryService } from "../delivery/service.js"; import type { RenderEngine } from "../develop/engine.js"; import type { DevelopService } from "../develop/service.js"; -import { type Box, frameScore, isReportage, peopleIn, sendBlockedByBall } from "../composition/compose.js"; +import { type Box, frameScore, isReportage, lensHintFromExif, peopleIn, sendBlockedByBall } from "../composition/compose.js"; import type { SubjectDetector } from "../composition/detect.js"; +import { cameraLevelAngle } from "../composition/cameraLevel.js"; import { planFrame, levelAngle, measuredValues } from "../composition/planFrame.js"; import { constrainRotated } from "../composition/geometry.js"; import type { IngestLogger } from "../ingest/service.js"; @@ -15,8 +16,16 @@ import type { LocalStorage } from "../storage/storage.js"; import { focusFromExifJson } from "../ingest/focus.js"; import { readFocusPoint } from "../ingest/exif.js"; import { assignBestRestExports, CANDIDATE_SELECT, candidatesOf } from "./best.js"; -import { sequenceWeights } from "./sequence.js"; -import { bestOf, FOCUS_SHARP, groupBursts, reportagePickCount } from "./bursts.js"; +import { rankForPick, sequenceWeights } from "./sequence.js"; +import { + bestOf, + FOCUS_SHARP, + groupBursts, + reportagePickCount, + SEQUENCE_PICK_GAP_MS, + sequenceIndex, + sequenceSendRoom, +} from "./bursts.js"; import { curate, matchMinutes } from "./curate.js"; import { type LearntStyle, learntStyle } from "./learning.js"; import { detailForCrop, lookValues } from "./look.js"; @@ -141,7 +150,16 @@ export class AutopilotService { rawAngle = auto.angle; values = measuredValues(auto.values, settings, photo.iso, style?.offsets ?? {}); } - const angle = levelAngle(rawAngle, settings.level); + // The sensor's roll beats the lines in the picture (a brick wall is not a horizon). + let cameraAngle: number | null = null; + if (settings.level) { + try { + cameraAngle = cameraLevelAngle(readFileSync(preview)); + } catch { + cameraAngle = null; + } + } + const angle = cameraAngle !== null ? levelAngle(cameraAngle, true) : levelAngle(rawAngle, settings.level); const load = this.deps.detector(); const detections = load ? await (await load).detect(preview) : null; const focusFile = photo.originalStored ? storage.resolve(photo.storageKey) : preview; @@ -166,6 +184,7 @@ export class AutopilotService { cropFactor: style?.cropFactor ?? null, cropBias: style?.cropBias ?? null, sport: photo.event?.sport ?? null, + lens: lensHintFromExif(photo.exif, photo.focalLength, photo.lens), settings, }); const ops = planned.ops; @@ -243,15 +262,48 @@ export class AutopilotService { const need = picksNeeded(settings); const asked = reportage ? reportagePickCount(sharp, need) : need; const planKey = [null, "half", "threeQuarter"] as const; - // Drop backs / blinks when the burst has a clearer face with open eyes (look weight already crushed). - // Soft frames lose when the burst has a sharp sibling (FOCUS_SHARP). - const sharpEnough = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP); - const lookOk = (sharpEnough.length ? sharpEnough : burst).filter((f) => (look.get(f.id) ?? 1) >= 0.25); - const usable = lookOk.length ? lookOk : sharpEnough.length ? sharpEnough : burst; - const pool = usable; + // Open eyes win whenever the burst has a frame where they can be seen. A sharper blink does not. + // Among the frames that remain, a sharp one beats a soft one. + const weights = burst.map((f) => look.get(f.id) ?? 1); + const pool = rankForPick(burst, weights, (f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP); // Extra frames beyond the event's number are only kept when they can carry a different plan. // The plan stays with the frame: dropping one does not hand its crop to the next. - const chosen = bestOf(pool, asked) + // The panel number is how many similar pictures of one sequence are chosen. A slow run (a second + // between frames) is still that sequence. A frame that looks different may add another, up to four. + let take = asked; + if (!reportage) { + take = Math.min(asked, Math.max(0, settings.picksPerBurst)); + } + const start = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime())); + const sameCamera = frames + .filter((f) => f.camera === burst[0]!.camera && !burst.some((b) => b.id === f.id)) + .map((f) => ({ + atMs: (f.capturedAt ?? f.createdAt).getTime(), + picked: f.flag === "PICK", + look: { + subject: f.rec?.subject ?? null, + people: f.rec?.people ?? null, + reason: f.rec?.reason ?? null, + }, + })); + const shotAt = [...sameCamera.map((frame) => frame.atMs), start]; + const key = sequenceIndex(shotAt, start, SEQUENCE_PICK_GAP_MS); + const already = sameCamera.filter((frame) => { + if (!frame.picked) return false; + return sequenceIndex(shotAt, frame.atMs, SEQUENCE_PICK_GAP_MS) === key; + }); + if (already.length > 0) { + const next = bestOf(pool, 1)[0]; + const room = next + ? sequenceSendRoom(settings.picksPerBurst, already.map((frame) => frame.look), { + subject: next.rec?.subject ?? null, + people: next.rec?.people ?? null, + reason: next.rec?.reason ?? null, + }) + : 0; + take = Math.min(take, room); + } + const chosen = bestOf(pool, take) .map((f, i) => ({ f, key: planKey[i] ?? null })) .filter(({ f, key }, i) => { if (!reportage || i < need) return true; @@ -263,6 +315,9 @@ export class AutopilotService { if (toFlag.length) { await db.photo.updateMany({ where: { id: { in: toFlag } }, data: { flag: "PICK" } }); broadcaster.library(event.organizationId, { type: "photo.updated", ids: toFlag, patch: { flag: "PICK" } }); + for (const frame of best) { + if (toFlag.includes(frame.id)) frame.flag = "PICK"; + } picked += toFlag.length; } // Apply the planned develop/crop only to the picks — never to the rest of the sequence. @@ -385,6 +440,7 @@ export class AutopilotService { durationMs: matchMinutes(event.sport) * 60_000, now: now.getTime(), minGapMs: MELHORES_GAP_MS, + sequenceCap: settings.picksPerBurst, }; const decisions = curate(candidates, decided, { count: galleries.length ? Math.max(...galleries.map((g) => g.count)) : settings.bestCount, diff --git a/apps/api/src/composition/cameraLevel.test.ts b/apps/api/src/composition/cameraLevel.test.ts new file mode 100644 index 0000000..ca70647 --- /dev/null +++ b/apps/api/src/composition/cameraLevel.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "vitest"; +import { cameraLevelAngle } from "./cameraLevel.js"; + +/** + * A tiny JPEG laid out like a Canon file: IFD0 points at the Exif IFD, and that IFD + * holds the maker note. LevelInfo says the camera rolled clockwise by `clockwise` degrees. + */ +function jpegWithRoll(clockwise: number): ArrayBuffer { + const raw = Math.round(-clockwise * 10); + const tiff = new Uint8Array(94); + const view = new DataView(tiff.buffer); + view.setUint16(0, 0x4949, true); + view.setUint16(2, 42, true); + view.setUint32(4, 8, true); + view.setUint16(8, 1, true); + view.setUint16(10, 0x8769, true); + view.setUint16(12, 4, true); + view.setUint32(14, 1, true); + view.setUint32(18, 26, true); + view.setUint16(26, 1, true); + view.setUint16(28, 0x927c, true); + view.setUint16(30, 7, true); + view.setUint32(32, 50, true); + view.setUint32(36, 44, true); + view.setUint16(44, 1, true); + view.setUint16(46, 0x4059, true); + view.setUint16(48, 7, true); + view.setUint32(50, 32, true); + view.setUint32(54, 62, true); + view.setInt32(62 + 12, raw, true); + view.setInt32(62 + 16, 0, true); + const app = new Uint8Array(2 + 2 + 6 + tiff.length); + const out = new DataView(app.buffer); + out.setUint16(0, 0xffe1); + out.setUint16(2, app.length - 2); + app.set([0x45, 0x78, 0x69, 0x66, 0, 0], 4); + app.set(tiff, 10); + const jpeg = new Uint8Array(2 + app.length + 2); + jpeg[0] = 0xff; + jpeg[1] = 0xd8; + jpeg.set(app, 2); + jpeg[jpeg.length - 2] = 0xff; + jpeg[jpeg.length - 1] = 0xd9; + return jpeg.buffer; +} + +describe("camera level", () => { + it("turns a clockwise Canon roll into the crop angle that cancels it", () => { + expect(cameraLevelAngle(jpegWithRoll(1.5))).toBe(-1.5); + }); + + it("keeps a level camera level, so a wall cannot tilt the frame", () => { + expect(cameraLevelAngle(jpegWithRoll(0))).toBe(0); + }); + + it("ignores a portrait roll and a file with no level", () => { + expect(cameraLevelAngle(jpegWithRoll(90))).toBeNull(); + expect(cameraLevelAngle(new Uint8Array([0xff, 0xd8, 0xff, 0xd9]).buffer)).toBeNull(); + }); +}); diff --git a/apps/api/src/composition/cameraLevel.ts b/apps/api/src/composition/cameraLevel.ts new file mode 100644 index 0000000..ceccb1c --- /dev/null +++ b/apps/api/src/composition/cameraLevel.ts @@ -0,0 +1,106 @@ +/** + * 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 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. + */ + +const MAX_ROLL = 8; + +export function cameraLevelAngle(bytes: ArrayBuffer | ArrayBufferView): number | null { + const view = bytes instanceof ArrayBuffer ? new DataView(bytes) : new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (view.byteLength < 4 || view.getUint16(0) !== 0xffd8) return null; + let off = 2; + while (off + 4 <= view.byteLength) { + const marker = view.getUint16(off); + const size = view.getUint16(off + 2); + if (marker === 0xffe1 && off + 10 <= view.byteLength && view.getUint32(off + 4) === 0x45786966) { + return canonRoll(view, off + 10, off + 2 + size); + } + if ((marker & 0xff00) !== 0xff00 || marker === 0xffda) return null; + off += 2 + size; + } + return null; +} + +function canonRoll(view: DataView, tiff: number, end: number): number | null { + if (tiff + 8 > end) return null; + const little = view.getUint16(tiff) === 0x4949; + const ifd0 = view.getUint32(tiff + 4, little); + const maker = makerNote(view, tiff, end, little, ifd0); + if (!maker) return null; + let note = tiff + maker.offset; + if (note + 8 > end) return null; + const head = String.fromCharCode( + view.getUint8(note), + view.getUint8(note + 1), + view.getUint8(note + 2), + view.getUint8(note + 3), + view.getUint8(note + 4), + ); + if (head === "Canon") note += 8; + const level = entryValue(view, tiff, end, little, note - tiff, 0x4059); + if (!level || level.count < 20) return null; + let blob = tiff + level.offset; + if (blob + 20 > end) blob = note + level.offset; + if (blob + 20 > end) return null; + // Entry 4 is roll, entry 5 is pitch. The table counts from 1. + const rollRaw = view.getInt32(blob + 3 * 4, little); + const pitchRaw = view.getInt32(blob + 4 * 4, little); + const pitch = canonDegrees(pitchRaw, false); + const clockwise = canonDegrees(rollRaw, true); + if (pitch === null || clockwise === null) return null; + if (Math.abs(pitch) > 90) return null; + if (Math.abs(clockwise) > MAX_ROLL) return null; + return Math.round(-clockwise * 100) / 100; +} + +function canonDegrees(raw: number, negate: boolean): number | null { + let v = raw; + if (v > 1800) v -= 3600; + if (v < -1800) v += 3600; + const degrees = (negate ? -v : v) / 10; + if (!Number.isFinite(degrees) || Math.abs(degrees) > 180) return null; + return degrees; +} + +/** MakerNote is usually inside the Exif IFD (tag 0x8769). A few files put it straight on IFD0. */ +function makerNote( + view: DataView, + tiff: number, + end: number, + little: boolean, + ifd0: number, +): { offset: number; count: number } | null { + const direct = entryValue(view, tiff, end, little, ifd0, 0x927c); + if (direct) return direct; + const exif = entryValue(view, tiff, end, little, ifd0, 0x8769); + if (!exif) return null; + return entryValue(view, tiff, end, little, exif.offset, 0x927c); +} + +function entryValue( + view: DataView, + tiff: number, + end: number, + little: boolean, + ifd: number, + tag: number, +): { offset: number; count: number } | null { + if (ifd <= 0 || tiff + ifd + 2 > end) return null; + const n = view.getUint16(tiff + ifd, little); + if (n > 80) return null; + for (let i = 0; i < n; i++) { + const e = ifd + 2 + i * 12; + if (tiff + e + 12 > end) return null; + if (view.getUint16(tiff + e, little) !== tag) continue; + const count = view.getUint32(tiff + e + 4, little); + const value = view.getUint32(tiff + e + 8, little); + return { offset: value, count }; + } + return null; +} diff --git a/apps/api/src/composition/compose.ts b/apps/api/src/composition/compose.ts index 4d1b8cc..ecec929 100644 --- a/apps/api/src/composition/compose.ts +++ b/apps/api/src/composition/compose.ts @@ -14,10 +14,12 @@ * stays whole when that person stays in the crop. A crop that slices a ball is not a crop. * - An open frame with a team in it stays open: the row is the subject, and the crop does not drop people out of it. * - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter. - * - A generic event, and any photo with no ball, is reportage: a whole hand and a whole foot stay in. When the - * foot already leaves the photo, the crop ends mid-shin or mid-thigh, never on the sock. A person the frame - * has already cut in half stays out. A stray hand or foot of someone else is cropped out. A head in a window - * or a torso does not beat a whole figure, and a crop never slices someone who is in it. + * - A generic event is reportage. The crop reads the shot the way a picture editor does, and trusts the + * framing: a long shot is the place, a full-length or a group whose bodies are whole stays as it was made, + * and a frame the camera already closed is only finished (mid-limb, a person already cut off at the edge + * left out). It is not zoomed to a sports fill. The space left around someone was left on purpose. + * A prime of 100mm or longer may step one notch closer on a single full-length, because it cannot zoom. + * A long shot and a group stay. That step stays centred on the photograph. * - "tight" is the agencies' handball look, and only with a ball in play: the subject fills the height, cut * mid-shin or mid-thigh when the foot is already out. "full" keeps whole bodies when they fit. * @@ -126,6 +128,23 @@ const HAND_PAD = 0.12; /** How many similar people, across how much of the frame, make an open plan rather than one player's photo. */ const OPEN_PEOPLE = 4; const OPEN_SPAN = 0.45; +/** + * A person under half the picture is a long shot: the place is what was photographed. + * The same line picture editors draw between a long shot and a full-length. + */ +const LONG_SHOT = 0.5; +/** + * A prime at least this long cannot zoom. On one full-length the crop may come in to PRIME_STEP, + * the zoom the lens could not make. Shorter primes and zooms stay with the frame as shot. + */ +const LONG_PRIME_MM = 100; +/** One step in from the photograph. Not the sports fill: the same picture, a little closer. */ +const PRIME_STEP = 0.85; +/** + * Among reportage crops of the same size, a slight pull toward the subject. + * Smaller than one step of the size search (0.025), so it never closes a frame to centre it. + */ +const FRAME_TIE = 0.02; /** Tight framing: the subject's tallest body about this many crop heights (a little cut at the bottom). */ export const TIGHT = { fillAt: 1.05, wFill: 2.2, chestAt: 0.34, headMax: 0.2 }; @@ -149,6 +168,52 @@ export interface ComposeOptions { * the photo. A sport that plays the ball on the ground (football) keeps the ball at the feet. */ sport?: string | null; + /** + * The lens that made the frame. A long prime may step closer on a single full-length. + * A zoom, or an unknown lens, does not: the photographer could have zoomed, so the space is the picture. + */ + lens?: LensHint | null; +} + +/** What the file says about the lens. `range` equal at both ends is a prime. */ +export interface LensHint { + focalLength?: number | null; + range?: readonly [number, number] | null; + name?: string | null; +} + +/** Focal length, lens name and the EXIF lens range stored on a photo. */ +export function lensHintFromExif(exif: unknown, focalLength: number | null, name: string | null): LensHint { + let range: [number, number] | null = null; + if (exif && typeof exif === "object" && "lensRange" in exif) { + const raw = (exif as { lensRange?: unknown }).lensRange; + if (Array.isArray(raw) && raw.length >= 2) { + const min = raw[0]; + const max = raw[1]; + if (typeof min === "number" && typeof max === "number" && Number.isFinite(min) && Number.isFinite(max)) { + range = [min, max]; + } + } + } + return { focalLength, range, name }; +} + +/** + * A prime of 100mm or more. The photographer could not zoom in. A 70-200 at 135mm is not this: + * that lens still had room. Unknown lens: not this either. + */ +export function isLongPrime(lens: LensHint | null | undefined): boolean { + if (!lens) return false; + const focal = lens.focalLength; + if (focal == null || !Number.isFinite(focal) || focal < LONG_PRIME_MM) return false; + const range = lens.range; + if (range && range[0] > 0 && range[1] > 0) { + return Math.abs(range[0] - range[1]) < 1; + } + const name = lens.name ?? ""; + if (/\d+\s*-\s*\d+/.test(name)) return false; + if (/\d+\s*mm/i.test(name)) return true; + return false; } /** A generic event: no opponent and no fixture. The crop is a person, not a match. */ @@ -179,6 +244,49 @@ const sharp = (p: Detection) => p.sharpness ?? 1; /** A hand at the frame edge, not a person standing in the row. */ const sliver = (p: Detection) => h(p) < 0.12 || (atEdge(p) && w(p) < 0.07); +/** What the photograph already is. The photographer framed it; the size of the person is the plan. */ +export type ShotIntent = "scene" | "figure" | "group" | "closed"; + +/** + * The plan a picture editor would name from the frame alone. + * A long shot is the place. A full-length or a group is finished when the bodies are whole. + * Closed means the camera already cut the body: the feet leave the picture and the person is large. + */ +export function shotIntent(subject: readonly Detection[]): ShotIntent | null { + const usable = subject.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT && !p.fragment && !sliver(p)); + if (usable.length === 0) return null; + const tallestPerson = usable.reduce((a, b) => (h(b) > h(a) ? b : a)); + if (h(tallestPerson) < LONG_SHOT) return "scene"; + const feetCut = usable.some((p) => p.y1 >= FEET_IN_FRAME); + if (feetCut) return "closed"; + if (usable.length >= 2) return "group"; + return "figure"; +} + +/** Someone the camera already left out: cut by the frame edge, and not a stray hand or foot. */ +function edgeAccident(p: Detection, tallest: number): boolean { + if (!atEdge(p)) return false; + if (sliver(p)) return false; + if (strayLimb(p, tallest)) return false; + return true; +} + +/** + * Reportage: the frame is the photograph. True when closing it would throw away a plan the camera finished. + * A person already cut off at the edge of a full-length is the exception: they are not the picture. + */ +function framedOnPurpose(inSubject: Detection[], others: Detection[]): boolean { + const intent = shotIntent(inSubject); + if (!intent) return false; + if (intent === "closed") return false; + if (intent === "scene") return true; + const tallest = Math.max(...inSubject.map(h)); + for (const p of others) { + if (edgeAccident(p, tallest)) return false; + } + return true; +} + /** * The hands of a narrow standing figure sit outside the torso box. A wide box already has the arms in it * (someone leaning), so it is left alone. @@ -308,7 +416,9 @@ export function findSubject( // middle. A sport that plays the ball on the ground keeps the one on the person, then the nearest. const handball = isHandball(opts?.sport); const balls = d.balls.filter((b) => b.score >= MIN_BALL && w(b) < 0.6 * h(main) && w(b) > 0.02 * h(main)); - const near = balls.filter((b) => Math.abs(cx(b) - cx(main)) <= w(main) / 2 + 0.5 * h(main) && cy(b) > main.y0 - 0.4 * h(main) && cy(b) < main.y1 + 0.1 * h(main)); + // An outstretched arm holds the ball well outside the torso box. Half a body is not enough. + const arm = handball ? 0.9 * h(main) : 0.5 * h(main); + const near = balls.filter((b) => Math.abs(cx(b) - cx(main)) <= w(main) / 2 + arm && cy(b) > main.y0 - 0.4 * h(main) && cy(b) < main.y1 + 0.1 * h(main)); const onTheFloor = (x: Box) => (cy(x) - main.y0) / Math.max(h(main), 1e-6) >= 0.74; const playing = handball ? near.filter((b) => !onTheFloor(b)) : near; const ball = playing.sort((a, b) => { @@ -369,12 +479,17 @@ function personAtFocus(people: Detection[], focus: FocusHint): Detection | null export function compose(d: Detections, aspect: number | null = null, opts: ComposeOptions = {}): Composition | null { const reportage = opts.context === "reportage"; const faces = opts.faces ?? []; - const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces }); + const detected = reportage ? forReportage(d, faces) : d; + const found = findSubject(detected, opts.focus, { reportage, sport: opts.sport ?? null, faces }); if (!found) return null; const { box: s, reason, people: inSubject, ball } = found; const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions const tallest = Math.max(...inSubject.map(h)); - const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p)); + const others = detected.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p)); + // A long shot, a full-length, or a group the camera already finished. The margins are the picture. + // 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; const headroom = 0.04 * tallest; const minWidth = opts.minWidth ?? 0; const balls = d.balls.filter((b) => b.score >= MIN_BALL); @@ -398,11 +513,12 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo if (opts.framing === "tight" && !personStory) { // Feet that are whole in the photo stay in. Cutting the leg is not how a tight frame is made. if (feetIn) { - // Headroom gives way before a complete foot does. + // 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); - if (whole) return finish(whole); + 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); @@ -415,9 +531,9 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo 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) - ?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls) - ?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls); + 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); 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)); } @@ -457,7 +573,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[] = []): (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): (Composition & { cost: number }) | null { const mainSharp = Math.max(...inSubject.map(sharp)); const keep = requiredBox(s, inSubject); let best: { rect: Box; cost: number } | null = null; @@ -493,7 +609,12 @@ 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; - const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight) + jointCost(r, inSubject, others, mainSharp); + if (reportage && overlapsStray(r, others, 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. + 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); if (!best || c < best.cost) best = { rect: r, cost: c }; } } @@ -502,7 +623,7 @@ 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): 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): number { let c = 0; // Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter. for (const p of others) { @@ -519,6 +640,18 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, const size = Math.min(1, h(p) / tallest); c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f)); } + if (trustFrame) { + // The photograph as shot. A long prime may take one step in, still centred on the same picture. + const scale = Math.max(ch, w(r) / ratio); + let target = 1; + if (closer) target = PRIME_STEP; + c += Math.abs(scale - target); + let anchor = cx(s); + if (closer) anchor = 0.5; + const offCentre = Math.abs(anchor - cx(r)) / Math.max(w(r), 1e-6); + c += FRAME_TIE * offCentre; + return c; + } if (tight) { // The agencies' framing: the subject as tall as the crop (or a little taller, legs cut mid-limb). c += TIGHT.wFill * Math.abs(tallest / ch - TIGHT.fillAt); @@ -635,6 +768,40 @@ function cutsHead(r: Box, people: Detection[], tallest: number): boolean { * Someone the crop keeps a piece of, but not as a photograph would. In, or out: never a slice through the body, * never the body without the head. A deliberate half or three-quarter (allowLegs) may end at the waist. */ +/** + * A player who is clearly in the photograph: large in the frame, or nearly as tall as the subject. + * Not a distant figure, not a hand at the edge. + */ +function prominentPlayer(p: Detection, tallest: number): boolean { + if (sliver(p) || strayLimb(p, tallest)) return false; + if (h(p) >= 0.42) return true; + if (h(p) >= 0.28 && h(p) >= 0.72 * tallest) return true; + return false; +} + +/** + * The crop throws a player out or cuts through them. A prominent player has to stay whole. + * A smaller one may be left out, but not sliced. + */ +function dropsPlayer(r: Box, others: Detection[], mainSharp: number, tallest: number): boolean { + for (const p of others) { + if (sliver(p) || strayLimb(p, tallest)) continue; + if (sharp(p) < 0.45 * mainSharp) continue; + if (edgeAccident(p, tallest)) continue; + const share = overlap(r, p) / Math.max(area(p), 1e-9); + const widthIn = Math.max(0, Math.min(r.x1, p.x1) - Math.max(r.x0, p.x0)) / Math.max(w(p), 1e-9); + if (prominentPlayer(p, tallest)) { + if (share < 0.9) return true; + if (r.y0 > p.y0 + 0.04 * h(p)) return true; + if (p.y1 < FEET_IN_FRAME && r.y1 < p.y1 - 0.05 * h(p)) return true; + continue; + } + if (share > 0.08 && share < 0.9) return true; + if (widthIn > 0.15 && widthIn < 0.88) return true; + } + return false; +} + function slicesOther(r: Box, others: Detection[], mainSharp: number, subjectTallest: number, allowLegs: boolean): boolean { const tallest = Math.max(subjectTallest, 0, ...others.map(h)); for (const p of others) { @@ -654,6 +821,24 @@ function strayLimb(p: Detection, tallest: number): boolean { return p.x0 < 0.02 || p.x1 > 0.98 || p.y0 < 0.02 || p.y1 > 0.98; } +function overlapsStray(r: Box, others: Detection[], tallest: number): boolean { + for (const p of others) { + if (!strayLimb(p, tallest)) continue; + const share = overlap(r, p) / Math.max(area(p), 1e-9); + if (share > 0.02) return true; + } + return false; +} + +function overlapsEdgeCut(r: Box, others: Detection[], tallest: number): boolean { + for (const p of others) { + if (!edgeAccident(p, tallest)) continue; + const share = overlap(r, p) / Math.max(area(p), 1e-9); + if (share > 0.05) return true; + } + return false; +} + /** * Where a sequence plan may end on this person, measured on their own box. A line taken from the top of the * group lands on the neck of whoever stands lower. The hands stay: at the hip on a standing figure, and at the @@ -677,7 +862,8 @@ function planCut(p: Detection, at: number): number | null { export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: number | null = null, opts: ComposeOptions = {}): Box | null { const reportage = opts.context === "reportage"; const faces = opts.faces ?? []; - const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces }); + const detected = reportage ? forReportage(d, faces) : d; + const found = findSubject(detected, opts.focus, { reportage, sport: opts.sport ?? null, faces }); if (!found) return null; const { box: s, reason, people: inSubject } = found; // A lineup is one photograph. A half or a three-quarter of it would cut the row. @@ -689,7 +875,7 @@ export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: numbe if (lines.some((line) => line === null)) return null; const bottom = Math.max(...(lines as number[])); const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); - const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p)); + 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); if (!made) return null; diff --git a/apps/api/src/composition/eyeScore.ts b/apps/api/src/composition/eyeScore.ts new file mode 100644 index 0000000..486739a --- /dev/null +++ b/apps/api/src/composition/eyeScore.ts @@ -0,0 +1,34 @@ +/** + * How open the eyes look in a greyscale crop of a face (0 shut, higher open). A shut eye is a horizontal lid: + * the grey changes down the crop and barely across it. An open eye has a round pupil, so it changes both ways. + * Only useful compared with the other frames of the same sequence. No image library: the desktop can run this. + */ +export function eyeOpenness(grey: Uint8Array, width: number, height: number): number | null { + if (width < 12 || height < 8) return null; + const left = region(grey, width, height, 0.12, 0.42); + const right = region(grey, width, height, 0.58, 0.88); + const scores = [left, right].filter((s): s is number => s !== null); + if (!scores.length) return null; + return scores.reduce((a, b) => a + b, 0) / scores.length; +} + +function region(grey: Uint8Array, width: number, height: number, x0f: number, x1f: number): number | null { + const x0 = Math.max(1, Math.floor(width * x0f)); + const x1 = Math.min(width - 1, Math.ceil(width * x1f)); + const y0 = Math.max(1, Math.floor(height * 0.15)); + const y1 = Math.min(height - 1, Math.ceil(height * 0.85)); + if (x1 - x0 < 4 || y1 - y0 < 4) return null; + let across = 0; + let down = 0; + let n = 0; + for (let y = y0; y < y1; y++) { + for (let x = x0; x < x1; x++) { + const i = y * width + x; + across += Math.abs((grey[i + 1] ?? 0) - (grey[i - 1] ?? 0)); + down += Math.abs((grey[i + width] ?? 0) - (grey[i - width] ?? 0)); + n++; + } + } + if (!n || down < 1) return null; + return across / down; +} diff --git a/apps/api/src/composition/eyes.ts b/apps/api/src/composition/eyes.ts index c874ac5..1949c26 100644 --- a/apps/api/src/composition/eyes.ts +++ b/apps/api/src/composition/eyes.ts @@ -1,39 +1,7 @@ import sharp from "sharp"; +import { eyeOpenness } from "./eyeScore.js"; -/** - * How open the eyes look in a greyscale crop of a face (0 shut, higher open). A shut eye is a horizontal lid: - * the grey changes down the crop and barely across it. An open eye has a round pupil, so it changes both ways. - * Only useful compared with the other frames of the same sequence. - */ -export function eyeOpenness(grey: Uint8Array, width: number, height: number): number | null { - if (width < 12 || height < 8) return null; - const left = region(grey, width, height, 0.12, 0.42); - const right = region(grey, width, height, 0.58, 0.88); - const scores = [left, right].filter((s): s is number => s !== null); - if (!scores.length) return null; - return scores.reduce((a, b) => a + b, 0) / scores.length; -} - -function region(grey: Uint8Array, width: number, height: number, x0f: number, x1f: number): number | null { - const x0 = Math.max(1, Math.floor(width * x0f)); - const x1 = Math.min(width - 1, Math.ceil(width * x1f)); - const y0 = Math.max(1, Math.floor(height * 0.15)); - const y1 = Math.min(height - 1, Math.ceil(height * 0.85)); - if (x1 - x0 < 4 || y1 - y0 < 4) return null; - let across = 0; - let down = 0; - let n = 0; - for (let y = y0; y < y1; y++) { - for (let x = x0; x < x1; x++) { - const i = y * width + x; - across += Math.abs((grey[i + 1] ?? 0) - (grey[i - 1] ?? 0)); - down += Math.abs((grey[i + width] ?? 0) - (grey[i - width] ?? 0)); - n++; - } - } - if (!n || down < 1) return null; - return across / down; -} +export { eyeOpenness } from "./eyeScore.js"; /** The upper part of one face, from the upright preview, reduced to a small grey crop. */ export async function eyeOpennessAt(file: string, face: { x0: number; y0: number; x1: number; y1: number }): Promise { diff --git a/apps/api/src/composition/planFrame.test.ts b/apps/api/src/composition/planFrame.test.ts index 8d76f7b..bbb2502 100644 --- a/apps/api/src/composition/planFrame.test.ts +++ b/apps/api/src/composition/planFrame.test.ts @@ -46,4 +46,65 @@ describe("planFrame", () => { expect(ratio).toBeCloseTo(6000 / 4000, 2); expect(crop.params.aspect).toEqual([6000, 4000]); }); + + it("does not close a reportage frame the camera left open, even when matches are cropped tight", () => { + const planned = planFrame({ + detections: { + width: 6000, + height: 4000, + people: [{ x0: 0.35, y0: 0.28, x1: 0.52, y1: 0.72, score: 0.9, sharpness: 1 }], + balls: [], + }, + width: 6000, + height: 4000, + reportage: true, + values: null, + angle: 0, + cropBias: { dx: 0, dy: 0, scale: 0.8, dAngle: 0, cut: 0.5, head: 0.02, sides: 0.1 }, + settings, + }); + expect(planned.ops.some((op) => op.command === "crop.set")).toBe(false); + }); + + it("does not apply a learnt cut that chops a player the crop had kept", () => { + const planned = planFrame({ + detections: { + width: 6000, + height: 4000, + people: [{ x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.9, score: 0.9, sharpness: 1 }], + balls: [], + }, + width: 6000, + height: 4000, + reportage: false, + values: null, + angle: 0, + cropBias: { dx: 0, dy: 0, scale: 0.8, dAngle: 0, cut: 0.45, head: 0.02, sides: 0.15 }, + settings, + }); + const crop = planned.ops.find((op) => op.command === "crop.set"); + if (!crop || crop.command !== "crop.set") return; + expect(crop.params.rect.y1).toBeGreaterThan(0.88); + expect(crop.params.rect.y0).toBeLessThanOrEqual(0.16); + expect(crop.params.rect.x0).toBeLessThanOrEqual(0.4); + expect(crop.params.rect.x1).toBeGreaterThanOrEqual(0.62); + }); + + it("does not close a reportage full-length the camera already composed", () => { + const planned = planFrame({ + detections: { + width: 6000, + height: 4000, + people: [{ x0: 0.3, y0: 0.12, x1: 0.48, y1: 0.82, score: 0.9, sharpness: 1 }], + balls: [], + }, + width: 6000, + height: 4000, + reportage: true, + values: null, + angle: 0, + settings, + }); + 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 5475943..dd46021 100644 --- a/apps/api/src/composition/planFrame.ts +++ b/apps/api/src/composition/planFrame.ts @@ -1,5 +1,5 @@ import type { EditCommand } from "@photoreport/contracts"; -import { type Box, type Detections, type FocusHint, clipsBall, compose, minCropWidth, planCrop } from "./compose.js"; +import { type Box, type Detections, type FocusHint, type LensHint, clipsBall, compose, minCropWidth, planCrop } from "./compose.js"; import { biasCrop, constrainRotated, frameOnSubject, keepPhotoAspect, tighter } from "./geometry.js"; import { type Look, WB_KEYS, TONE_KEYS, detailForCrop, lookValues, toneApplied } from "../autopilot/look.js"; import type { CropBias } from "../autopilot/cropBias.js"; @@ -10,6 +10,33 @@ const MIN_LEVEL = 0.25; /** A crop this close to the whole frame is not worth making. */ const KEEP_WHOLE = 0.92; +/** The crop no longer contains the ball that was in play. Leaving it outside is the same as cutting it. */ +function losesBall(rect: Box | null, ball: Box | null | undefined): boolean { + if (!rect || !ball) return false; + if (rect.x0 > ball.x0 + 1e-4) return true; + if (rect.y0 > ball.y0 + 1e-4) return true; + if (rect.x1 < ball.x1 - 1e-4) return true; + if (rect.y1 < ball.y1 - 1e-4) return true; + return false; +} + +/** The learnt cut would take off a head or the feet that the crop had kept. */ +function chopsKeptPlayer(original: Box, placed: Box, subject: Box): boolean { + const hadHead = original.y0 <= subject.y0 + 0.03; + const keepsHead = placed.y0 <= subject.y0 + 0.03; + if (hadHead && !keepsHead) return true; + const hadFeet = original.y1 >= subject.y1 - 0.03; + const keepsFeet = placed.y1 >= subject.y1 - 0.03; + if (hadFeet && !keepsFeet) return true; + const hadLeft = original.x0 <= subject.x0 + 0.02; + const keepsLeft = placed.x0 <= subject.x0 + 0.02; + if (hadLeft && !keepsLeft) return true; + const hadRight = original.x1 >= subject.x1 - 0.02; + const keepsRight = placed.x1 >= subject.x1 - 0.02; + if (hadRight && !keepsRight) return true; + return false; +} + export interface PlanSettings { crop: boolean; tone: boolean; @@ -79,6 +106,8 @@ export function planFrame(input: { cropBias?: Omit | null; /** The event's sport. Handball does not frame on a ball that is sitting on the floor. */ 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; settings: PlanSettings; }): PlannedFrame { const { detections, settings, width: W, height: H, reportage } = input; @@ -89,18 +118,28 @@ export function planFrame(input: { const faces = input.faces ?? []; const focus = input.focus ?? null; const sport = input.sport ?? null; - const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context, faces, 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; let crop: Box | null = null; let angle = input.angle; if (settings.crop && composition) { let rect = composition.rect; - const bias = input.cropBias; - const factor = bias?.scale ?? input.cropFactor ?? null; + // Match corrections (a shorter body, a tighter frame) stay on matches. Reportage keeps the frame it planned. + let bias = input.cropBias ?? null; + let factor = input.cropFactor ?? null; + if (reportage) { + bias = null; + factor = null; + } else if (bias?.scale != null) { + factor = bias.scale; + } if (bias && typeof bias.cut === "number") { // The photographer's cut on the body (legs, head, arms), not a uniform shrink. - rect = frameOnSubject(composition.rect, composition.subject, bias); + // It must not chop a player this photograph had kept whole. + const placed = frameOnSubject(composition.rect, composition.subject, bias); + if (!chopsKeptPlayer(composition.rect, placed, composition.subject)) rect = placed; if (bias.dx) { const w = rect.x1 - rect.x0; const x0 = Math.min(Math.max(0, rect.x0 + bias.dx), 1 - w); @@ -112,10 +151,13 @@ export function planFrame(input: { rect = factor < 1 ? tighter(composition.rect, composition.subject, factor) : biasCrop(composition.rect, composition.subject, { dx: 0, dy: 0, scale: factor }); } if (bias?.dAngle) angle = Math.max(-MAX_LEVEL, Math.min(MAX_LEVEL, angle + bias.dAngle)); - // A learnt crop must not slice a ball the frame had kept whole. + // 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)) rect = composition.rect; - if (!clipsBall(rect, balls) && rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(keepPhotoAspect(rect), angle, W, H); + 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); + 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); diff --git a/apps/api/src/delivery/routes.ts b/apps/api/src/delivery/routes.ts index 3ca9844..fcfa0fa 100644 --- a/apps/api/src/delivery/routes.ts +++ b/apps/api/src/delivery/routes.ts @@ -1,7 +1,7 @@ import { createReadStream, existsSync } from "node:fs"; import { DeliveryBestRequest, DeliveryRequest } from "@photoreport/contracts"; import { bestOfEvent } from "../autopilot/best.js"; -import { IptcTemplate, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata"; +import { IptcTemplate, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder, buildVars, withEventDay } from "@photoreport/metadata"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js"; @@ -137,16 +137,30 @@ function localCopyOf( /** Renders the templates against a sample event so a broken template is refused when saved, not at delivery. */ function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra: Record = {}) { - const sample = { - ...buildVars( - { home: "Casa", away: "Fora", venue: "Pavilhão", city: "Cidade", sport: "andebol", competition: "Competição", competitionCode: "C01", round: "1", matchNumber: "1", startsAt: new Date("2026-09-23T19:00:00Z") }, - { capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 }, - "Fotógrafo", - ), - ...extra, - }; + const startsAt = new Date("2026-09-23T19:00:00Z"); + const built = buildVars( + { + home: "Casa", + away: "Fora", + venue: "Pavilhão", + city: "Cidade", + sport: "andebol", + competition: "Competição", + competitionCode: "C01", + round: "1", + matchNumber: "1", + startsAt, + }, + { capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 }, + "Fotógrafo", + ); + const fileSample = { ...built, ...extra }; + const folderSample = { ...withEventDay(built, startsAt), ...extra }; try { - return { folder: renderFolder(folderTemplate, sample), fileName: renderFileName(fileNameTemplate, sample, "IMG_0001.JPG") }; + return { + folder: renderFolder(folderTemplate, folderSample), + fileName: renderFileName(fileNameTemplate, fileSample, "IMG_0001.JPG"), + }; } catch (err) { if (err instanceof PathTemplateError) throw badRequest("invalid_template", err.message); throw err; diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index 53ba3a7..00b9366 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -7,7 +7,9 @@ import { LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, + folderDay, renderFolder, + withEventDay, } from "@photoreport/metadata"; import type { Db } from "../db.js"; import type { DeliveryItem, DeliveryTarget } from "../generated/prisma/client.js"; @@ -167,6 +169,13 @@ export interface DeliveryDeps { originals?: { downloadOriginal(photoId: string): Promise<{ file: string; done: () => Promise } | null> } | undefined; } +/** A match has two sides or a fixture. Those stay on the kickoff day. */ +function eventIsMatch(event: { away: string; fixtureId: string | null }): boolean { + if (event.fixtureId) return true; + if (event.away.trim().length > 0) return true; + return false; +} + /** * Delivery queue: editors pick photos and a target; every photo is rendered (4000 px, IPTC) and uploaded on its * own, with retries. The {n} in file names is fixed when the photo is queued, in capture order, so names never @@ -564,7 +573,19 @@ export class DeliveryService { const exif = item.photo.exif ?? (await readCameraInfo(source).then((c) => c.extra ?? null, () => null)); const vars = buildVars(eventInfoOf(item.event), photoInfoOf({ ...item.photo, exif }, { sequence: item.sequence }), item.photo.uploader?.name, { iptc: iptc?.values }); const named = sameExport && viaTarget ? { ...vars, destination: viaTarget.name } : vars; - let folder = renderFolder(sameExport && viaTarget ? viaTarget.localFolderTemplate || LOCAL_COPY_FOLDER : item.target.folderTemplate, named); + let folderNamed = named; + if (item.event) { + const day = folderDay( + { + startsAt: item.event.startsAt, + endsAt: item.event.ingestUntil, + match: eventIsMatch(item.event), + }, + new Date(), + ); + folderNamed = withEventDay(named, day); + } + let folder = renderFolder(sameExport && viaTarget ? viaTarget.localFolderTemplate || LOCAL_COPY_FOLDER : item.target.folderTemplate, folderNamed); if (!sameExport && item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`; // {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file). // Untouched: the camera's own name, as a local FTP would have received it. @@ -725,7 +746,16 @@ export class DeliveryService { const target = await db.deliveryTarget.findFirst({ where: { id: targetId, organizationId } }); const event = await db.event.findFirst({ where: { id: eventId, organizationId } }); if (!target || !event) throw new DeliveryRejected("not_found"); - const folder = renderFolder(target.folderTemplate, buildVars(eventInfoOf(event))); + const info = eventInfoOf(event); + const day = folderDay( + { + startsAt: info.startsAt, + endsAt: event.ingestUntil, + match: eventIsMatch(event), + }, + new Date(), + ); + const folder = renderFolder(target.folderTemplate, withEventDay(buildVars(info), day)); const client = this.client(target); if (!client.shareLink) throw new DeliveryRejected("share_not_supported"); await client.ensureFolder(folder); diff --git a/apps/api/src/faces/numbers.ts b/apps/api/src/faces/numbers.ts index 25b675f..3316ec8 100644 --- a/apps/api/src/faces/numbers.ts +++ b/apps/api/src/faces/numbers.ts @@ -423,7 +423,10 @@ export async function rosterOf(db: Db, eventId: string): Promise { if (!teamIds.length) return []; const rows = await db.$queryRaw<{ id: string }[]>` @@ -438,7 +441,11 @@ async function peopleOnSquad(db: Db, organizationId: string, teamIds: string[], AND squad.season = ${season} AND ( squad.id = mine.id - OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id) + OR ( + squad.external_id IS NOT NULL + AND squad.external_id = mine.external_id + AND squad.team_id = mine.team_id + ) OR ( squad.birth_date IS NOT NULL AND squad.full_name IS NOT NULL AND mine.birth_date = squad.birth_date diff --git a/apps/api/src/ingest/service.ts b/apps/api/src/ingest/service.ts index 49c6b66..9358f28 100644 --- a/apps/api/src/ingest/service.ts +++ b/apps/api/src/ingest/service.ts @@ -109,8 +109,9 @@ export class IngestService { return { status: "skipped", reason: "unknown_login" }; } - // "Receber FTP aqui": pin is a preferred event for captures that still sit in its ingest window (and session). - // Outside that window the clock routes — a leftover pin on the afternoon training must not take the morning studio. + // "Receber FTP aqui": pin prefers this event. A shoot that runs past the window (extra time, + // penalties, the celebration) stays here while it is the same session. A later session follows the clock, + // so a pin left on from the afternoon does not take the next morning. const target = account.targetEventId && (!account.targetUntil || account.targetUntil > new Date()) ? await db.event.findFirst({ where: { id: account.targetEventId, organizationId: account.organizationId, archivedAt: null }, select: { id: true } }) @@ -387,9 +388,10 @@ export class IngestService { } /** - * The event asked for on the upload (open library / desktop pin). Kept only while the capture sits in that - * event's ingest window and the photographer has not paused more than {@link INGEST_SESSION_GAP_MS} since - * their last photo there — otherwise the clock (or inbox) decides. + * The event asked for on the upload (open library, desktop pin, or "Receber FTP aqui"). Inside the ingest + * window it is kept while the photographer has not paused more than {@link INGEST_SESSION_GAP_MS}. + * Past the end of the window it is kept only as a continuation of that same session — extra time must not + * fall off an open pin, and a new session must not attach to it either. */ private async requestedEvent( organizationId: string, @@ -403,8 +405,11 @@ export class IngestService { select: { ingestFrom: true, ingestUntil: true }, }); if (!event) return undefined; - if (at < event.ingestFrom || at > event.ingestUntil) return undefined; - if (!(await this.sameSession(requested, userId, at))) return undefined; + if (at < event.ingestFrom) return undefined; + const last = await this.lastCapture(requested, userId, at); + if (!withinIngestSession(at, last)) return undefined; + if (at <= event.ingestUntil) return requested; + if (!last) return undefined; return requested; } @@ -433,8 +438,8 @@ export class IngestService { return null; } - /** Last capture by this photographer in the event; none yet → new session may start. */ - private async sameSession(eventId: string, userId: string, at: Date): Promise { + /** Last capture by this photographer in the event, strictly before `at`. */ + private async lastCapture(eventId: string, userId: string, at: Date): Promise { const last = await this.deps.db.photo.findFirst({ where: { eventId, @@ -444,7 +449,12 @@ export class IngestService { orderBy: { capturedAt: "desc" }, select: { capturedAt: true }, }); - return withinIngestSession(at, last?.capturedAt); + return last?.capturedAt ?? null; + } + + /** None yet → a new session may start. A pause longer than {@link INGEST_SESSION_GAP_MS} starts another. */ + private async sameSession(eventId: string, userId: string, at: Date): Promise { + return withinIngestSession(at, await this.lastCapture(eventId, userId, at)); } /** @@ -497,35 +507,53 @@ export class IngestService { } /** - * Photos stored an hour early because the camera still writes +01:00 in winter. Re-read the stored file - * (the original, or the preview the desktop sent, which keeps the camera's clock) and, when it moves by - * that hour, put the capture time right and let the autopilot decide the frame again. + * Photos stored an hour early because an older read treated a summer offset (+01:00) as real in winter. + * Re-read the stored file and, when that hour is still missing after the login's own clock offset, put the + * capture time right and let the autopilot decide the frame again. + * The login offset is applied again here. Without it, a body set an hour back (clockOffsetSec -3600) is + * "repaired" forward and the offset the photographer saved is undone on every new photo. */ async backfillCaptureClock(limit = 100): Promise { const { db, storage, log } = this.deps; const rows = await db.$queryRaw< - Array<{ id: string; storage_key: string; captured_at: Date | null; taken_at: Date; autopilot: unknown; exif: unknown }> + Array<{ id: string; storage_key: string; captured_at: Date | null; taken_at: Date; autopilot: unknown; exif: unknown; clock_offset_sec: number }> >` - SELECT id, storage_key, captured_at, taken_at, autopilot, exif - FROM photos - WHERE status = 'READY' - AND created_at > now() - interval '3 days' + SELECT p.id, p.storage_key, p.captured_at, p.taken_at, p.autopilot, p.exif, + COALESCE(( + SELECT CASE + WHEN COUNT(DISTINCT a.clock_offset_sec) = 1 THEN MIN(a.clock_offset_sec) + ELSE 0 + END + FROM ftp_accounts a + WHERE a.user_id = p.uploader_id + AND a.organization_id = p.organization_id + ), 0) AS clock_offset_sec + FROM photos p + WHERE p.status = 'READY' + AND p.created_at > now() - interval '3 days' AND ( - exif IS NULL - OR jsonb_typeof(exif::jsonb) <> 'object' - OR COALESCE((exif::jsonb->>'captureClockChecked')::boolean, false) IS NOT TRUE + p.exif IS NULL + OR jsonb_typeof(p.exif::jsonb) <> 'object' + OR COALESCE((p.exif::jsonb->>'captureClockChecked')::boolean, false) IS NOT TRUE ) - ORDER BY created_at DESC + ORDER BY p.created_at DESC LIMIT ${limit} `; let fixed = 0; for (const row of rows) { const camera = await readCameraInfo(storage.resolve(row.storage_key)).catch(() => null); - const next = camera?.capturedAt ?? null; + const read = camera?.capturedAt ?? null; const prev = row.captured_at ? new Date(row.captured_at).getTime() : null; - const hourOff = next && prev !== null && Math.abs(next.getTime() - prev - 3_600_000) < 2_000; + const offsetMs = Number(row.clock_offset_sec) * 1000; + let corrected: Date | null = null; + if (read && prev !== null) { + const adjusted = read.getTime() + offsetMs; + const storedHourEarly = Math.abs(adjusted - prev - 3_600_000) < 2_000; + const storedIgnoredOffset = offsetMs !== 0 && Math.abs(prev - read.getTime()) < 2_000 && Math.abs(prev - adjusted) >= 2_000; + if (storedHourEarly || storedIgnoredOffset) corrected = new Date(adjusted); + } const autopilot = row.autopilot && typeof row.autopilot === "object" && !Array.isArray(row.autopilot) ? { ...(row.autopilot as Record) } : null; - if (hourOff && autopilot) { + if (corrected && autopilot) { delete autopilot.curated; delete autopilot.chosen; delete autopilot.gallery; @@ -535,16 +563,16 @@ export class IngestService { where: { id: row.id }, data: { exif: withCaptureClockChecked(row.exif) as Prisma.InputJsonValue, - ...(hourOff && next + ...(corrected ? { - capturedAt: next, - ...(prev !== null && Math.abs(taken - prev) < 2_000 ? { takenAt: next } : {}), + capturedAt: corrected, + ...(prev !== null && Math.abs(taken - prev) < 2_000 ? { takenAt: corrected } : {}), ...(autopilot ? { autopilot: autopilot as Prisma.InputJsonValue } : {}), } : {}), }, }); - if (hourOff) fixed++; + if (corrected) fixed++; } if (rows.length) log.info({ scanned: rows.length, fixed }, "ingest: capture clock repair"); return fixed; diff --git a/apps/api/src/library/ftp.ts b/apps/api/src/library/ftp.ts index 1212a35..4e99d26 100644 --- a/apps/api/src/library/ftp.ts +++ b/apps/api/src/library/ftp.ts @@ -57,7 +57,8 @@ export function sftpgoUser( expiration_date: account.expiresAt ? account.expiresAt.getTime() : 0, quota_size: (account.plan?.quotaMb ?? 0) * 1024 * 1024, quota_files: account.plan?.quotaFiles ?? 0, - max_sessions: 4, + // Authenticated cameras have no session cap. SFTPGo reads 0 as no limit. + max_sessions: 0, }; } const UpdateBody = z.object({ diff --git a/apps/api/src/library/serialize.ts b/apps/api/src/library/serialize.ts index f82323a..a8de2f2 100644 --- a/apps/api/src/library/serialize.ts +++ b/apps/api/src/library/serialize.ts @@ -21,6 +21,7 @@ export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSum width: photo.width, height: photo.height, capturedAt: photo.capturedAt?.toISOString() ?? null, + createdAt: photo.createdAt.toISOString(), cameraModel: photo.cameraModel, lens: photo.lens, focalLength: photo.focalLength, diff --git a/apps/api/test/autopilot.test.ts b/apps/api/test/autopilot.test.ts index 305de3a..13944c4 100644 --- a/apps/api/test/autopilot.test.ts +++ b/apps/api/test/autopilot.test.ts @@ -133,6 +133,31 @@ describe("only the best", () => { const opened = curate([...early, late], [{ id: late.id, chosen: true, at: late.at }], opts); expect(opened.find((d) => d.window === 0)?.chosen.length).toBeGreaterThan(0); }); + + it("keeps two frames of a slow sequence, not every shot a second apart", () => { + const seq = Array.from({ length: 10 }, (_, i) => c(i * 2_000, 8 - i * 0.1, { reason: "person" })); + const opts = { count: 150, start, durationMs: 115 * min, now: start + 10 * min }; + const chosen = curate(seq, [], opts).flatMap((d) => d.chosen); + expect(chosen.length).toBe(2); + expect(chosen).toContain(seq[0]!.id); + }); + + it("sends up to four when the same sequence changes picture, not one of every frame", () => { + const standing = { x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.95 }; + const tight = { x0: 0.35, y0: 0.05, x1: 0.7, y1: 0.45 }; + const group = { x0: 0.05, y0: 0.3, x1: 0.95, y1: 0.85 }; + const boxes = [standing, tight, group, standing, tight, group, standing, tight]; + const seq = boxes.map((subject, i) => + c(i * 6_000, 8 - i * 0.05, { + reason: subject === group ? "group" : "person", + people: subject === group ? 3 : 1, + subject, + }), + ); + const opts = { count: 150, start, durationMs: 115 * min, now: start + 10 * min, sequenceCap: 2 }; + const chosen = curate(seq, [], opts).flatMap((d) => d.chosen); + expect(chosen.length).toBe(4); + }); }); describe("learning from corrections", () => { @@ -418,7 +443,8 @@ describe("autopilot", () => { const { orgId, userId, eventId } = await setup(); await ctx.db.event.update({ where: { id: eventId }, data: { venue: "Pavilhão Flávio Sá Leite" } }); const photos: string[] = []; - for (let i = 0; i < 6; i++) photos.push(await shot(orgId, userId, eventId, i * 10_000, 300)); + // Farther apart than one sequence, so each frame is edited. A sequence only crops its picks. + for (let i = 0; i < 6; i++) photos.push(await shot(orgId, userId, eventId, i * 20_000, 300)); await runQueue(); await autopilot.decideBursts(new Date(Date.now() + 20_000)); // The photographer lifts the exposure (0.2 -> 0.5) and crops tighter on five of them. @@ -437,7 +463,7 @@ describe("autopilot", () => { expect(style).toMatchObject({ samples: 5, venue: "pavilhão flávio sá leite", offsets: { "light.exposure": 0.3 } }); expect(style!.cropFactor).toBeCloseTo(0.84, 1); - const next = await shot(orgId, userId, eventId, 100_000, 300); + const next = await shot(orgId, userId, eventId, 200_000, 300); await runQueue(); await autopilot.decideBursts(new Date(Date.now() + 20_000)); const edits = await ctx.db.photoEdit.findMany({ where: { photoId: next }, orderBy: { seq: "asc" } }); diff --git a/apps/api/test/compose.test.ts b/apps/api/test/compose.test.ts index ee0712f..a744f62 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, isReportage, minCropWidth, planCrop, sendBlockedByBall } from "../src/composition/compose.js"; +import { clipsBall, compose, type Detection, findSubject, isHandball, isLongPrime, isReportage, minCropWidth, planCrop, sendBlockedByBall, shotIntent } 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; @@ -29,6 +29,15 @@ describe("automatic crop", () => { expect(main).toMatchObject(s.box); }); + it("does not throw a second player out of the frame", () => { + const main = person(0.18, 0.18, 0.4, 0.86); + const other = person(0.68, 0.2, 0.9, 0.84); + const c = compose({ ...frame, people: [main, other], balls: [] }, null, { framing: "tight", context: "sport" }); + if (!c) return; + expect(inside(c.rect, main)).toBe(true); + expect(inside(c.rect, other)).toBe(true); + }); + it("keeps a group together, and doesn't slice a big body at the crop's edge", () => { const a = person(0.3, 0.2, 0.42, 0.8); const b = person(0.4, 0.22, 0.52, 0.82); @@ -139,6 +148,15 @@ describe("the ball follows the sport", () => { expect(isHandball(null)).toBe(false); }); + it("keeps a ball in the outstretched hand inside the crop", () => { + const player = person(0.48, 0.15, 0.62, 0.92); + const ball = { x0: 0.02, y0: 0.28, x1: 0.08, y1: 0.36, score: 0.9 }; + const c = compose({ ...frame, people: [player], balls: [ball] }, null, { framing: "tight", context: "sport", sport: "andebol" })!; + expect(c.reason).toBe("ball"); + expect(inside(c.rect, player)).toBe(true); + expect(inside(c.rect, ball)).toBe(true); + }); + it("in handball the ball in the hands wins over one on the floor, even when the floor ball overlaps the player and is closer to the body's middle", () => { const player = { ...person(0.4, 0.15, 0.66, 0.996), sharpness: 1 }; const inHand = { x0: 0.48, y0: 0.08, x1: 0.56, y1: 0.18, score: 0.9 }; @@ -167,26 +185,68 @@ describe("reportage", () => { expect(isReportage({ away: "", fixtureId: "11111111-1111-4111-8111-111111111111" })).toBe(false); }); - it("keeps the whole person when the event asked for the sports framing", () => { - const p = person(0.4, 0.15, 0.55, 0.8); - const c = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" })!; - expect(c.rect.y1).toBeGreaterThan(p.y1); - expect(c.rect.x0).toBeLessThanOrEqual(p.x0); - expect(c.rect.x1).toBeGreaterThanOrEqual(p.x1); - expect((p.y1 - p.y0) / (c.rect.y1 - c.rect.y0)).toBeLessThan(1); + it("names the shot from the frame", () => { + expect(shotIntent([person(0.35, 0.28, 0.52, 0.72)])).toBe("scene"); + expect(shotIntent([person(0.3, 0.12, 0.48, 0.82)])).toBe("figure"); + const left = person(0.16, 0.08, 0.36, 0.86); + const right = person(0.62, 0.06, 0.84, 0.88); + expect(shotIntent([left, right])).toBe("group"); + expect(shotIntent([person(0.36, 0.15, 0.66, 0.996)])).toBe("closed"); }); - it("keeps every head of a conversation, including someone stood in the shade", () => { + it("leaves a wide frame as shot", () => { + const speaker = person(0.35, 0.28, 0.52, 0.72); + const room = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "reportage" }); + expect(room).toBeNull(); + const match = compose({ ...frame, people: [speaker], balls: [] }, null, { context: "sport" }); + expect(match).not.toBeNull(); + }); + + it("knows a long prime from a zoom and from a short prime", () => { + expect(isLongPrime({ focalLength: 135, range: [135, 135] })).toBe(true); + expect(isLongPrime({ focalLength: 100, range: [100, 100] })).toBe(true); + expect(isLongPrime({ focalLength: 85, range: [85, 85] })).toBe(false); + expect(isLongPrime({ focalLength: 200, range: [70, 200] })).toBe(false); + expect(isLongPrime({ focalLength: 400, name: "RF100-500mm F4.5-7.1" })).toBe(false); + expect(isLongPrime({ focalLength: 135, name: "RF135mm F1.8" })).toBe(true); + expect(isLongPrime({ focalLength: 200 })).toBe(false); + }); + + it("steps a full-length closer on a long prime, and leaves the same frame on a zoom", () => { + const p = person(0.3, 0.12, 0.48, 0.82); + const photo = { ...frame, people: [p], balls: [] }; + const prime = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [135, 135] } })!; + expect(prime.rect.y0).toBeLessThanOrEqual(p.y0); + expect(prime.rect.y1).toBeGreaterThan(p.y1); + expect(prime.rect.x0).toBeLessThanOrEqual(p.x0); + expect(prime.rect.x1).toBeGreaterThanOrEqual(p.x1); + const width = prime.rect.x1 - prime.rect.x0; + expect(width).toBeGreaterThan(0.8); + expect(width).toBeLessThan(0.92); + const zoom = compose(photo, null, { context: "reportage", lens: { focalLength: 135, range: [70, 200] } }); + expect(zoom).toBeNull(); + const wide = person(0.35, 0.28, 0.52, 0.72); + const scene = compose({ ...frame, people: [wide], balls: [] }, null, { context: "reportage", lens: { focalLength: 200, range: [200, 200] } }); + expect(scene).toBeNull(); + }); + + it("leaves a full-length as it was framed, and a match of the same picture still closes", () => { + const p = person(0.3, 0.12, 0.48, 0.82); + const room = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" }); + expect(room).toBeNull(); + const match = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "sport" }); + expect(match).not.toBeNull(); + if (!match) return; + expect(match.rect.x1 - match.rect.x0).toBeLessThan(0.92); + }); + + it("leaves a conversation as it was framed", () => { const left = { ...person(0.16, 0.08, 0.36, 0.86), sharpness: 0.4 }; const center = { ...person(0.38, 0.16, 0.6, 0.92), sharpness: 1 }; const right = { ...person(0.62, 0.06, 0.84, 0.88), sharpness: 0.45 }; - const c = compose({ ...frame, people: [left, center, right], balls: [] }, null, { framing: "tight", context: "reportage" })!; - expect(c.reason).toBe("group"); - expect(c.people).toBe(3); - expect(c.rect.y0).toBeLessThanOrEqual(0.06); - expect(c.rect.y1).toBeGreaterThan(0.92); - expect(c.rect.x0).toBeLessThanOrEqual(0.16); - expect(c.rect.x1).toBeGreaterThanOrEqual(0.84); + const c = compose({ ...frame, people: [left, center, right], balls: [] }, null, { framing: "tight", context: "reportage" }); + expect(c).toBeNull(); + expect(shotIntent([left, center, right])).toBe("group"); }); it("does not slice the head of a person the crop otherwise keeps", () => { @@ -220,20 +280,31 @@ describe("reportage", () => { for (const j of [0.53, 0.74, 0.95]) expect(Math.abs(at - j)).toBeGreaterThanOrEqual(0.035); }); - it("keeps a complete foot when the head is already against the top edge", () => { + it("leaves a full-length that already fills the frame, so the foot stays", () => { const p = person(0.4, 0.02, 0.55, 0.984); - const c = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" })!; - expect(c.rect.y1).toBeGreaterThan(p.y1 - 1e-6); - expect(c.rect.y0).toBeLessThanOrEqual(p.y0 + 1e-6); + const c = compose({ ...frame, people: [p], balls: [] }, null, { framing: "tight", context: "reportage" }); + expect(c).toBeNull(); + expect(shotIntent([p])).toBe("figure"); }); - it("leaves out a stray hand at the edge of someone who is not the subject", () => { + it("does not close a full-length to delete a hand at the edge", () => { const subject = person(0.22, 0.18, 0.4, 0.82); const hand = person(0, 0.35, 0.07, 0.5, 0.8); - const c = compose({ ...frame, people: [subject, hand], balls: [] }, null, { context: "reportage" })!; - const handIn = Math.max(0, Math.min(c.rect.x1, hand.x1) - Math.max(c.rect.x0, hand.x0)) / (hand.x1 - hand.x0); - expect(handIn).toBeLessThan(0.05); + const c = compose({ ...frame, people: [subject, hand], balls: [] }, null, { context: "reportage" }); + expect(c).toBeNull(); + }); + + it("drops a person the frame already cut off, and keeps the full-length around the subject", () => { + const subject = person(0.32, 0.18, 0.5, 0.84); + const cutOff = person(0, 0.2, 0.16, 0.95); + const c = compose({ ...frame, people: [subject, cutOff], balls: [] }, null, { context: "reportage" })!; + const cutIn = Math.max(0, Math.min(c.rect.x1, cutOff.x1) - Math.max(c.rect.x0, cutOff.x0)) / (cutOff.x1 - cutOff.x0); + expect(cutIn).toBeLessThan(0.05); + expect(c.rect.x0).toBeLessThanOrEqual(subject.x0); + expect(c.rect.x1).toBeGreaterThanOrEqual(subject.x1); + expect(c.rect.y0).toBeLessThanOrEqual(subject.y0); expect(c.rect.y1).toBeGreaterThan(subject.y1); + expect(c.rect.y1 - c.rect.y0).toBeGreaterThan(0.8); }); it("crops the whole person at the car, not the sharper face in the window", () => { @@ -261,7 +332,8 @@ describe("reportage", () => { }); it("keeps the closer woman whole when the woman behind her is sharper", () => { - // PSR39046, the glass entrance. The foreground figure is taller; the crop used to be a band on the woman behind. + // PSR39046, the glass entrance. The foreground figure is the full-length. Leaving the frame keeps her whole, + // instead of cutting a band on the woman behind. const front = { ...person(0.45, 0.23, 0.636, 0.933, 0.9), sharpness: 0.6 }; const behind = { ...person(0.382, 0.304, 0.473, 0.667, 0.9), sharpness: 1 }; const c = compose({ width: 6000, height: 4000, people: [front, behind], balls: [] }, null, { @@ -271,25 +343,17 @@ describe("reportage", () => { { x0: 0.5, y0: 0.25, x1: 0.56, y1: 0.34 }, { x0: 0.4, y0: 0.31, x1: 0.45, y1: 0.4 }, ], - })!; - expect(c.rect.y0).toBeLessThanOrEqual(front.y0 + 1e-6); - expect(c.rect.y1).toBeGreaterThan(front.y1 - 1e-6); - expect(c.rect.x0).toBeLessThanOrEqual(front.x0 + 1e-6); - expect(c.rect.x1).toBeGreaterThanOrEqual(front.x1 - 1e-6); - expect(c.rect.y1 - c.rect.y0).toBeGreaterThan(0.7); + }); + expect(c).toBeNull(); }); - it("still frames three whole figures standing in the middle of a wide shot", () => { - // PSR16148. The boxes already are the bodies. The crop stays around them, it does not become the whole frame. + it("leaves a wide shot of small figures as it was framed", () => { + // People in the middle of a room, none of them large. The space around them is the photograph. const a = { ...person(0.368, 0.296, 0.463, 0.614), sharpness: 0.84 }; const b = { ...person(0.477, 0.308, 0.547, 0.627), sharpness: 1 }; const c0 = { ...person(0.535, 0.293, 0.615, 0.62), sharpness: 0.85 }; - const c = compose({ width: 6000, height: 4000, people: [a, b, c0], balls: [] }, null, { context: "reportage", minWidth: 0.5 })!; - expect(c.reason).toBe("group"); - expect(c.rect.y0).toBeLessThanOrEqual(0.296); - expect(c.rect.y1).toBeGreaterThanOrEqual(0.627); - expect(c.rect.y1 - c.rect.y0).toBeLessThan(0.75); - expect(c.rect.x1 - c.rect.x0).toBeLessThan(0.92); + const c = compose({ width: 6000, height: 4000, people: [a, b, c0], balls: [] }, null, { context: "reportage", minWidth: 0.5 }); + expect(c).toBeNull(); }); it("makes a three-quarter plan below the hands, and refuses a half that would cut them", () => { diff --git a/apps/api/test/library.test.ts b/apps/api/test/library.test.ts index 57aa1b2..ea23b9e 100644 --- a/apps/api/test/library.test.ts +++ b/apps/api/test/library.test.ts @@ -264,6 +264,48 @@ describe("library", () => { expect(await send("c.jpg", "2026:09:23 22:00:00")).toMatchObject({ status: "ingested", eventId: null }); }); + it("keeps a pin for extra time after the window, and does not undo a login clock offset", async () => { + const { orgId, photographer, event } = await setup(); + const send = async (name: string, taken: string, offset = 0) => { + const file = path.join(dir, name); + await writeFile(file, await jpeg({ color: "#445566", taken })); + return service.ingest(file, { + organizationId: orgId, + userId: photographer.id, + source: "DESKTOP", + originalName: name, + eventId: event.id, + clockOffsetSec: offset, + }); + }; + // 00:20 wall in summer is 23:20 UTC, still inside the window that ends at 23:30. + expect(await send("late.jpg", "2026:09:24 00:20:00")).toMatchObject({ status: "ingested", eventId: event.id }); + // 01:00 wall is 00:00 UTC, past the window, forty minutes later: the same match, not the inbox. + expect(await send("extra.jpg", "2026:09:24 01:00:00")).toMatchObject({ status: "ingested", eventId: event.id }); + + // Mark those two checked before the login offset changes, so the repair is only about the offset photo. + expect(await service.backfillCaptureClock(10)).toBe(0); + await ctx.db.ftpAccount.updateMany({ data: { clockOffsetSec: -3600 } }); + const shifted = await send("clock.jpg", "2026:11:20 00:14:34", -3600); + const photoId = (shifted as { photoId: string }).photoId; + const photo = await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } }); + expect(photo.capturedAt?.toISOString()).toBe("2026-11-19T23:14:34.000Z"); + expect(await service.backfillCaptureClock(10)).toBe(0); + const kept = await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } }); + expect(kept.capturedAt?.toISOString()).toBe("2026-11-19T23:14:34.000Z"); + + await ctx.db.ftpAccount.updateMany({ data: { clockOffsetSec: 0 } }); + const early = await send("early.jpg", "2026:12:05 21:14:07", 0); + const earlyId = (early as { photoId: string }).photoId; + await ctx.db.photo.update({ + where: { id: earlyId }, + data: { capturedAt: new Date("2026-12-05T20:14:07.000Z"), exif: {} }, + }); + expect(await service.backfillCaptureClock(10)).toBe(1); + const repaired = await ctx.db.photo.findUniqueOrThrow({ where: { id: earlyId } }); + expect(repaired.capturedAt?.toISOString()).toBe("2026-12-05T21:14:07.000Z"); + }); + it("an archive import stays in its put-away event when the photo was taken outside that window", async () => { const { orgId, admin, photographer, event } = await setup(); await ctx.db.event.update({ where: { id: event.id }, data: { archivedAt: new Date("2026-09-24T00:00:00Z") } }); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 4d04b65..4c353a9 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -62,6 +62,18 @@ export const t = { photoMenuDevelop: "Revelar", photoMenuLoupe: "Lupa", photoMenuGrid: "Grelha", + photoMenuSend: "Enviar", + photoMenuMove: "Mover para evento", + photoMenuApplyDevelop: "Aplicar revelação básica", + photoMenuSelectAll: "Selecionar tudo", + photoMenuSelectNone: "Limpar seleção", + photoMenuNothingToSend: "Nada para enviar: as selecionadas estão rejeitadas ou ainda a chegar.", + eventMenu: "Evento", + eventMenuOpen: "Abrir", + eventMenuSettings: "Definições", + eventMenuAutopilot: "Piloto automático", + eventMenuFtp: "Receber o FTP local aqui", + eventMenuFtpStop: "Deixar de receber o FTP local", folderSheet: { opening: "A abrir a pasta…", close: "Fechar", @@ -97,6 +109,12 @@ export const t = { noPhotos: "Sem fotografias neste filtro.", noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.", filter: "Filtro", + sortBy: "Ordem", + sortOptions: { + capture: { asc: "Captura", desc: "Captura, mais recente" }, + arrival: { asc: "Chegada", desc: "Chegada, mais recente" }, + name: { asc: "Nome do ficheiro", desc: "Nome do ficheiro, Z–A" }, + }, flagFilter: { all: "Todas", PICK: "Escolhidas", UNFLAGGED: "Sem marca", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas" }, starsAtLeast: "Estrelas (pelo menos)", starsOrMore: (n: number) => (n === 1 ? "1 estrela ou mais" : `${n} estrelas ou mais`), diff --git a/apps/app/src/library/Autopilot.tsx b/apps/app/src/library/Autopilot.tsx index 4f696b0..c051e3b 100644 --- a/apps/app/src/library/Autopilot.tsx +++ b/apps/app/src/library/Autopilot.tsx @@ -8,12 +8,26 @@ import { ZerozeroGamePicker } from "./ZerozeroGame.js"; * Autopilot for the open event (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest * are edited (tone, level, crop) and the best frames of each burst picked, and optionally delivered. */ -export function AutopilotButton(props: { api: ApiClient; event: EventSummary; targets: DeliveryTarget[]; canEdit: boolean; onSaved: (e: EventSummary) => void }) { +export function AutopilotButton(props: { + api: ApiClient; + event: EventSummary; + targets: DeliveryTarget[]; + canEdit: boolean; + onSaved: (e: EventSummary) => void; + /** Set from the event menu. Opens this panel once, then calls onAsked. */ + autopilotAsk?: { id: string; n: number } | null; + onAsked?: () => void; +}) { const L = t.autopilot; const [open, setOpen] = useState(false); const [s, setS] = useState(() => AutopilotSettings.parse(props.event.autopilot ?? {})); const [state, setState] = useState<"idle" | "saving" | "error">("idle"); useEffect(() => setS(AutopilotSettings.parse(props.event.autopilot ?? {})), [props.event]); + useEffect(() => { + if (!props.autopilotAsk || props.autopilotAsk.id !== props.event.id) return; + setOpen(true); + props.onAsked?.(); + }, [props.autopilotAsk, props.event.id, props.onAsked]); const save = async (next: AutopilotSettings) => { // Keep deliverTargetIds in sync with the two legacy slots (N exports = ordered list). diff --git a/apps/app/src/library/ContextMenu.test.tsx b/apps/app/src/library/ContextMenu.test.tsx new file mode 100644 index 0000000..e3725dd --- /dev/null +++ b/apps/app/src/library/ContextMenu.test.tsx @@ -0,0 +1,102 @@ +import type { EventSummary } from "@photoreport/sdk"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { EventsPanel } from "./EventsPanel.js"; +import { PhotoContextMenu } from "./PhotoContextMenu.js"; + +function event(id: string, title: string): EventSummary { + return { + id, + organizationId: "org", + title, + home: title, + away: "", + homeShort: null, + awayShort: null, + venue: null, + city: null, + sport: null, + competition: null, + competitionCode: null, + round: null, + matchNumber: null, + startsAt: "2026-11-21T10:56:00.000Z", + ingestFrom: "2026-11-21T08:56:00.000Z", + ingestUntil: "2026-11-21T14:56:00.000Z", + iptcTemplate: {}, + archivedAt: null, + photographers: [], + photoCount: 12, + }; +} + +describe("event context menu", () => { + it("asks for the event menu and does not fall through to the page", () => { + const onEventMenu = vi.fn(); + const onPanelMenu = vi.fn(); + const onInboxMenu = vi.fn(); + render( + {}} + onCreate={() => {}} + onEventMenu={onEventMenu} + onInboxMenu={onInboxMenu} + onPanelMenu={onPanelMenu} + />, + ); + + const row = screen.getByRole("button", { name: /Assembleia Geral FAP/ }); + fireEvent.contextMenu(row); + expect(onEventMenu).toHaveBeenCalledOnce(); + const rowMenu = onEventMenu.mock.calls[0]?.[1] as MouseEvent; + expect(rowMenu.defaultPrevented).toBe(true); + expect(onPanelMenu).not.toHaveBeenCalled(); + + const inbox = screen.getByRole("button", { name: /Sem evento/ }); + fireEvent.contextMenu(inbox); + expect(onInboxMenu).toHaveBeenCalledOnce(); + + const panel = screen.getByRole("complementary", { name: "Eventos" }); + fireEvent.contextMenu(panel); + expect(onPanelMenu).toHaveBeenCalledOnce(); + }); +}); + +describe("photo context menu", () => { + it("sets a colour and opens a destination list", () => { + const onColor = vi.fn(); + const onClose = vi.fn(); + const onSend = vi.fn(); + render( + {} }, + ]} + />, + ); + + fireEvent.click(screen.getByRole("button", { name: "Vermelho" })); + expect(onColor).toHaveBeenCalledWith("RED"); + expect(onClose).toHaveBeenCalledOnce(); + + fireEvent.click(screen.getByRole("menuitem", { name: "Enviar" })); + expect(onClose).toHaveBeenCalledOnce(); + fireEvent.click(screen.getByRole("menuitem", { name: "FPA Eventos" })); + expect(onSend).toHaveBeenCalledOnce(); + expect(onClose).toHaveBeenCalledTimes(2); + }); +}); diff --git a/apps/app/src/library/EventSettings.tsx b/apps/app/src/library/EventSettings.tsx index 99753bd..aff392a 100644 --- a/apps/app/src/library/EventSettings.tsx +++ b/apps/app/src/library/EventSettings.tsx @@ -27,6 +27,9 @@ export function EventSettingsButton(props: { canEdit: boolean; onSaved: (e: EventSummary) => void; onRemoved: (eventId: string) => void; + /** Set from the event menu. Opens this panel once, then calls onAsked. */ + settingsAsk?: { id: string; n: number } | null; + onAsked?: () => void; }) { const L = t.eventSettings; const { api, event } = props; @@ -48,6 +51,12 @@ export function EventSettingsButton(props: { const [error, setError] = useState(null); const [confirm, setConfirm] = useState(false); + useEffect(() => { + if (!props.settingsAsk || props.settingsAsk.id !== event.id) return; + setOpen(true); + props.onAsked?.(); + }, [props.settingsAsk, event.id, props.onAsked]); + useEffect(() => { setStartsAt(isoToLisbonLocal(event.startsAt)); setFrom(isoToLisbonLocal(event.ingestFrom)); diff --git a/apps/app/src/library/EventsPanel.tsx b/apps/app/src/library/EventsPanel.tsx index 1cfea61..a59cb48 100644 --- a/apps/app/src/library/EventsPanel.tsx +++ b/apps/app/src/library/EventsPanel.tsx @@ -29,6 +29,9 @@ export function EventsPanel(props: { /** Events put away by hand (loaded when asked for); null: not shown. */ archived?: EventSummary[] | null; onToggleArchived?: () => void; + onEventMenu?: (event: EventSummary, e: React.MouseEvent) => void; + onInboxMenu?: (e: React.MouseEvent) => void; + onPanelMenu?: (e: React.MouseEvent) => void; }) { const [older, setOlder] = useState(false); const L = t.eventsList; @@ -46,8 +49,14 @@ export function EventsPanel(props: { const item = (e: EventSummary, archived = false) => ( + + {openId === a.id && !!a.items?.length && ( +
+ {a.items.map((item) => ( + + ))} +
+ )} + ))} ); diff --git a/apps/app/src/library/SortControl.tsx b/apps/app/src/library/SortControl.tsx new file mode 100644 index 0000000..45e49b1 --- /dev/null +++ b/apps/app/src/library/SortControl.tsx @@ -0,0 +1,27 @@ +import { t } from "../i18n.js"; +import { SORT_CHOICES, sortValue, parseSortValue, type LibrarySort } from "./sort.js"; + +/** The library order: capture time, arrival time, or file name, each oldest/A–Z or the other way. */ +export function SortControl(props: { sort: LibrarySort; onChange: (sort: LibrarySort) => void }) { + const { sort, onChange } = props; + return ( + + ); +} diff --git a/apps/app/src/library/TargetForm.tsx b/apps/app/src/library/TargetForm.tsx index d1b0eff..81ffb87 100644 --- a/apps/app/src/library/TargetForm.tsx +++ b/apps/app/src/library/TargetForm.tsx @@ -477,7 +477,7 @@ export function TargetForm({ field( "folderTemplate", v.kind === "LOCAL" - ? "Subpasta ({event} = Casa x Fora, {iptcdate} = 20261009)" + ? "Subpasta ({event} = Casa x Fora, {iptcdate} = dia do evento)" : "Pasta ({event} = Casa x Fora)", )} {field( @@ -620,7 +620,7 @@ export function TargetForm({