2026-06-09 11:20:41 +08:00
|
|
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
2026-07-19 09:45:14 +08:00
|
|
|
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
2026-06-09 11:20:41 +08:00
|
|
|
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
2026-06-01 23:08:58 +08:00
|
|
|
import '@shumai/db/src/prisma-json-types'
|
2026-06-05 23:32:27 +08:00
|
|
|
import { execFile } from 'child_process'
|
2026-05-19 16:05:09 +08:00
|
|
|
import * as fs from 'fs'
|
|
|
|
|
import * as os from 'os'
|
|
|
|
|
import * as path from 'path'
|
|
|
|
|
import sharp from 'sharp'
|
2026-06-05 21:25:08 +08:00
|
|
|
import { ulid } from 'ulid'
|
2026-06-09 11:20:41 +08:00
|
|
|
import { promisify } from 'util'
|
2026-06-16 09:47:27 +08:00
|
|
|
import { dataFormatNames } from './dataFormatNames'
|
2026-05-19 16:05:09 +08:00
|
|
|
|
2026-06-05 23:32:27 +08:00
|
|
|
const execFileAsync = promisify(execFile)
|
2026-05-19 16:05:09 +08:00
|
|
|
|
|
|
|
|
export interface MediaMetadata {
|
|
|
|
|
originalWidth: number
|
|
|
|
|
originalHeight: number
|
|
|
|
|
duration: number
|
|
|
|
|
bitRate: number
|
|
|
|
|
frameRate: number
|
2026-06-28 15:11:32 +08:00
|
|
|
totalFrames: number
|
2026-06-28 21:04:40 +08:00
|
|
|
startTimecode?: string
|
2026-05-19 16:05:09 +08:00
|
|
|
hasAudio: boolean
|
2026-05-26 15:41:12 +08:00
|
|
|
videoCodec?: string
|
2026-05-26 15:09:06 +08:00
|
|
|
audioCodec?: string
|
|
|
|
|
audioChannels?: number
|
|
|
|
|
audioSampleRate?: number
|
|
|
|
|
audioBitDepth?: number
|
2026-05-19 16:05:09 +08:00
|
|
|
mimeType: string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface TranscodeVideoParams {
|
|
|
|
|
inputFile: string
|
|
|
|
|
outputFile: string
|
|
|
|
|
width: number
|
|
|
|
|
height: number
|
2026-06-17 22:55:01 +08:00
|
|
|
frameRate?: number | string
|
2026-05-19 16:05:09 +08:00
|
|
|
disableAudio?: boolean
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface ExtractVideoFramesParams {
|
|
|
|
|
inputFile: string
|
|
|
|
|
outputDir: string
|
|
|
|
|
numFrames: number
|
|
|
|
|
frameHeight: number
|
|
|
|
|
isImage: boolean
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export class TranscodeService {
|
|
|
|
|
constructor(private readonly prismaClient: typeof prisma = prisma) {}
|
|
|
|
|
|
2026-05-26 15:41:12 +08:00
|
|
|
private resolveCodecName(stream: {
|
|
|
|
|
/* eslint-disable @typescript-eslint/naming-convention */
|
|
|
|
|
codec_name?: string
|
|
|
|
|
mime_codec_string?: string
|
|
|
|
|
tags?: { mime_codec_string?: string }
|
|
|
|
|
/* eslint-enable @typescript-eslint/naming-convention */
|
|
|
|
|
}): string | undefined {
|
|
|
|
|
const mimeCodec = stream.mime_codec_string || stream.tags?.mime_codec_string
|
|
|
|
|
if (mimeCodec && typeof mimeCodec === 'string') {
|
|
|
|
|
const shortCodec = mimeCodec.split('.')[0]
|
|
|
|
|
if (dataFormatNames[shortCodec]) {
|
|
|
|
|
return dataFormatNames[shortCodec]
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return stream.codec_name
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-26 15:43:26 +08:00
|
|
|
private safeParseInt(value: string | number | undefined): number | undefined {
|
|
|
|
|
if (value === undefined || value === null) return undefined
|
|
|
|
|
const parsed = typeof value === 'string' ? parseInt(value, 10) : value
|
|
|
|
|
return Number.isFinite(parsed) ? (parsed as number) : undefined
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-19 16:05:09 +08:00
|
|
|
async getVideoInfo(inputFile: string): Promise<MediaMetadata> {
|
2026-06-05 23:32:27 +08:00
|
|
|
const { stdout } = await execFileAsync('ffprobe', [
|
|
|
|
|
'-v',
|
|
|
|
|
'quiet',
|
|
|
|
|
'-print_format',
|
|
|
|
|
'json',
|
|
|
|
|
'-show_format',
|
|
|
|
|
'-show_streams',
|
|
|
|
|
inputFile,
|
|
|
|
|
])
|
2026-05-19 16:05:09 +08:00
|
|
|
const info = JSON.parse(stdout)
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
|
const videoStream = info.streams.find((s: any) => s.codec_type === 'video')
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
|
const audioStream = info.streams.find((s: any) => s.codec_type === 'audio')
|
|
|
|
|
|
|
|
|
|
if (!videoStream) {
|
|
|
|
|
throw new Error('No video stream found')
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-28 15:11:32 +08:00
|
|
|
let fps = 0
|
|
|
|
|
if (videoStream.avg_frame_rate) {
|
|
|
|
|
const parts = videoStream.avg_frame_rate.split('/')
|
|
|
|
|
if (parts.length === 2) {
|
|
|
|
|
const num = parseFloat(parts[0])
|
|
|
|
|
const den = parseFloat(parts[1])
|
|
|
|
|
if (den > 0) {
|
|
|
|
|
fps = num / den
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (fps === 0 && videoStream.r_frame_rate) {
|
|
|
|
|
const parts = videoStream.r_frame_rate.split('/')
|
|
|
|
|
if (parts.length === 2) {
|
|
|
|
|
const num = parseFloat(parts[0])
|
|
|
|
|
const den = parseFloat(parts[1])
|
|
|
|
|
if (den > 0) {
|
|
|
|
|
fps = num / den
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const duration = parseFloat(info.format.duration)
|
|
|
|
|
let totalFrames = 0
|
|
|
|
|
if (videoStream.nb_frames) {
|
|
|
|
|
totalFrames = parseInt(videoStream.nb_frames, 10)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!totalFrames && fps > 0 && !isNaN(duration)) {
|
|
|
|
|
totalFrames = Math.round(duration * fps)
|
|
|
|
|
}
|
2026-06-28 21:04:40 +08:00
|
|
|
const startTimecode = videoStream.tags?.timecode || info.format?.tags?.timecode
|
2026-05-19 16:05:09 +08:00
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
originalWidth: videoStream.width,
|
|
|
|
|
originalHeight: videoStream.height,
|
2026-06-28 15:11:32 +08:00
|
|
|
duration,
|
2026-05-19 16:05:09 +08:00
|
|
|
bitRate: parseFloat(info.format.bit_rate),
|
2026-06-28 15:11:32 +08:00
|
|
|
frameRate: fps || 30,
|
|
|
|
|
totalFrames: totalFrames || 0,
|
2026-06-28 21:04:40 +08:00
|
|
|
startTimecode,
|
2026-05-19 16:05:09 +08:00
|
|
|
hasAudio: !!audioStream,
|
2026-05-26 15:41:12 +08:00
|
|
|
videoCodec: this.resolveCodecName(videoStream),
|
|
|
|
|
audioCodec: audioStream ? this.resolveCodecName(audioStream) : undefined,
|
2026-05-26 15:09:06 +08:00
|
|
|
audioChannels: audioStream?.channels,
|
2026-05-26 15:43:26 +08:00
|
|
|
audioSampleRate: this.safeParseInt(audioStream?.sample_rate),
|
|
|
|
|
audioBitDepth:
|
|
|
|
|
this.safeParseInt(audioStream?.bits_per_raw_sample) ??
|
|
|
|
|
this.safeParseInt(audioStream?.bits_per_sample),
|
2026-05-19 16:05:09 +08:00
|
|
|
mimeType: '',
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async getImageInfo(inputFile: string): Promise<MediaMetadata> {
|
|
|
|
|
let input: string | Buffer = inputFile
|
|
|
|
|
if (inputFile.startsWith('http')) {
|
|
|
|
|
const resp = await fetch(inputFile)
|
|
|
|
|
if (!resp.ok) {
|
|
|
|
|
throw new Error(`Failed to fetch image from ${inputFile}: ${resp.statusText}`)
|
|
|
|
|
}
|
|
|
|
|
input = Buffer.from(await resp.arrayBuffer())
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-08 17:13:19 +08:00
|
|
|
const metadata = await sharp(input, { limitInputPixels: false }).metadata()
|
2026-05-19 16:05:09 +08:00
|
|
|
return {
|
|
|
|
|
originalWidth: metadata.width || 0,
|
|
|
|
|
originalHeight: metadata.height || 0,
|
|
|
|
|
duration: 0,
|
|
|
|
|
bitRate: 0,
|
|
|
|
|
frameRate: 0,
|
2026-06-28 15:11:32 +08:00
|
|
|
totalFrames: 0,
|
2026-06-28 21:04:40 +08:00
|
|
|
startTimecode: undefined,
|
2026-05-19 16:05:09 +08:00
|
|
|
hasAudio: false,
|
|
|
|
|
mimeType: metadata.format || '',
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
|
|
|
|
|
let filterComplex = `[0:v]scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
|
|
|
|
|
if (params.frameRate) {
|
|
|
|
|
filterComplex += `,fps=${params.frameRate}`
|
|
|
|
|
}
|
|
|
|
|
filterComplex += '[vout]'
|
|
|
|
|
|
2026-06-05 23:32:27 +08:00
|
|
|
const args = ['-i', params.inputFile, '-filter_complex', filterComplex, '-map', '[vout]']
|
2026-05-19 16:05:09 +08:00
|
|
|
|
2026-06-28 15:11:32 +08:00
|
|
|
if (params.frameRate) {
|
|
|
|
|
let calculatedFps: number
|
|
|
|
|
if (typeof params.frameRate === 'number') {
|
|
|
|
|
calculatedFps = params.frameRate
|
|
|
|
|
} else {
|
|
|
|
|
const parts = params.frameRate.split('/')
|
|
|
|
|
if (parts.length === 2) {
|
|
|
|
|
calculatedFps = parseFloat(parts[0]) / parseFloat(parts[1])
|
|
|
|
|
} else {
|
|
|
|
|
calculatedFps = parseFloat(params.frameRate)
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-06-29 10:55:28 +08:00
|
|
|
if (Number.isFinite(calculatedFps) && calculatedFps > 0) {
|
2026-06-28 15:11:32 +08:00
|
|
|
const roundedFps = Math.max(1, Math.round(calculatedFps))
|
|
|
|
|
args.push(
|
|
|
|
|
'-r',
|
|
|
|
|
calculatedFps.toString(),
|
|
|
|
|
'-g',
|
|
|
|
|
roundedFps.toString(),
|
|
|
|
|
'-force_key_frames',
|
|
|
|
|
'expr:gte(t,n_forced*1)',
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-19 16:05:09 +08:00
|
|
|
if (!params.disableAudio) {
|
|
|
|
|
args.push('-map', '0:a?')
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-28 15:11:32 +08:00
|
|
|
args.push('-c:v', 'libx264', '-preset', 'fast', '-crf', '26')
|
2026-05-19 16:05:09 +08:00
|
|
|
|
|
|
|
|
if (!params.disableAudio) {
|
|
|
|
|
args.push('-c:a', 'aac', '-b:a', '128k')
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-05 23:32:27 +08:00
|
|
|
args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', params.outputFile)
|
2026-05-19 16:05:09 +08:00
|
|
|
|
2026-06-18 11:57:38 +08:00
|
|
|
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
2026-05-19 16:05:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async transcodeImage(
|
2026-06-08 12:14:14 +08:00
|
|
|
inputFile: string | Buffer,
|
2026-05-19 16:05:09 +08:00
|
|
|
outputFile: string,
|
|
|
|
|
width: number,
|
|
|
|
|
quality: number,
|
|
|
|
|
height: number | null = null,
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
let input: string | Buffer = inputFile
|
2026-06-08 12:14:14 +08:00
|
|
|
if (typeof inputFile === 'string' && inputFile.startsWith('http')) {
|
2026-05-19 16:05:09 +08:00
|
|
|
const resp = await fetch(inputFile)
|
|
|
|
|
if (!resp.ok) {
|
|
|
|
|
throw new Error(`Failed to fetch image from ${inputFile}: ${resp.statusText}`)
|
|
|
|
|
}
|
|
|
|
|
input = Buffer.from(await resp.arrayBuffer())
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-08 17:13:19 +08:00
|
|
|
const sharpInstance = sharp(input, { limitInputPixels: false })
|
2026-05-19 16:05:09 +08:00
|
|
|
|
2026-06-09 11:20:41 +08:00
|
|
|
const WEBP_MAX_DIMENSION = 7680
|
2026-06-08 17:13:19 +08:00
|
|
|
const targetW = width > 0 ? Math.min(width, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
|
|
|
|
|
const targetH = height && height > 0 ? Math.min(height, WEBP_MAX_DIMENSION) : WEBP_MAX_DIMENSION
|
2026-05-19 16:05:09 +08:00
|
|
|
|
2026-06-08 17:13:19 +08:00
|
|
|
sharpInstance.resize(targetW, targetH, {
|
|
|
|
|
withoutEnlargement: true,
|
|
|
|
|
fit: 'inside',
|
|
|
|
|
})
|
2026-05-19 16:05:09 +08:00
|
|
|
|
|
|
|
|
await sharpInstance.webp({ quality }).toFile(outputFile)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async generateSprite(
|
|
|
|
|
inputFile: string,
|
|
|
|
|
outputSprite: string,
|
|
|
|
|
outputPoster: string,
|
|
|
|
|
duration: number,
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
const spriteFps = 100 / duration
|
2026-07-01 12:45:16 +08:00
|
|
|
const filterComplex = `[0:v]fps=${spriteFps},scale=w=480:h=-2,tile=10x10[sprite_out];[0:v]scale=-2:480:force_original_aspect_ratio=decrease,select='eq(n\\,0)'[thumb_out]`
|
2026-05-19 16:05:09 +08:00
|
|
|
|
|
|
|
|
const args = [
|
|
|
|
|
'-i',
|
2026-06-05 23:32:27 +08:00
|
|
|
inputFile,
|
2026-05-19 16:05:09 +08:00
|
|
|
'-filter_complex',
|
2026-06-05 23:32:27 +08:00
|
|
|
filterComplex,
|
2026-05-19 16:05:09 +08:00
|
|
|
'-map',
|
|
|
|
|
'[sprite_out]',
|
|
|
|
|
'-frames:v',
|
|
|
|
|
'1',
|
|
|
|
|
'-c:v',
|
|
|
|
|
'libwebp',
|
|
|
|
|
'-q:v',
|
|
|
|
|
'75',
|
2026-06-05 23:32:27 +08:00
|
|
|
outputSprite,
|
2026-05-19 16:05:09 +08:00
|
|
|
'-map',
|
|
|
|
|
'[thumb_out]',
|
|
|
|
|
'-c:v',
|
|
|
|
|
'libwebp',
|
|
|
|
|
'-q:v',
|
|
|
|
|
'75',
|
|
|
|
|
'-frames:v',
|
|
|
|
|
'1',
|
|
|
|
|
'-max_muxing_queue_size',
|
|
|
|
|
'1024',
|
2026-06-05 23:32:27 +08:00
|
|
|
outputPoster,
|
2026-05-19 16:05:09 +08:00
|
|
|
]
|
2026-06-18 11:57:38 +08:00
|
|
|
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
2026-05-19 16:05:09 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-18 10:32:38 +08:00
|
|
|
async generatePdfSprite(
|
|
|
|
|
inputFile: string,
|
|
|
|
|
outputSprite: string,
|
|
|
|
|
outputPoster: string,
|
|
|
|
|
): Promise<{ pageCount: number; originalWidth: number; originalHeight: number }> {
|
|
|
|
|
const tmpDir = this.createTempDir('pdf-sprite-')
|
|
|
|
|
try {
|
|
|
|
|
const pagePrefix = path.join(tmpDir, 'page')
|
|
|
|
|
try {
|
|
|
|
|
await execFileAsync('pdftoppm', ['-png', '-f', '1', '-l', '100', inputFile, pagePrefix])
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const msg = err instanceof Error ? err.message : String(err)
|
|
|
|
|
if (msg.includes('pdftoppm') || msg.includes('ENOENT') || msg.includes('not found')) {
|
|
|
|
|
throw new Error(
|
|
|
|
|
`pdftoppm executable not found in $PATH. Please install poppler-utils / poppler. (${msg})`,
|
|
|
|
|
{ cause: err },
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
throw err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const files = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.png'))
|
|
|
|
|
if (files.length === 0) {
|
|
|
|
|
throw new Error('pdftoppm produced no image outputs')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
files.sort((a, b) => {
|
|
|
|
|
const numA = parseInt(a.replace(/[^0-9]/g, ''), 10)
|
|
|
|
|
const numB = parseInt(b.replace(/[^0-9]/g, ''), 10)
|
|
|
|
|
return numA - numB
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const extractedCount = files.length
|
|
|
|
|
const firstPagePath = path.join(tmpDir, files[0])
|
|
|
|
|
const firstMeta = await sharp(firstPagePath, { limitInputPixels: false }).metadata()
|
|
|
|
|
const originalWidth = firstMeta.width || 800
|
|
|
|
|
const originalHeight = firstMeta.height || 1000
|
|
|
|
|
|
|
|
|
|
for (let f = 1; f <= 100; f++) {
|
|
|
|
|
const pageIdx = Math.min(extractedCount - 1, Math.floor(((f - 1) * extractedCount) / 100))
|
|
|
|
|
const srcPath = path.join(tmpDir, files[pageIdx])
|
|
|
|
|
const destPath = path.join(tmpDir, `frame_${f}.png`)
|
|
|
|
|
if (srcPath !== destPath) {
|
|
|
|
|
fs.copyFileSync(srcPath, destPath)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const spriteArgs = [
|
|
|
|
|
'-i',
|
|
|
|
|
path.join(tmpDir, 'frame_%d.png'),
|
|
|
|
|
'-filter_complex',
|
|
|
|
|
'scale=w=480:h=-2,tile=10x10',
|
|
|
|
|
'-frames:v',
|
|
|
|
|
'1',
|
|
|
|
|
'-c:v',
|
|
|
|
|
'libwebp',
|
|
|
|
|
'-q:v',
|
|
|
|
|
'75',
|
|
|
|
|
outputSprite,
|
|
|
|
|
]
|
|
|
|
|
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...spriteArgs])
|
|
|
|
|
|
|
|
|
|
await sharp(firstPagePath, { limitInputPixels: false })
|
|
|
|
|
.resize(480, null, { withoutEnlargement: true, fit: 'inside' })
|
|
|
|
|
.webp({ quality: 75 })
|
|
|
|
|
.toFile(outputPoster)
|
|
|
|
|
|
|
|
|
|
let totalPages = extractedCount
|
|
|
|
|
try {
|
|
|
|
|
const { stdout } = await execFileAsync('pdfinfo', [inputFile])
|
|
|
|
|
const match = stdout.match(/Pages:\s+(\d+)/)
|
|
|
|
|
if (match) {
|
|
|
|
|
totalPages = parseInt(match[1], 10)
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// Fallback to extracted count if pdfinfo is unavailable
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
pageCount: totalPages,
|
|
|
|
|
originalWidth,
|
|
|
|
|
originalHeight,
|
|
|
|
|
}
|
|
|
|
|
} finally {
|
|
|
|
|
this.removeDir(tmpDir)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async getPdfInfo(inputFile: string): Promise<MediaMetadata> {
|
|
|
|
|
const tmpDir = this.createTempDir('pdf-info-')
|
|
|
|
|
let originalWidth = 800
|
|
|
|
|
let originalHeight = 1000
|
|
|
|
|
let pageCount = 1
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const pagePrefix = path.join(tmpDir, 'page')
|
|
|
|
|
await execFileAsync('pdftoppm', ['-png', '-f', '1', '-l', '1', inputFile, pagePrefix])
|
|
|
|
|
const files = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.png'))
|
|
|
|
|
if (files.length > 0) {
|
|
|
|
|
const meta = await sharp(path.join(tmpDir, files[0]), {
|
|
|
|
|
limitInputPixels: false,
|
|
|
|
|
}).metadata()
|
|
|
|
|
originalWidth = meta.width || 800
|
|
|
|
|
originalHeight = meta.height || 1000
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.warn('pdftoppm not available for PDF dimensions extraction:', err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const { stdout } = await execFileAsync('pdfinfo', [inputFile])
|
|
|
|
|
const match = stdout.match(/Pages:\s+(\d+)/)
|
|
|
|
|
if (match) {
|
|
|
|
|
pageCount = parseInt(match[1], 10)
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// Fallback
|
|
|
|
|
} finally {
|
|
|
|
|
this.removeDir(tmpDir)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
originalWidth,
|
|
|
|
|
originalHeight,
|
|
|
|
|
duration: 0,
|
|
|
|
|
bitRate: 0,
|
|
|
|
|
frameRate: 0,
|
|
|
|
|
totalFrames: pageCount,
|
|
|
|
|
hasAudio: false,
|
|
|
|
|
mimeType: 'application/pdf',
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-19 16:05:09 +08:00
|
|
|
async extractAudio(inputFile: string, outputFile: string, bitrate: string): Promise<void> {
|
2026-06-05 23:32:27 +08:00
|
|
|
const args = ['-i', inputFile, '-vn', '-acodec', 'libmp3lame', '-b:a', bitrate, outputFile]
|
2026-06-18 11:57:38 +08:00
|
|
|
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
2026-05-19 16:05:09 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-05 15:11:19 +08:00
|
|
|
async getAudioInfo(inputFile: string): Promise<MediaMetadata> {
|
|
|
|
|
const { stdout } = await execFileAsync('ffprobe', [
|
|
|
|
|
'-v',
|
|
|
|
|
'quiet',
|
|
|
|
|
'-print_format',
|
|
|
|
|
'json',
|
|
|
|
|
'-show_format',
|
|
|
|
|
'-show_streams',
|
|
|
|
|
inputFile,
|
|
|
|
|
])
|
|
|
|
|
const info = JSON.parse(stdout)
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
|
const audioStream = info.streams.find((s: any) => s.codec_type === 'audio')
|
|
|
|
|
|
|
|
|
|
if (!audioStream) {
|
|
|
|
|
throw new Error('No audio stream found')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const duration = parseFloat(info.format.duration)
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
originalWidth: 0,
|
|
|
|
|
originalHeight: 0,
|
|
|
|
|
duration: isNaN(duration) ? 0 : duration,
|
|
|
|
|
bitRate: parseFloat(info.format.bit_rate) || 0,
|
|
|
|
|
frameRate: 0,
|
|
|
|
|
totalFrames: 0,
|
|
|
|
|
startTimecode: undefined,
|
|
|
|
|
hasAudio: true,
|
|
|
|
|
videoCodec: undefined,
|
|
|
|
|
audioCodec: this.resolveCodecName(audioStream),
|
|
|
|
|
audioChannels: audioStream?.channels,
|
|
|
|
|
audioSampleRate: this.safeParseInt(audioStream?.sample_rate),
|
|
|
|
|
audioBitDepth:
|
|
|
|
|
this.safeParseInt(audioStream?.bits_per_raw_sample) ??
|
|
|
|
|
this.safeParseInt(audioStream?.bits_per_sample),
|
|
|
|
|
mimeType: '',
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async transcodeAudio(params: {
|
|
|
|
|
inputFile: string
|
|
|
|
|
outputFile: string
|
|
|
|
|
bitrate?: string
|
|
|
|
|
}): Promise<void> {
|
|
|
|
|
const bitrate = params.bitrate || '128k'
|
|
|
|
|
const args = [
|
|
|
|
|
'-i',
|
|
|
|
|
params.inputFile,
|
|
|
|
|
'-vn',
|
|
|
|
|
'-c:a',
|
|
|
|
|
'aac',
|
|
|
|
|
'-b:a',
|
|
|
|
|
bitrate,
|
|
|
|
|
'-ac',
|
|
|
|
|
'2',
|
|
|
|
|
params.outputFile,
|
|
|
|
|
]
|
|
|
|
|
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-19 16:05:09 +08:00
|
|
|
async extractVideoFrames(params: ExtractVideoFramesParams): Promise<string[]> {
|
|
|
|
|
if (params.isImage) {
|
|
|
|
|
const outputFile = path.join(params.outputDir, '1.webp')
|
|
|
|
|
await this.transcodeImage(params.inputFile, outputFile, -1, 80, params.frameHeight)
|
|
|
|
|
return [outputFile]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const meta = await this.getVideoInfo(params.inputFile)
|
|
|
|
|
const fps = params.numFrames / meta.duration
|
|
|
|
|
const outputPattern = path.join(params.outputDir, '%d.webp')
|
|
|
|
|
|
|
|
|
|
const args = [
|
|
|
|
|
'-i',
|
2026-06-05 23:32:27 +08:00
|
|
|
params.inputFile,
|
2026-05-19 16:05:09 +08:00
|
|
|
'-vf',
|
|
|
|
|
`fps=${fps},scale=-2:${params.frameHeight}`,
|
|
|
|
|
'-c:v',
|
|
|
|
|
'libwebp',
|
|
|
|
|
'-q:v',
|
|
|
|
|
'80',
|
2026-06-05 23:32:27 +08:00
|
|
|
outputPattern,
|
2026-05-19 16:05:09 +08:00
|
|
|
]
|
2026-06-18 11:57:38 +08:00
|
|
|
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
2026-05-19 16:05:09 +08:00
|
|
|
|
|
|
|
|
const files = fs.readdirSync(params.outputDir)
|
|
|
|
|
return files
|
|
|
|
|
.filter((f) => f.endsWith('.webp'))
|
|
|
|
|
.sort((a, b) => {
|
|
|
|
|
const na = parseInt(path.basename(a, '.webp'))
|
|
|
|
|
const nb = parseInt(path.basename(b, '.webp'))
|
|
|
|
|
return na - nb
|
|
|
|
|
})
|
|
|
|
|
.map((f) => path.join(params.outputDir, f))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
createTempDir(prefix: string): string {
|
|
|
|
|
return fs.mkdtempSync(path.join(os.tmpdir(), prefix))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
removeDir(dir: string): void {
|
|
|
|
|
fs.rmSync(dir, { recursive: true, force: true })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- Task Creation Helpers ---
|
|
|
|
|
|
2026-05-28 09:48:05 +08:00
|
|
|
async createVideoTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
|
2026-05-19 16:05:09 +08:00
|
|
|
return this.prismaClient.workflowTask.create({
|
|
|
|
|
data: {
|
|
|
|
|
assetId,
|
2026-05-28 09:48:05 +08:00
|
|
|
projectId,
|
2026-05-19 16:05:09 +08:00
|
|
|
type: WorkflowTaskType.transcode,
|
|
|
|
|
status: WorkflowTaskStatus.pending,
|
2026-05-28 09:48:05 +08:00
|
|
|
payload: {
|
|
|
|
|
projectId,
|
|
|
|
|
transcode: spec,
|
|
|
|
|
},
|
2026-05-19 16:05:09 +08:00
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-28 09:48:05 +08:00
|
|
|
async createImageTranscodeTask(assetId: string, projectId: string, spec: PrismaJson.TaskSpec) {
|
2026-05-19 16:05:09 +08:00
|
|
|
return this.prismaClient.workflowTask.create({
|
|
|
|
|
data: {
|
|
|
|
|
assetId,
|
2026-05-28 09:48:05 +08:00
|
|
|
projectId,
|
2026-05-19 16:05:09 +08:00
|
|
|
type: WorkflowTaskType.transcode,
|
|
|
|
|
status: WorkflowTaskStatus.pending,
|
2026-05-28 09:48:05 +08:00
|
|
|
payload: {
|
|
|
|
|
projectId,
|
|
|
|
|
transcode: spec,
|
|
|
|
|
},
|
2026-05-19 16:05:09 +08:00
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
}
|
2026-06-05 21:25:08 +08:00
|
|
|
|
|
|
|
|
async takeScreenshots(params: {
|
|
|
|
|
assetKey: string
|
|
|
|
|
assetId: string
|
|
|
|
|
start: number
|
|
|
|
|
end: number
|
|
|
|
|
count: number
|
|
|
|
|
commentTimestamp?: number | null
|
|
|
|
|
annotations?: PrismaJson.AnnotationList | null
|
|
|
|
|
}): Promise<Array<{ key: string; timestamp: number }>> {
|
|
|
|
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
|
|
|
|
const tmpDir = this.createTempDir('screenshot-')
|
|
|
|
|
const videoPath = path.join(tmpDir, path.basename(params.assetKey))
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// 1. Download video
|
|
|
|
|
await s3Service.downloadToFile(bucket, params.assetKey, videoPath)
|
|
|
|
|
|
|
|
|
|
// 2. Generate timestamps
|
|
|
|
|
let timestamps: number[] = []
|
|
|
|
|
if (params.count <= 1) {
|
|
|
|
|
timestamps = [params.start]
|
|
|
|
|
} else {
|
|
|
|
|
const step = (params.end - params.start) / params.count
|
|
|
|
|
timestamps = Array.from({ length: params.count }, (_, i) => params.start + i * step)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 3. Snap closest timestamp to commentTimestamp if within range
|
|
|
|
|
const commentTimestamp = params.commentTimestamp
|
|
|
|
|
if (commentTimestamp !== undefined && commentTimestamp !== null) {
|
|
|
|
|
if (commentTimestamp >= params.start && commentTimestamp <= params.end) {
|
|
|
|
|
let closestIdx = 0
|
|
|
|
|
let minDiff = Math.abs(timestamps[0] - commentTimestamp)
|
|
|
|
|
for (let i = 1; i < timestamps.length; i++) {
|
|
|
|
|
const diff = Math.abs(timestamps[i] - commentTimestamp)
|
|
|
|
|
if (diff < minDiff) {
|
|
|
|
|
minDiff = diff
|
|
|
|
|
closestIdx = i
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
timestamps[closestIdx] = commentTimestamp
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const results: Array<{ key: string; timestamp: number }> = []
|
|
|
|
|
|
|
|
|
|
// 4. Extract each screenshot
|
|
|
|
|
for (const t of timestamps) {
|
|
|
|
|
const outName = `shot-${t.toFixed(3)}-${ulid()}.webp`
|
|
|
|
|
const localShotPath = path.join(tmpDir, outName)
|
|
|
|
|
|
|
|
|
|
const args = [
|
|
|
|
|
'-ss',
|
|
|
|
|
t.toFixed(3),
|
|
|
|
|
'-i',
|
2026-06-05 23:32:27 +08:00
|
|
|
videoPath,
|
2026-06-05 21:25:08 +08:00
|
|
|
'-vframes',
|
|
|
|
|
'1',
|
|
|
|
|
'-vf',
|
|
|
|
|
'scale=-2:720',
|
|
|
|
|
'-c:v',
|
|
|
|
|
'libwebp',
|
|
|
|
|
'-q:v',
|
|
|
|
|
'80',
|
2026-06-05 23:32:27 +08:00
|
|
|
localShotPath,
|
2026-06-05 21:25:08 +08:00
|
|
|
]
|
2026-06-18 11:57:38 +08:00
|
|
|
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
2026-06-05 21:25:08 +08:00
|
|
|
|
|
|
|
|
// 5. Overlay annotations if timestamp matches commentTimestamp exactly
|
|
|
|
|
if (
|
|
|
|
|
commentTimestamp !== undefined &&
|
|
|
|
|
commentTimestamp !== null &&
|
|
|
|
|
t === commentTimestamp &&
|
|
|
|
|
params.annotations &&
|
|
|
|
|
params.annotations.length > 0
|
|
|
|
|
) {
|
2026-06-08 17:13:19 +08:00
|
|
|
const meta = await sharp(localShotPath, { limitInputPixels: false }).metadata()
|
2026-06-05 21:25:08 +08:00
|
|
|
const width = meta.width || 1280
|
|
|
|
|
const height = meta.height || 720
|
|
|
|
|
|
|
|
|
|
const svgStr = renderAnnotationsToSvg(width, height, params.annotations)
|
|
|
|
|
const tempCompositedPath = path.join(tmpDir, `composite-${outName}`)
|
|
|
|
|
|
2026-06-08 17:13:19 +08:00
|
|
|
await sharp(localShotPath, { limitInputPixels: false })
|
2026-06-05 21:25:08 +08:00
|
|
|
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
|
|
|
|
|
.toFile(tempCompositedPath)
|
|
|
|
|
|
|
|
|
|
fs.renameSync(tempCompositedPath, localShotPath)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 6. Upload to S3
|
2026-06-08 12:14:14 +08:00
|
|
|
const s3Key = `files/${params.assetId}/screenshots/${outName}`
|
2026-06-05 21:25:08 +08:00
|
|
|
const fileBuffer = fs.readFileSync(localShotPath)
|
|
|
|
|
await s3Service.putObject(bucket, s3Key, fileBuffer, fileBuffer.length, 'image/webp')
|
|
|
|
|
|
|
|
|
|
results.push({ key: s3Key, timestamp: t })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return results
|
|
|
|
|
} finally {
|
|
|
|
|
this.removeDir(tmpDir)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-19 09:45:14 +08:00
|
|
|
async renderPdfPages(params: {
|
|
|
|
|
assetKey: string
|
|
|
|
|
assetId: string
|
|
|
|
|
start: number
|
|
|
|
|
end: number
|
|
|
|
|
commentTimestamp?: number | null
|
|
|
|
|
annotations?: PrismaJson.AnnotationList | null
|
|
|
|
|
}): Promise<Array<{ key: string; page: number }>> {
|
|
|
|
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
|
|
|
|
const tmpDir = this.createTempDir('pdf-pages-')
|
|
|
|
|
const pdfPath = path.join(tmpDir, path.basename(params.assetKey))
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// 1. Download PDF file
|
|
|
|
|
await s3Service.downloadToFile(bucket, params.assetKey, pdfPath)
|
|
|
|
|
|
|
|
|
|
// 2. Render pages via pdftoppm (-png -f start -l end)
|
|
|
|
|
const pagePrefix = path.join(tmpDir, 'page')
|
|
|
|
|
try {
|
|
|
|
|
await execFileAsync('pdftoppm', [
|
|
|
|
|
'-png',
|
|
|
|
|
'-f',
|
|
|
|
|
params.start.toString(),
|
|
|
|
|
'-l',
|
|
|
|
|
params.end.toString(),
|
|
|
|
|
pdfPath,
|
|
|
|
|
pagePrefix,
|
|
|
|
|
])
|
|
|
|
|
} catch (err) {
|
|
|
|
|
const msg = err instanceof Error ? err.message : String(err)
|
|
|
|
|
if (msg.includes('pdftoppm') || msg.includes('ENOENT') || msg.includes('not found')) {
|
|
|
|
|
throw new Error(
|
|
|
|
|
`pdftoppm executable not found in $PATH. Please install poppler-utils / poppler. (${msg})`,
|
|
|
|
|
{ cause: err },
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
throw err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const files = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.png'))
|
|
|
|
|
if (files.length === 0) {
|
|
|
|
|
throw new Error('pdftoppm produced no image outputs')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
files.sort((a, b) => {
|
|
|
|
|
const numA = parseInt(a.replace(/[^0-9]/g, ''), 10)
|
|
|
|
|
const numB = parseInt(b.replace(/[^0-9]/g, ''), 10)
|
|
|
|
|
return numA - numB
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
const results: Array<{ key: string; page: number }> = []
|
|
|
|
|
const stem = stemFromKey(params.assetKey)
|
|
|
|
|
|
|
|
|
|
for (let i = 0; i < files.length; i++) {
|
|
|
|
|
const pageNum = params.start + i
|
|
|
|
|
const localPngPath = path.join(tmpDir, files[i])
|
|
|
|
|
const webpName = `${stem}-page-${pageNum}-${ulid()}.webp`
|
|
|
|
|
const localWebpPath = path.join(tmpDir, webpName)
|
|
|
|
|
|
|
|
|
|
// Convert to 1080p WebP (fit inside 1920x1080)
|
|
|
|
|
await sharp(localPngPath, { limitInputPixels: false })
|
|
|
|
|
.resize(1920, 1080, { fit: 'inside', withoutEnlargement: false })
|
|
|
|
|
.webp({ quality: 85 })
|
|
|
|
|
.toFile(localWebpPath)
|
|
|
|
|
|
|
|
|
|
// Overlay annotations if comment page matches pageNum
|
|
|
|
|
const commentPage =
|
|
|
|
|
params.commentTimestamp !== undefined && params.commentTimestamp !== null
|
|
|
|
|
? Math.round(params.commentTimestamp)
|
|
|
|
|
: null
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
commentPage !== null &&
|
|
|
|
|
pageNum === commentPage &&
|
|
|
|
|
params.annotations &&
|
|
|
|
|
params.annotations.length > 0
|
|
|
|
|
) {
|
|
|
|
|
const meta = await sharp(localWebpPath, { limitInputPixels: false }).metadata()
|
|
|
|
|
const width = meta.width || 1920
|
|
|
|
|
const height = meta.height || 1080
|
|
|
|
|
|
|
|
|
|
const svgStr = renderAnnotationsToSvg(width, height, params.annotations)
|
|
|
|
|
const tempCompositedPath = path.join(tmpDir, `composite-${webpName}`)
|
|
|
|
|
|
|
|
|
|
await sharp(localWebpPath, { limitInputPixels: false })
|
|
|
|
|
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
|
|
|
|
|
.toFile(tempCompositedPath)
|
|
|
|
|
|
|
|
|
|
fs.renameSync(tempCompositedPath, localWebpPath)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Upload to S3
|
|
|
|
|
const s3Key = `files/${params.assetId}/pdf_pages/${webpName}`
|
|
|
|
|
const webpBuffer = fs.readFileSync(localWebpPath)
|
|
|
|
|
await s3Service.putObject(bucket, s3Key, webpBuffer, webpBuffer.length, 'image/webp')
|
|
|
|
|
|
|
|
|
|
results.push({ key: s3Key, page: pageNum })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return results
|
|
|
|
|
} finally {
|
|
|
|
|
this.removeDir(tmpDir)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-05 21:25:08 +08:00
|
|
|
async overlayAnnotations(params: {
|
|
|
|
|
assetKey: string
|
|
|
|
|
assetId: string
|
|
|
|
|
annotations: PrismaJson.AnnotationList
|
|
|
|
|
}): Promise<string> {
|
|
|
|
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
|
|
|
|
const tmpDir = this.createTempDir('annotation-')
|
|
|
|
|
const imgPath = path.join(tmpDir, path.basename(params.assetKey))
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// 1. Download image
|
|
|
|
|
await s3Service.downloadToFile(bucket, params.assetKey, imgPath)
|
|
|
|
|
|
|
|
|
|
// 2. Read dimensions
|
2026-06-08 17:13:19 +08:00
|
|
|
const meta = await sharp(imgPath, { limitInputPixels: false }).metadata()
|
2026-06-05 21:25:08 +08:00
|
|
|
const width = meta.width || 1920
|
|
|
|
|
const height = meta.height || 1080
|
|
|
|
|
|
|
|
|
|
// 3. Render SVG
|
|
|
|
|
const svgStr = renderAnnotationsToSvg(width, height, params.annotations)
|
|
|
|
|
|
|
|
|
|
// 4. Composite
|
|
|
|
|
const outName = `annotation-${ulid()}.webp`
|
|
|
|
|
const localOutPath = path.join(tmpDir, outName)
|
|
|
|
|
|
2026-06-08 17:13:19 +08:00
|
|
|
await sharp(imgPath, { limitInputPixels: false })
|
2026-06-05 21:25:08 +08:00
|
|
|
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
|
2026-06-08 17:13:19 +08:00
|
|
|
.resize(16383, 16383, { fit: 'inside', withoutEnlargement: true })
|
2026-06-05 21:25:08 +08:00
|
|
|
.webp({ quality: 90 })
|
|
|
|
|
.toFile(localOutPath)
|
|
|
|
|
|
|
|
|
|
// 5. Upload to S3
|
2026-06-08 12:14:14 +08:00
|
|
|
const s3Key = `files/${params.assetId}/annotations/${outName}`
|
2026-06-05 21:25:08 +08:00
|
|
|
const fileBuffer = fs.readFileSync(localOutPath)
|
|
|
|
|
await s3Service.putObject(bucket, s3Key, fileBuffer, fileBuffer.length, 'image/webp')
|
|
|
|
|
|
|
|
|
|
return s3Key
|
|
|
|
|
} finally {
|
|
|
|
|
this.removeDir(tmpDir)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderAnnotationsToSvg(
|
|
|
|
|
width: number,
|
|
|
|
|
height: number,
|
|
|
|
|
annotations: PrismaJson.AnnotationList,
|
|
|
|
|
): string {
|
|
|
|
|
const strokeWidth = Math.max(2, Math.round(Math.max(width, height) * 0.004))
|
|
|
|
|
const svgElements: string[] = []
|
|
|
|
|
|
|
|
|
|
for (const ann of annotations) {
|
|
|
|
|
const color = ann.color || '#ff0000'
|
|
|
|
|
const type = ann.type
|
|
|
|
|
|
|
|
|
|
switch (type) {
|
|
|
|
|
case 'box': {
|
|
|
|
|
if (ann.points.length < 2) continue
|
|
|
|
|
const [start, end] = ann.points
|
|
|
|
|
const x = Math.min(start[0], end[0]) * width
|
|
|
|
|
const y = Math.min(start[1], end[1]) * height
|
|
|
|
|
const boxWidth = Math.abs(end[0] - start[0]) * width
|
|
|
|
|
const boxHeight = Math.abs(end[1] - start[1]) * height
|
|
|
|
|
|
|
|
|
|
svgElements.push(
|
|
|
|
|
`<rect x="${x}" y="${y}" width="${boxWidth}" height="${boxHeight}" stroke="${color}" stroke-width="${strokeWidth}" fill="none" />`,
|
|
|
|
|
)
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
case 'line':
|
|
|
|
|
case 'freehand': {
|
|
|
|
|
if (ann.points.length < 2) continue
|
|
|
|
|
const pointsStr = ann.points.map(([px, py]) => `${px * width},${py * height}`).join(' ')
|
|
|
|
|
svgElements.push(
|
|
|
|
|
`<polyline points="${pointsStr}" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`,
|
|
|
|
|
)
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
case 'arrow': {
|
|
|
|
|
if (ann.points.length < 2) continue
|
|
|
|
|
const pts = ann.points.map(([px, py]) => [px * width, py * height])
|
|
|
|
|
const pointsStr = pts.map(([x, y]) => `${x},${y}`).join(' ')
|
|
|
|
|
|
|
|
|
|
svgElements.push(
|
|
|
|
|
`<polyline points="${pointsStr}" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const endPt = pts[pts.length - 1]
|
|
|
|
|
const prevPt = pts[pts.length - 2]
|
|
|
|
|
const dx = endPt[0] - prevPt[0]
|
|
|
|
|
const dy = endPt[1] - prevPt[1]
|
|
|
|
|
const angle = Math.atan2(dy, dx)
|
|
|
|
|
|
|
|
|
|
const pointerLength = Math.max(12, Math.max(width, height) * 0.015)
|
|
|
|
|
const x1 = endPt[0] - pointerLength * Math.cos(angle - Math.PI / 6)
|
|
|
|
|
const y1 = endPt[1] - pointerLength * Math.sin(angle - Math.PI / 6)
|
|
|
|
|
const x2 = endPt[0] - pointerLength * Math.cos(angle + Math.PI / 6)
|
|
|
|
|
const y2 = endPt[1] - pointerLength * Math.sin(angle + Math.PI / 6)
|
|
|
|
|
|
|
|
|
|
svgElements.push(
|
|
|
|
|
`<polygon points="${endPt[0]},${endPt[1]} ${x1},${y1} ${x2},${y2}" fill="${color}" />`,
|
|
|
|
|
)
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return `<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">${svgElements.join(
|
|
|
|
|
'\n',
|
|
|
|
|
)}</svg>`
|
2026-05-19 16:05:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const transcodeService = new TranscodeService()
|