feat(comments): add printable comments page with frame thumbnails and markup overlays (#550)

* feat(comments): add printable comments page with frame thumbnails and markup overlays

* fix(comments): guarantee frame-accurate ffmpeg seeking for printable comment thumbnails

* fix(comments): address printable comments review findings
This commit is contained in:
Yiling-J
2026-11-25 19:53:39 +08:00
committed by GitHub
parent e32445684f
commit 5a1655e4ef
25 changed files with 3428 additions and 51 deletions
+52 -26
View File
@@ -2289,6 +2289,35 @@ export class AssetService {
})
}
private getCommentInclude() {
return {
creator: true,
completionLastChangedBy: true,
asset: { include: { storageKey: true } },
attachments: { include: { asset: { include: { storageKey: true } } } },
reactions: {
include: {
user: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'asc' as const },
},
replies: {
include: {
creator: true,
completionLastChangedBy: true,
attachments: { include: { asset: { include: { storageKey: true } } } },
reactions: {
include: {
user: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'asc' as const },
},
},
orderBy: { id: 'asc' as const },
},
}
}
async listComments(
assetId: string,
params: PaginationParams,
@@ -2300,32 +2329,7 @@ export class AssetService {
async (skip, take) => {
return this.prismaClient.assetComment.findMany({
where: { assetId: resolvedAssetId, replyToId: null },
include: {
creator: true,
completionLastChangedBy: true,
asset: { include: { storageKey: true } },
attachments: { include: { asset: { include: { storageKey: true } } } },
reactions: {
include: {
user: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'asc' },
},
replies: {
include: {
creator: true,
completionLastChangedBy: true,
attachments: { include: { asset: { include: { storageKey: true } } } },
reactions: {
include: {
user: { select: { id: true, name: true } },
},
orderBy: { createdAt: 'asc' },
},
},
orderBy: { id: 'asc' },
},
},
include: this.getCommentInclude(),
skip,
take,
orderBy: { id: 'asc' },
@@ -2343,6 +2347,28 @@ export class AssetService {
return { data: infos, pageInfo }
}
async listAllComments(assetId: string, requestingUserId?: string): Promise<CommentInfo[]> {
const resolvedAssetId = await this.resolveLatestVersionId(assetId)
const comments = await this.prismaClient.assetComment.findMany({
where: { assetId: resolvedAssetId, replyToId: null },
include: this.getCommentInclude(),
orderBy: { id: 'asc' },
})
return Promise.all(comments.map((c) => this.toCommentInfo(c, requestingUserId)))
}
async getProjectNameForAsset(assetId: string): Promise<string | null> {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
select: {
project: { select: { name: true } },
},
})
return asset?.project?.name ?? null
}
async exportComments(
assetId: string,
format: CommentExportFormat,
@@ -0,0 +1,738 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { prisma, AssetType, AssetStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { s3Service } from '@shumai/core/src/s3/s3'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { assetService } from '@shumai/core/src/asset/asset'
import {
CommentFrameService,
FrameExtractionQueue,
selectBestVideoProxyKey,
type ExecFileFn,
} from './comment-frame'
import { execFileSync } from 'child_process'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import sharp from 'sharp'
async function createSamplePngBuffer(): Promise<Buffer> {
return sharp({
create: {
width: 32,
height: 18,
channels: 3,
background: { r: 20, g: 120, b: 220 },
},
})
.png()
.toBuffer()
}
async function createSampleWebpBuffer(): Promise<Buffer> {
return sharp({
create: {
width: 32,
height: 18,
channels: 3,
background: { r: 220, g: 80, b: 40 },
},
})
.webp()
.toBuffer()
}
describe('FrameExtractionQueue', () => {
it('enforces maxConcurrency and processes queued tasks in FIFO order', async () => {
const queue = new FrameExtractionQueue(2)
let active = 0
let maxObserved = 0
const order: number[] = []
const resolvers: Array<() => void> = []
const makeTask = (id: number) =>
queue.enqueue(async () => {
active++
maxObserved = Math.max(maxObserved, active)
order.push(id)
await new Promise<void>((resolve) => resolvers.push(resolve))
active--
return id
})
const p1 = makeTask(1)
const p2 = makeTask(2)
const p3 = makeTask(3)
const p4 = makeTask(4)
expect(queue.activeCount).toBe(2)
expect(queue.queuedCount).toBe(2)
expect(maxObserved).toBe(2)
resolvers.shift()?.()
await p1
expect(queue.activeCount).toBe(2)
expect(queue.queuedCount).toBe(1)
resolvers.shift()?.()
await p2
expect(queue.activeCount).toBe(2)
expect(queue.queuedCount).toBe(0)
resolvers.shift()?.()
await p3
resolvers.shift()?.()
await p4
expect(order).toEqual([1, 2, 3, 4])
expect(maxObserved).toBe(2)
expect(queue.activeCount).toBe(0)
expect(queue.queuedCount).toBe(0)
})
it('cancels queued tasks when their AbortSignal fires before execution', async () => {
const queue = new FrameExtractionQueue(1)
let releaseFirst!: () => void
const first = queue.enqueue(
() =>
new Promise<string>((resolve) => {
releaseFirst = () => resolve('first')
}),
)
const controller = new AbortController()
const runSecond = vi.fn().mockResolvedValue('second')
const second = queue.enqueue(runSecond, controller.signal)
expect(queue.queuedCount).toBe(1)
controller.abort()
await expect(second).rejects.toThrow('Frame extraction aborted')
expect(queue.queuedCount).toBe(0)
expect(runSecond).not.toHaveBeenCalled()
releaseFirst()
await expect(first).resolves.toBe('first')
})
})
describe('selectBestVideoProxyKey', () => {
it('prefers SDR proxies over HDR and chooses lowest adequate resolution >= 360p', () => {
const key = selectBestVideoProxyKey([
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
{ key: 'sdr-1080.mp4', width: 1920, height: 1080, hdr: false, resolution: '1080p' },
{ key: 'sdr-540.mp4', width: 960, height: 540, hdr: false, resolution: '540p' },
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
])
expect(key).toBe('sdr-540.mp4')
})
it('falls back to highest available SDR proxy if all are below 360p', () => {
const key = selectBestVideoProxyKey([
{ key: 'sdr-180.mp4', width: 320, height: 180, hdr: false, resolution: '180p' },
{ key: 'sdr-240.mp4', width: 426, height: 240, hdr: false, resolution: '240p' },
])
expect(key).toBe('sdr-240.mp4')
})
it('falls back to HDR proxy if no SDR proxy exists', () => {
const key = selectBestVideoProxyKey([
{ key: 'hdr-1080.mp4', width: 1920, height: 1080, hdr: true, resolution: '1080p' },
{ key: 'hdr-720.mp4', width: 1280, height: 720, hdr: true, resolution: '720p' },
])
expect(key).toBe('hdr-720.mp4')
})
it('returns null when no valid keys exist', () => {
expect(selectBestVideoProxyKey([])).toBeNull()
expect(selectBestVideoProxyKey(null)).toBeNull()
})
})
describe('CommentFrameService & AssetService print helpers', () => {
setupTestDbHooks()
let userId: string
let teamId: string
let projectId: string
let rootFolderId: string
let subFolderId: string
beforeEach(async () => {
const user = await prisma.user.create({
data: {
name: 'Alice',
email: `alice-${Date.now()}-${Math.random()}@example.com`,
},
})
userId = user.id
const team = await prisma.team.create({
data: {
name: 'Studio Team',
},
})
teamId = team.id
const rootFolder = await prisma.asset.create({
data: {
name: 'root',
type: AssetType.root,
status: AssetStatus.processed,
creatorId: userId,
},
})
rootFolderId = rootFolder.id
const project = await prisma.project.create({
data: {
name: 'Commercial Cut',
teamId,
rootFolderId,
},
})
projectId = project.id
await prisma.asset.update({
where: { id: rootFolderId },
data: { projectId },
})
const subFolder = await prisma.asset.create({
data: {
name: 'Dailies',
type: AssetType.folder,
status: AssetStatus.processed,
projectId,
parentId: rootFolderId,
creatorId: userId,
},
})
subFolderId = subFolder.id
})
afterEach(() => {
vi.restoreAllMocks()
})
it('skips extraction when the request is aborted during asset lookup', async () => {
const storageKey = await prisma.storageKey.create({ data: { key: 'files/clip.mp4' } })
const asset = await prisma.asset.create({
data: {
name: 'clip.mp4',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
},
})
const controller = new AbortController()
const resolveLatestVersionId = assetService.resolveLatestVersionId.bind(assetService)
vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementationOnce(async (assetId) => {
const resolvedId = await resolveLatestVersionId(assetId)
controller.abort()
return resolvedId
})
const resolveInput = vi.spyOn(s3Service, 'resolveInput').mockResolvedValue('/local/clip.mp4')
const execFileFn = vi.fn<ExecFileFn>().mockResolvedValue({ stdout: '', stderr: '' })
const service = new CommentFrameService({ execFileFn })
await expect(
service.extractFrame({ assetId: asset.id, second: 0, signal: controller.signal }),
).rejects.toMatchObject({ name: 'AbortError' })
expect(resolveInput).not.toHaveBeenCalled()
expect(execFileFn).not.toHaveBeenCalled()
})
it('extracts a video frame using the lowest adequate SDR proxy and deduplicates concurrent requests', async () => {
const webpBuffer = await createSampleWebpBuffer()
const storageKey = await prisma.storageKey.create({
data: { key: 'files/video-original.mp4' },
})
const videoAsset = await prisma.asset.create({
data: {
name: 'scene1.mp4',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
media: {
proxyType: 'video',
duration: 10,
filesize: 1000,
frames: 240,
imageTranscodes: [],
videoTranscodes: [
{ key: 'files/proxies/1080p.mp4', width: 1920, height: 1080, hdr: false },
{ key: 'files/proxies/540p.mp4', width: 960, height: 540, hdr: false },
{ key: 'files/proxies/720p-hdr.mp4', width: 1280, height: 720, hdr: true },
],
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const resolveInputSpy = vi
.spyOn(s3Service, 'resolveInput')
.mockResolvedValue('/local/files/proxies/540p.mp4')
let releaseExec!: () => void
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
await new Promise<void>((resolve) => {
releaseExec = resolve
})
const outPath = args[args.length - 1]
fs.writeFileSync(outPath, webpBuffer)
return { stdout: '', stderr: '' }
})
const service = new CommentFrameService({ maxConcurrency: 2, execFileFn: execFileMock })
const p1 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
const p2 = service.extractFrame({ assetId: videoAsset.id, second: 2.5, width: 400 })
// Let async DB lookup finish before releasing exec
await vi.waitFor(() => expect(execFileMock).toHaveBeenCalledTimes(1))
releaseExec()
const [r1, r2] = await Promise.all([p1, p2])
expect(r1.mimeType).toBe('image/webp')
expect(r1.buffer.equals(webpBuffer)).toBe(true)
expect(r2.buffer.equals(webpBuffer)).toBe(true)
expect(execFileMock).toHaveBeenCalledTimes(1)
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/proxies/540p.mp4')
})
it('extracts a 3D model turntable frame and enforces watermark-only proxies when watermarkConfigId is set', async () => {
const webpBuffer = await createSampleWebpBuffer()
const storageKey = await prisma.storageKey.create({
data: { key: 'files/chair.glb' },
})
const modelAsset = await prisma.asset.create({
data: {
name: 'chair.glb',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'model/gltf-binary',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
media: {
proxyType: '3d',
duration: 24,
filesize: 2000,
frames: 24,
imageTranscodes: [],
videoTranscodes: [{ key: 'files/proxies/turntable.mp4', width: 1024, height: 1024 }],
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const watermarkSpy = vi
.spyOn(watermarkService, 'getCompletedWatermarkMediaMap')
.mockResolvedValueOnce(
new Map([
[
modelAsset.id,
{
proxyType: '3d',
duration: 24,
filesize: 2000,
frames: 24,
imageTranscodes: [],
videoTranscodes: [{ key: 'files/wm/turntable-wm.mp4', width: 1024, height: 1024 }],
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
],
]),
)
.mockResolvedValueOnce(new Map())
const resolveInputSpy = vi
.spyOn(s3Service, 'resolveInput')
.mockResolvedValue('/local/files/wm/turntable-wm.mp4')
const execFileMock = vi.fn<ExecFileFn>(async (_file, args) => {
const outPath = args[args.length - 1]
fs.writeFileSync(outPath, webpBuffer)
return { stdout: '', stderr: '' }
})
const service = new CommentFrameService({ execFileFn: execFileMock })
const res = await service.extractFrame({
assetId: modelAsset.id,
second: 3,
width: 400,
watermarkConfigId: 'wm-cfg-1',
})
expect(res.mimeType).toBe('image/webp')
expect(watermarkSpy).toHaveBeenCalledWith([modelAsset.id], 'wm-cfg-1')
expect(resolveInputSpy).toHaveBeenCalledWith(expect.any(String), 'files/wm/turntable-wm.mp4')
// Missing watermark proxy must reject with 422 rather than leaking unwatermarked media
await expect(
service.extractFrame({
assetId: modelAsset.id,
second: 3,
width: 400,
watermarkConfigId: 'wm-cfg-2',
}),
).rejects.toMatchObject({ status: 422 })
})
it('renders a PDF page frame via pdftoppm and sharp', async () => {
const samplePng = await createSamplePngBuffer()
const storageKey = await prisma.storageKey.create({
data: { key: 'files/deck.pdf' },
})
const pdfAsset = await prisma.asset.create({
data: {
name: 'deck.pdf',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'application/pdf',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
media: {
proxyType: 'pdf',
duration: 0,
filesize: 5000,
frames: 5,
imageTranscodes: [],
videoTranscodes: [],
pdfTranscode: { key: 'files/proxies/deck.pdf' },
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const downloadSpy = vi
.spyOn(s3Service, 'downloadToFile')
.mockImplementation(async (_bucket, _key, dest) => {
fs.writeFileSync(dest, '%PDF-1.4 mock')
})
const execFileMock = vi.fn<ExecFileFn>(async (file, args) => {
expect(file).toBe('pdftoppm')
expect(args[args.indexOf('-scale-to') + 1]).toBe('400')
expect(args).toContain('-f')
expect(args).toContain('3')
const prefix = args[args.length - 1]
fs.writeFileSync(`${prefix}-3.png`, samplePng)
return { stdout: '', stderr: '' }
})
const service = new CommentFrameService({ execFileFn: execFileMock })
const res = await service.extractFrame({ assetId: pdfAsset.id, second: 3, width: 400 })
expect(downloadSpy).toHaveBeenCalledWith(
expect.any(String),
'files/proxies/deck.pdf',
expect.stringContaining(path.sep),
)
expect(res.mimeType).toBe('image/webp')
expect(res.buffer.length).toBeGreaterThan(0)
})
it('rejects unsupported asset types with 400 and archived assets without proxy with 422', async () => {
const imgKey = await prisma.storageKey.create({
data: { key: 'files/photo.png' },
})
const imageAsset = await prisma.asset.create({
data: {
name: 'photo.png',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'image/png',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: imgKey.id,
media: {
proxyType: 'image',
duration: 0,
filesize: 100,
frames: 1,
imageTranscodes: [],
videoTranscodes: [],
finishedAt: new Date().toISOString(),
metadata: null,
original: null,
},
},
})
const archivedKey = await prisma.storageKey.create({
data: { key: 'files/archived.mp4', isArchived: true },
})
const archivedVideo = await prisma.asset.create({
data: {
name: 'archived.mp4',
type: AssetType.file,
status: AssetStatus.archived,
mediaType: 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: archivedKey.id,
},
})
const service = new CommentFrameService()
await expect(service.extractFrame({ assetId: imageAsset.id, second: 0 })).rejects.toMatchObject(
{ status: 400 },
)
await expect(
service.extractFrame({ assetId: archivedVideo.id, second: 1 }),
).rejects.toMatchObject({ status: 422 })
await expect(
service.extractFrame({ assetId: 'non-existent-id', second: 0 }),
).rejects.toMatchObject({ status: 404 })
})
it('lists all comments with replies, reactions, completion status, and fetches project name', async () => {
vi.spyOn(s3Service, 'presign').mockResolvedValue('http://mock-s3/file')
const storageKey = await prisma.storageKey.create({
data: { key: 'files/cut.mp4' },
})
const asset = await prisma.asset.create({
data: {
name: 'cut.mp4',
type: AssetType.file,
status: AssetStatus.processed,
mediaType: 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: storageKey.id,
},
})
const parent = await prisma.assetComment.create({
data: {
assetId: asset.id,
creatorId: userId,
message: 'Check lighting',
second: 1.5,
isCompleted: true,
completionLastChangedById: userId,
},
})
await prisma.assetCommentReaction.create({
data: { commentId: parent.id, userId, code: '👍' },
})
await prisma.assetComment.create({
data: {
assetId: asset.id,
creatorId: userId,
replyToId: parent.id,
message: 'Fixed in v2',
},
})
const allComments = await assetService.listAllComments(asset.id, userId)
expect(allComments).toHaveLength(1)
expect(allComments[0].message).toBe('Check lighting')
expect(allComments[0].isCompleted).toBe(true)
expect(allComments[0].reactionCounts).toEqual([
expect.objectContaining({ code: '👍', count: 1, requestingUserReacted: true }),
])
expect(allComments[0].replies).toHaveLength(1)
expect(allComments[0].replies[0].message).toBe('Fixed in v2')
const projectName = await assetService.getProjectNameForAsset(asset.id)
expect(projectName).toBe('Commercial Cut')
})
it('extracts exact frames with real ffmpeg for 30fps video, 23.976fps video, and 6fps 3D turntable', async () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-frame-acc-'))
const w = 64
const h = 64
const createColorCodedVideo = (filename: string, rateArg: string, totalFrames: number) => {
const raw = Buffer.alloc(w * h * 3 * totalFrames)
for (let n = 0; n < totalFrames; n++) {
const r = (n * 9) & 255
const g = (n * 15) & 255
const off = n * w * h * 3
for (let i = 0; i < w * h; i++) {
raw[off + i * 3] = r
raw[off + i * 3 + 1] = g
raw[off + i * 3 + 2] = 120
}
}
const rawPath = path.join(tmpDir, `${filename}.rgb`)
const mp4Path = path.join(tmpDir, `${filename}.mp4`)
fs.writeFileSync(rawPath, raw)
execFileSync('ffmpeg', [
'-y',
'-loglevel',
'error',
'-f',
'rawvideo',
'-pix_fmt',
'rgb24',
'-s',
`${w}x${h}`,
'-r',
rateArg,
'-i',
rawPath,
'-c:v',
'libx264',
'-pix_fmt',
'yuv420p',
'-g',
'12',
'-bf',
'2',
'-movflags',
'+faststart',
mp4Path,
])
return mp4Path
}
const identifyExtractedFrame = async (webpBuffer: Buffer, totalFrames: number) => {
const { data, info } = await sharp(webpBuffer).raw().toBuffer({ resolveWithObject: true })
const cx = Math.floor(info.width / 2)
const cy = Math.floor(info.height / 2)
const idx = (cy * info.width + cx) * info.channels
const r = data[idx]
const g = data[idx + 1]
let best = -1
let bestDist = Infinity
for (let n = 0; n < totalFrames; n++) {
const dr = r - ((n * 9) & 255)
const dg = g - ((n * 15) & 255)
const dist = dr * dr + dg * dg
if (dist < bestDist) {
bestDist = dist
best = n
}
}
return best
}
try {
const mp4Fps30 = createColorCodedVideo('v30', '30', 24)
const mp4Fps23976 = createColorCodedVideo('v23976', '24000/1001', 24)
const mp4Turntable = createColorCodedVideo('turntable', '6', 24)
const keyMap: Record<string, string> = {
'files/proxies/v30.mp4': mp4Fps30,
'files/proxies/v23976.mp4': mp4Fps23976,
'files/proxies/turntable.mp4': mp4Turntable,
}
vi.spyOn(s3Service, 'resolveInput').mockImplementation(async (_bucket, key) => keyMap[key])
const createAsset = async (
name: string,
proxyType: 'video' | '3d',
proxyKey: string,
fps: number,
totalFrames: number,
) => {
const sk = await prisma.storageKey.create({ data: { key: `files/${name}` } })
return prisma.asset.create({
data: {
name,
type: AssetType.file,
status: AssetStatus.processed,
mediaType: proxyType === '3d' ? 'model/gltf-binary' : 'video/mp4',
projectId,
parentId: subFolderId,
creatorId: userId,
storageKeyId: sk.id,
media: {
proxyType,
duration: totalFrames / fps,
filesize: 1000,
frames: totalFrames,
imageTranscodes: [],
videoTranscodes: [{ key: proxyKey, width: 64, height: 64, hdr: false }],
finishedAt: new Date().toISOString(),
metadata: {
originalHeight: h,
originalWidth: w,
hasAudio: false,
bitRate: 100000,
frameRate: fps,
totalFrames,
duration: totalFrames / fps,
startTimecode: '00:00:00:00',
format: {},
},
original: null,
},
},
})
}
const asset30 = await createAsset('v30.mp4', 'video', 'files/proxies/v30.mp4', 30, 24)
const asset23976 = await createAsset(
'v23976.mp4',
'video',
'files/proxies/v23976.mp4',
24000 / 1001,
24,
)
const asset3d = await createAsset('chair.glb', '3d', 'files/proxies/turntable.mp4', 6, 24)
const realService = new CommentFrameService({ maxConcurrency: 2 })
// Frames where .toFixed(4) previously rounded UP and skipped to N+1:
// 30fps: frame 2 (0.06666... -> 0.0667), frame 5 (0.16666... -> 0.1667), frame 23 (last frame)
for (const frame of [0, 2, 5, 8, 17, 23]) {
const res = await realService.extractFrame({
assetId: asset30.id,
second: frame / 30,
width: 64,
})
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
}
// 23.976fps: frame 7 (0.291958 -> 0.2920), frame 8, frame 19, frame 23
for (const frame of [0, 7, 8, 19, 23]) {
const res = await realService.extractFrame({
assetId: asset23976.id,
second: frame / (24000 / 1001),
width: 64,
})
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
}
// 3D 6fps turntable where model-viewer stores center times ((N + 0.5) / 6, last = (23 + 0.25) / 6)
for (const frame of [0, 1, 6, 12, 23]) {
const centerSec = frame === 23 ? (frame + 0.25) / 6 : (frame + 0.5) / 6
const res = await realService.extractFrame({
assetId: asset3d.id,
second: centerSec,
width: 64,
})
expect(await identifyExtractedFrame(res.buffer, 24)).toBe(frame)
}
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true })
}
})
})
+557
View File
@@ -0,0 +1,557 @@
import { assetService } from '@shumai/core/src/asset/asset'
import { logger } from '@shumai/core/src/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import { secondToTurntableFrame, TURNTABLE_FPS } from '@shumai/core/src/utils/model3d'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { prisma } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { execFile } from 'child_process'
import * as fs from 'fs'
import { HTTPException } from 'hono/http-exception'
import * as os from 'os'
import * as path from 'path'
import sharp from 'sharp'
import { ulid } from 'ulid'
import { promisify } from 'util'
const execFileAsync = promisify(execFile)
const DEFAULT_CONCURRENCY = 4
const DEFAULT_FRAME_TIMEOUT_MS = 30_000
const MIN_PREFERRED_PROXY_HEIGHT = 360
export interface ExtractCommentFrameParams {
assetId: string
second: number
width?: number
watermarkConfigId?: string | null
signal?: AbortSignal
}
export interface ExtractCommentFrameResult {
buffer: Buffer
mimeType: string
}
export type ExecFileFn = (
file: string,
args: string[],
options?: { signal?: AbortSignal; timeout?: number },
) => Promise<{ stdout: string | Buffer; stderr: string | Buffer }>
interface QueuedTask<T> {
run: () => Promise<T>
resolve: (value: T) => void
reject: (err: unknown) => void
signal?: AbortSignal
onAbort?: () => void
}
/**
* Bounded FIFO concurrency queue dedicated to on-demand comment frame extraction,
* isolated from background transcode workers so print requests stay fast without
* overloading the main API server.
*/
export class FrameExtractionQueue {
private running = 0
private readonly pending: QueuedTask<unknown>[] = []
constructor(private readonly maxConcurrency: number) {}
get activeCount(): number {
return this.running
}
get queuedCount(): number {
return this.pending.length
}
enqueue<T>(run: () => Promise<T>, signal?: AbortSignal): Promise<T> {
if (signal?.aborted) {
return Promise.reject(new DOMException('Frame extraction aborted', 'AbortError'))
}
return new Promise<T>((resolve, reject) => {
const task: QueuedTask<T> = { run, resolve, reject, signal }
if (signal) {
const onAbort = () => {
const idx = this.pending.indexOf(task as QueuedTask<unknown>)
if (idx !== -1) {
this.pending.splice(idx, 1)
signal.removeEventListener('abort', onAbort)
reject(new DOMException('Frame extraction aborted', 'AbortError'))
}
}
task.onAbort = onAbort
signal.addEventListener('abort', onAbort, { once: true })
}
this.pending.push(task as QueuedTask<unknown>)
this.drain()
})
}
private drain(): void {
while (this.running < this.maxConcurrency && this.pending.length > 0) {
const task = this.pending.shift()
if (!task) break
if (task.signal && task.onAbort) {
task.signal.removeEventListener('abort', task.onAbort)
}
if (task.signal?.aborted) {
task.reject(new DOMException('Frame extraction aborted', 'AbortError'))
continue
}
this.running++
task.run().then(
(result) => {
this.running--
this.drain()
task.resolve(result)
},
(err) => {
this.running--
this.drain()
task.reject(err)
},
)
}
}
}
/**
* Picks the fastest video proxy suitable for thumbnail extraction:
* 1. Prefer SDR proxies over HDR to avoid washed-out colors.
* 2. Among SDR proxies, pick the lowest resolution that is still >= 360p (fast seek + decode
* for a ~400px thumbnail). If none are >= 360p, pick the highest available SDR proxy.
*/
export function selectBestVideoProxyKey(
videoTranscodes?: PrismaJson.VideoTranscode[] | null,
): string | null {
if (!videoTranscodes || videoTranscodes.length === 0) return null
const valid = videoTranscodes.filter((t) => Boolean(t.key))
if (valid.length === 0) return null
const sdr = valid.filter((t) => !t.hdr)
const pool = sdr.length > 0 ? sdr : valid
const adequate = pool
.filter((t) => (t.height || 0) >= MIN_PREFERRED_PROXY_HEIGHT)
.sort((a, b) => (a.height || 0) - (b.height || 0))
if (adequate.length > 0) {
return adequate[0].key ?? null
}
const fallback = [...pool].sort((a, b) => (b.height || 0) - (a.height || 0))
return fallback[0]?.key ?? null
}
/**
* Resolves an ffmpeg `-ss` input seek timestamp that lands squarely on the exact
* target frame displayed by Shumai's video and 3D turntable players.
*
* `ffmpeg -ss T -i input -vframes 1` outputs the first frame with `PTS >= T`.
* Passing `N / fps` directly (especially after decimal rounding) or a frame center
* `(N + 0.5) / fps` causes ffmpeg to skip frame `N` and emit frame `N + 1` whenever
* `T` exceeds `PTS(N)` by even 1µs.
*
* Instead, we recover integer frame `N` with the exact player formula
* (`Math.floor(second * fps + 0.45)` for video, `secondToTurntableFrame` for 3D)
* and seek to the midpoint between frame `N - 1` and frame `N`: `(N - 0.5) / fps`,
* leaving a full ±0.5 frame tolerance margin on both sides.
*/
export function resolveFrameAccurateSeek(params: {
second: number
proxyType: 'video' | '3d'
frameRate?: number | null
totalFrames?: number | null
duration?: number | null
}): { seekTime: number; frameIndex: number | null } {
const safeSecond = Math.max(0, params.second)
if (params.proxyType === '3d') {
const frameIndex = secondToTurntableFrame(safeSecond)
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / TURNTABLE_FPS
return { seekTime, frameIndex }
}
const fps = params.frameRate && params.frameRate > 0 ? params.frameRate : null
if (fps) {
let frameIndex = Math.max(0, Math.floor(safeSecond * fps + 0.45))
if (params.totalFrames && params.totalFrames > 0) {
frameIndex = Math.min(frameIndex, params.totalFrames - 1)
} else if (params.duration && params.duration > 0) {
const maxFrame = Math.max(0, Math.round(params.duration * fps) - 1)
frameIndex = Math.min(frameIndex, maxFrame)
}
const seekTime = frameIndex <= 0 ? 0 : (frameIndex - 0.5) / fps
return { seekTime, frameIndex }
}
const seekTime =
params.duration && params.duration > 0 && safeSecond >= params.duration
? Math.max(0, params.duration - 0.05)
: safeSecond
return { seekTime, frameIndex: null }
}
export class CommentFrameService {
private readonly queue: FrameExtractionQueue
private readonly inFlight = new Map<
string,
{
promise: Promise<ExtractCommentFrameResult>
controller: AbortController
waiters: number
}
>()
private readonly execFileFn: ExecFileFn
private readonly timeoutMs: number
constructor(options?: { maxConcurrency?: number; timeoutMs?: number; execFileFn?: ExecFileFn }) {
const envConcurrency = Number(process.env.PRINT_FRAME_CONCURRENCY)
const maxConcurrency =
options?.maxConcurrency ??
(Number.isInteger(envConcurrency) && envConcurrency > 0
? envConcurrency
: DEFAULT_CONCURRENCY)
this.queue = new FrameExtractionQueue(maxConcurrency)
this.timeoutMs = options?.timeoutMs ?? DEFAULT_FRAME_TIMEOUT_MS
this.execFileFn =
options?.execFileFn ??
((file, args, opts) =>
execFileAsync(file, args, {
signal: opts?.signal,
timeout: opts?.timeout,
maxBuffer: 10 * 1024 * 1024,
}))
}
async extractFrame(params: ExtractCommentFrameParams): Promise<ExtractCommentFrameResult> {
if (params.signal?.aborted) {
throw new DOMException('Frame extraction aborted', 'AbortError')
}
const width = Math.max(64, Math.min(1280, Math.round(params.width ?? 400)))
const second = Math.max(0, params.second)
const targetAssetId = await assetService.resolveLatestVersionId(params.assetId)
const asset = await prisma.asset.findUnique({
where: { id: targetAssetId },
include: { storageKey: true },
})
params.signal?.throwIfAborted()
if (!asset || asset.isDeleted) {
throw new HTTPException(404, { message: 'Asset not found' })
}
const media = asset.media as PrismaJson.MediaInfo | null
const proxyType = media?.proxyType ?? this.inferProxyType(asset.mediaType)
if (proxyType !== 'video' && proxyType !== '3d' && proxyType !== 'pdf') {
throw new HTTPException(400, {
message: 'Frame extraction is only supported for video, 3D model, and PDF assets',
})
}
const frameTarget =
proxyType === 'pdf'
? null
: resolveFrameAccurateSeek({
second,
proxyType,
frameRate: media?.metadata?.frameRate,
totalFrames: media?.metadata?.totalFrames ?? media?.frames,
duration: media?.duration ?? media?.metadata?.duration,
})
const normalizedKeyTime =
proxyType === 'pdf'
? `p${Math.max(1, Math.round(second))}`
: frameTarget!.frameIndex !== null
? `f${frameTarget!.frameIndex}`
: frameTarget!.seekTime.toFixed(6)
const dedupeKey = `${targetAssetId}:${params.watermarkConfigId ?? ''}:${normalizedKeyTime}:${width}`
let entry = this.inFlight.get(dedupeKey)
if (!entry) {
const controller = new AbortController()
const promise = this.queue
.enqueue(async () => {
if (proxyType === 'pdf') {
return this.extractPdfPageFrame({
asset,
media,
page: Math.max(1, Math.round(second)),
width,
signal: controller.signal,
})
}
return this.extractVideoFrame({
asset,
media,
second,
seekTime: frameTarget!.seekTime,
frameRate: proxyType === '3d' ? TURNTABLE_FPS : media?.metadata?.frameRate,
width,
watermarkConfigId: params.watermarkConfigId,
signal: controller.signal,
})
}, controller.signal)
.finally(() => {
if (this.inFlight.get(dedupeKey)?.promise === promise) {
this.inFlight.delete(dedupeKey)
}
})
entry = { promise, controller, waiters: 0 }
this.inFlight.set(dedupeKey, entry)
}
entry.waiters++
const currentEntry = entry
if (!params.signal) {
return currentEntry.promise.finally(() => {
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
})
}
return new Promise<ExtractCommentFrameResult>((resolve, reject) => {
let settled = false
const cleanup = () => {
params.signal?.removeEventListener('abort', onAbort)
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
if (currentEntry.waiters === 0) {
currentEntry.controller.abort()
}
}
const onAbort = () => {
if (settled) return
settled = true
cleanup()
reject(new DOMException('Frame extraction aborted', 'AbortError'))
}
params.signal!.addEventListener('abort', onAbort, { once: true })
currentEntry.promise.then(
(res) => {
if (settled) return
settled = true
params.signal?.removeEventListener('abort', onAbort)
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
resolve(res)
},
(err) => {
if (settled) return
settled = true
params.signal?.removeEventListener('abort', onAbort)
currentEntry.waiters = Math.max(0, currentEntry.waiters - 1)
reject(err)
},
)
})
}
private inferProxyType(mediaType: string | null): PrismaJson.MediaInfo['proxyType'] | undefined {
const lower = (mediaType || '').toLowerCase()
if (lower.startsWith('video/')) return 'video'
if (lower === 'application/pdf') return 'pdf'
if (lower.startsWith('image/')) return 'image'
if (lower.startsWith('audio/')) return 'audio'
return undefined
}
private async extractVideoFrame(params: {
asset: {
id: string
status: string
storageKey: { key: string; isArchived: boolean } | null
}
media: PrismaJson.MediaInfo | null
second: number
seekTime: number
frameRate?: number | null
width: number
watermarkConfigId?: string | null
signal?: AbortSignal
}): Promise<ExtractCommentFrameResult> {
const bucket = process.env.S3_BUCKET || 'shumai'
let targetKey: string | null
if (params.watermarkConfigId) {
const wfMap = await watermarkService.getCompletedWatermarkMediaMap(
[params.asset.id],
params.watermarkConfigId,
)
const watermarkMedia = wfMap.get(params.asset.id) ?? null
targetKey = selectBestVideoProxyKey(watermarkMedia?.videoTranscodes)
if (!targetKey) {
throw new HTTPException(422, {
message: 'Watermarked proxy is not ready for this asset',
})
}
} else {
targetKey = selectBestVideoProxyKey(params.media?.videoTranscodes)
if (!targetKey) {
const originalKey = params.asset.storageKey?.key
const isArchived =
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
if (!originalKey || isArchived) {
throw new HTTPException(422, {
message: 'Original video file is archived and no proxy is available',
})
}
targetKey = originalKey
}
}
const inputSource = await s3Service.resolveInput(bucket, targetKey)
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-frame-'))
try {
const outPath = path.join(tmpDir, `frame-${ulid()}.webp`)
const runFfmpeg = async (timestamp: number) => {
const args = [
'-y',
'-loglevel',
'warning',
...(isRemote
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
: []),
'-ss',
timestamp.toFixed(6),
'-i',
inputSource,
'-map',
'0:V:0',
'-vframes',
'1',
'-vf',
`scale=${params.width}:-2:force_original_aspect_ratio=decrease`,
'-c:v',
'libwebp',
'-q:v',
'80',
outPath,
]
await this.execFileFn('ffmpeg', args, {
signal: params.signal,
timeout: this.timeoutMs,
})
}
await runFfmpeg(params.seekTime)
// If container metadata overestimated totalFrames at EOF, step back one frame and retry.
if ((!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) && params.seekTime > 0) {
const stepBack = params.frameRate && params.frameRate > 0 ? 1 / params.frameRate : 0.1
await runFfmpeg(Math.max(0, params.seekTime - stepBack))
}
if (!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) {
throw new HTTPException(404, { message: 'Could not extract frame at requested timestamp' })
}
const buffer = fs.readFileSync(outPath)
return { buffer, mimeType: 'image/webp' }
} catch (err) {
if (err instanceof HTTPException) throw err
if ((err as { name?: string })?.name === 'AbortError') throw err
logger.error(
{ assetId: params.asset.id, second: params.second, err },
'Failed to extract video comment frame',
)
throw new HTTPException(500, { message: 'Failed to extract video frame' })
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true })
}
}
private async extractPdfPageFrame(params: {
asset: {
id: string
status: string
storageKey: { key: string; isArchived: boolean } | null
}
media: PrismaJson.MediaInfo | null
page: number
width: number
signal?: AbortSignal
}): Promise<ExtractCommentFrameResult> {
const bucket = process.env.S3_BUCKET || 'shumai'
const proxyKey = params.media?.pdfTranscode?.key
const originalKey = params.asset.storageKey?.key
const isArchived =
Boolean(params.asset.storageKey?.isArchived) || params.asset.status === 'archived'
let targetKey: string | null = proxyKey || null
if (!targetKey) {
if (!originalKey || isArchived) {
throw new HTTPException(422, {
message: 'Original PDF file is archived and no proxy is available',
})
}
targetKey = originalKey
}
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shumai-print-pdf-'))
try {
const pdfPath = path.join(tmpDir, 'source.pdf')
await s3Service.downloadToFile(bucket, targetKey, pdfPath)
const pagePrefix = path.join(tmpDir, 'page')
await this.execFileFn(
'pdftoppm',
[
'-png',
'-scale-to',
String(params.width),
'-f',
String(params.page),
'-l',
String(params.page),
pdfPath,
pagePrefix,
],
{
signal: params.signal,
timeout: this.timeoutMs,
},
)
const pngFile = fs.readdirSync(tmpDir).find((f) => f.endsWith('.png'))
if (!pngFile) {
throw new HTTPException(404, { message: `PDF page ${params.page} not found` })
}
const buffer = await sharp(path.join(tmpDir, pngFile), {
limitInputPixels: (params.width + 1) ** 2,
})
.toColorspace('srgb')
.webp({ quality: 82 })
.toBuffer()
return { buffer, mimeType: 'image/webp' }
} catch (err) {
if (err instanceof HTTPException) throw err
if ((err as { name?: string })?.name === 'AbortError') throw err
logger.error(
{ assetId: params.asset.id, page: params.page, err },
'Failed to render PDF comment page frame',
)
throw new HTTPException(500, { message: 'Failed to render PDF page' })
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true })
}
}
}
export const commentFrameService = new CommentFrameService()
+1
View File
@@ -5,6 +5,7 @@ export * from './asset/auto-archive-job'
export * from './auth/auth'
export * from './authz/authz'
export * from './collection/collection'
export * from './comment/comment-frame'
export * from './invite/invite'
export * from './metadata/metadata'
export * from './notification/index'