diff --git a/apps/api/src/archive/routes.ts b/apps/api/src/archive/routes.ts index 4741322..f32559a 100644 --- a/apps/api/src/archive/routes.ts +++ b/apps/api/src/archive/routes.ts @@ -62,16 +62,24 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const files = await db.cloudFile.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } }); const folders = await db.cloudFolder.groupBy({ by: ["sourceId", "matchedBy"], where: { sourceId: { in: sourceIds }, ...GALLERY }, _count: { _all: true } }); const videos = await db.cloudVideo.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } }); + // Faces in the videos made (videos waiting for their copy are not waiting for faces yet). + const videoFaces = await db.cloudVideo.groupBy({ by: ["sourceId", "facesStatus"], where: { sourceId: { in: sourceIds }, status: "DONE", facesStatus: { not: "NONE" } }, _count: { _all: true } }); // The pace: images indexed in the last 15 minutes, per hour. const recent = await db.cloudFile.groupBy({ by: ["sourceId"], where: { sourceId: { in: sourceIds }, status: "DONE", updatedAt: { gte: new Date(Date.now() - 15 * 60_000) } }, _count: { _all: true } }); const out = new Map>(); - const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0 }).get(id)!; + const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0 }).get(id)!; for (const v of videos) { const c = get(v.sourceId); if (v.status === "DONE") c.videos! += v._count._all; else if (v.status === "FAILED") c.videosFailed! += v._count._all; else c.videosPending! += v._count._all; } + for (const v of videoFaces) { + const c = get(v.sourceId); + if (v.facesStatus === "DONE") c.videoFacesDone! += v._count._all; + else if (v.facesStatus === "FAILED") c.videoFacesFailed! += v._count._all; + else c.videoFacesPending! += v._count._all; + } for (const r of recent) get(r.sourceId).perHour = r._count._all * 4; for (const f of files) { const c = get(f.sourceId); @@ -102,7 +110,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db nextScanAt: s.nextScanAt, lastError: s.lastError, loginUrl: loginUrl ?? archive.pendingLoginUrl(s), - counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, ...c }, + counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, videoFacesPending: 0, videoFacesDone: 0, videoFacesFailed: 0, ...c }, }); const loadSource = async (req: Parameters[1], sourceId: string, role: "EDITOR" | "ADMIN") => { diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index 80b5fb7..c4cfa52 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -1097,22 +1097,27 @@ export class FaceWorker { if (n) this.opts.log.info({ videos: n }, "faces: videos queued again"); } for (const id of await this.service.claimReferences(5)) await this.service.processReference(id); - const ids = await this.service.claim(this.opts.concurrency - this.inFlight); - for (const id of ids) { - this.inFlight++; - void this.service.process(id).finally(() => { - this.inFlight--; - }); - } - // Archive videos one at a time, when the photos leave room (a video is many frames). - if (!ids.length && this.videosInFlight === 0) { + // Archive videos one at a time, in one of the engine's places: with photos always arriving (a live game, + // the archive's backlog) a video waiting for the photos to stop would never start. With a single place the + // photos keep it, and a video waits until they leave it free. + const startVideo = async () => { for (const id of await this.service.claimVideos(1)) { this.videosInFlight++; void this.service.processVideo(id).finally(() => { this.videosInFlight--; }); } + }; + const shared = this.opts.concurrency > 1; + if (shared && this.videosInFlight === 0 && this.inFlight < this.opts.concurrency) await startVideo(); + const ids = await this.service.claim(this.opts.concurrency - this.inFlight - (shared ? this.videosInFlight : 0)); + for (const id of ids) { + this.inFlight++; + void this.service.process(id).finally(() => { + this.inFlight--; + }); } + if (!shared && !ids.length && this.inFlight === 0 && this.videosInFlight === 0) await startVideo(); } catch (err) { this.opts.log.warn({ err }, "faces: poll failed"); } finally { diff --git a/apps/api/src/faces/worker.test.ts b/apps/api/src/faces/worker.test.ts new file mode 100644 index 0000000..da8f02b --- /dev/null +++ b/apps/api/src/faces/worker.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { waitUntil } from "../lib/idle.js"; +import { FaceWorker, type FaceService } from "./service.js"; + +const quiet = { info() {}, warn() {}, error() {}, debug() {} } as never; + +/** A queue that never empties of photos (a live game, the archive's backlog) and has one video waiting. */ +function busyQueue() { + const running = { photos: 0, videos: 0, most: 0 }; + let videos = ["v1"]; + const finish = () => new Promise((r) => setTimeout(r, 20)); + const service = { + queueMissed: async () => 0, + requeueFailed: async () => 0, + requeueVideos: async () => 0, + requeueStale: async () => 0, + claimReferences: async () => [], + processReference: async () => {}, + claim: async (limit: number) => Array.from({ length: Math.max(0, limit) }, (_, i) => `p${i}`), + process: async () => { + running.photos++; + running.most = Math.max(running.most, running.photos + running.videos); + await finish(); + running.photos--; + }, + claimVideos: async (limit: number) => { + const out = videos.slice(0, limit); + videos = videos.slice(limit); + return out; + }, + processVideo: async () => { + running.videos++; + running.most = Math.max(running.most, running.photos + running.videos); + await finish(); + running.videos--; + started.push("v1"); + }, + stopVideos: () => {}, + }; + const started: string[] = []; + return { service: service as unknown as FaceService, running, started }; +} + +describe("the face worker", () => { + it("starts an archive video while photos keep arriving, in one of the engine's places", async () => { + const { service, running, started } = busyQueue(); + const worker = new FaceWorker(service, { concurrency: 3, intervalMs: 5, log: quiet }); + worker.start(); + expect(await waitUntil(() => started.length > 0, { timeoutMs: 2000 })).toBe(true); + await worker.stop(2000); + // Never more at once than the engine has places. + expect(running.most).toBeLessThanOrEqual(3); + }); + + it("with a single place, leaves it to the photos while they keep arriving", async () => { + const { service, started } = busyQueue(); + const worker = new FaceWorker(service, { concurrency: 1, intervalMs: 5, log: quiet }); + worker.start(); + await new Promise((r) => setTimeout(r, 200)); + await worker.stop(2000); + expect(started).toEqual([]); + }); +}); diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index 05185a0..de135e4 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -1557,6 +1557,8 @@ describe("archive from a Nextcloud", () => { for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id); const video = await ctx.db.cloudVideo.findFirstOrThrow(); expect(video).toMatchObject({ status: "DONE", facesStatus: "PENDING" }); + const facesCount = async () => (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/cloud-sources`, headers: bearer(token) })).json().sources[0].counts; + expect(await facesCount()).toMatchObject({ videoFacesPending: 1, videoFacesDone: 0 }); // Rita in the photos and the first second of the video; someone else from 0.8 s on, in the video only. const rita = unitVec(1); @@ -1592,6 +1594,7 @@ describe("archive from a Nextcloud", () => { const ritaGroup = await ctx.db.faceGroup.findUniqueOrThrow({ where: { id: photoFace.groupId! }, include: { suggested: true } }); expect(ritaGroup.suggested?.name).toBe("Rita Sousa"); expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("DONE"); + expect(await facesCount()).toMatchObject({ videoFacesPending: 0, videoFacesDone: 1, videoFacesFailed: 0 }); // An editor of the game's folder reviews it: the card carries the video's frame, and confirming names both. const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01"); diff --git a/docs/archive.md b/docs/archive.md index d09aa01..deea32a 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -171,7 +171,8 @@ Viewers: a gallery's first page carries its videos (`videos`, `videoTotal`), eac length; the player opens like the large photo, with "Descarregar" (the web copy) for everyone and the original's link on the cloud only for those who edit that folder. A gallery of videos only takes its first video's frame as cover. **Faces in videos** (organizations with face recognition on, like the photos): once a video's web copy is made its -`faces_status` is PENDING, and the face worker (after the photos, one video at a time) takes `ARCHIVE_VIDEO_FACE_FPS` +`faces_status` is PENDING, and the face worker (one video at a time, in one of the engine's places beside the photos, +so a steady flow of photos never keeps it waiting; with a single place, only when no photo is waiting) takes `ARCHIVE_VIDEO_FACE_FPS` frames a second (default 5) out of the web copy with ffmpeg and analyses each with the same engine and filters as a photo (size, focus, sharpness). The same face in consecutive frames (alike, and about where it was; missed for up to 1.5 s) is one appearance (`video_faces`: start, end, its clearest frame kept beside the web copy, the mean of its sharp @@ -180,7 +181,8 @@ confirming, "não é", false positives, recognition off and merging are the phot video appearances beside its photos' faces (the frame, signed: `/v1/files/video-faces/:id`); a group with videos can be changed only by a viewer who edits every folder its photos and videos are in. The gallery's videos carry who appears and when (`people`, with each moment), and a person's page lists the videos they are in: the player jumps to -each moment. A folder moved to another event has its videos' faces looked for again there. +each moment. A folder moved to another event has its videos' faces looked for again there. The app's archive counts +show how many videos are waiting for their faces (`videoFacesPending`), done and failed. ### Downloads