返回 AiToEarn
video-metadata.service.ts
根目录 / project / aitoearn-backend / libs / assets / src / video-metadata.service.ts
1 import type { ExecaError } from 'execa'
2 import { createReadStream, createWriteStream } from 'node:fs'
3 import { mkdtemp, open, rm } from 'node:fs/promises'
4 import * as os from 'node:os'
5 import * as path from 'node:path'
6 import { Readable } from 'node:stream'
7 import { pipeline } from 'node:stream/promises'
8 import { Injectable, Logger } from '@nestjs/common'
9 import { UserType } from '@yikart/common'
10 import { Asset, AssetRepository, AssetStatus, AssetType } from '@yikart/mongodb'
11 import { execa } from 'execa'
12 import { StorageProvider } from './storage-provider'
13 import { generateAssetPath, PathGeneratorOptions } from './utils/path-generator'
14
15 export interface VideoMetadata {
16 width: number
17 height: number
18 duration: number
19 bitrate: number
20 frameRate: number
21 }
22
23 export interface ExtractThumbnailOptions {
24 timeInSeconds?: number
25 }
26
27 const FFPROBE_USER_AGENT = 'AiToEarn-MediaProbe/1.0'
28 // httpproxy is required for https inputs when http_proxy is set
29 const REMOTE_PROTOCOL_WHITELIST = 'http,https,tls,tcp,httpproxy'
30 const DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000
31 const MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024 * 1024 // 2GB
32
33 function assertSafeVideoUrl(videoUrl: string): void {
34 const url = String(videoUrl ?? '').trim()
35 if (url.startsWith('-') || !(url.startsWith('http://') || url.startsWith('https://'))) {
36 throw new Error(`Invalid video URL: ${url}`)
37 }
38 }
39
40 @Injectable()
41 export class VideoMetadataService {
42 private readonly logger = new Logger(VideoMetadataService.name)
43
44 constructor(
45 private readonly storage: StorageProvider,
46 private readonly assetRepository: AssetRepository,
47 ) {}
48
49 async probeVideoMetadata(videoUrl: string): Promise<VideoMetadata> {
50 assertSafeVideoUrl(videoUrl)
51
52 const { stdout } = await execa('ffprobe', [
53 '-v',
54 'error',
55 '-user_agent',
56 FFPROBE_USER_AGENT,
57 '-protocol_whitelist',
58 REMOTE_PROTOCOL_WHITELIST,
59 '-print_format',
60 'json',
61 '-show_format',
62 '-show_streams',
63 videoUrl,
64 ], {
65 timeout: 60000,
66 }).catch((err: ExecaError) => {
67 const stderr = String(err.stderr ?? '').trim()
68 throw new Error(err.timedOut
69 ? 'ffprobe timed out after 60s'
70 : `ffprobe failed: ${stderr.split('\n').pop() || `exit code ${err.exitCode}`}`)
71 })
72
73 const probeData = JSON.parse(stdout)
74 const videoStream = probeData.streams?.find((s: { codec_type: string }) => s.codec_type === 'video')
75 const format = probeData.format
76
77 if (!videoStream) {
78 throw new Error('No video stream found')
79 }
80
81 const frameRateParts = (videoStream.r_frame_rate || '0/1').split('/')
82 const frameRate = frameRateParts.length === 2
83 ? Number(frameRateParts[0]) / Number(frameRateParts[1])
84 : Number(frameRateParts[0])
85
86 return {
87 width: videoStream.width || 0,
88 height: videoStream.height || 0,
89 duration: Number(format?.duration || videoStream.duration || 0),
90 bitrate: Number(format?.bit_rate || 0),
91 frameRate: Math.round(frameRate * 100) / 100,
92 }
93 }
94
95 /**
96 * Ensure a remote video is compatible with strict upload targets (e.g. Facebook/Meta,
97 * error 1363045): H.264 video codec inside a faststart MP4. Downloads the source,
98 * probes it, and transcodes when needed. Returns the original URL when already
99 * compatible, otherwise uploads the transcoded file and returns its URL.
100 */
101 async ensureCompatibleVideo(videoUrl: string, userId = 'system'): Promise<string> {
102 assertSafeVideoUrl(videoUrl)
103
104 const workDir = await mkdtemp(path.join(os.tmpdir(), 'aitoearn-video-'))
105 const inputPath = path.join(workDir, 'input.video')
106 const outputPath = path.join(workDir, 'output.mp4')
107
108 try {
109 await this.downloadVideo(videoUrl, inputPath)
110
111 const { stdout } = await execa('ffprobe', [
112 '-v',
113 'quiet',
114 '-print_format',
115 'json',
116 '-show_format',
117 '-show_streams',
118 inputPath,
119 ], {
120 timeout: 60000,
121 })
122
123 const probeData = JSON.parse(stdout)
124 const videoStream = probeData.streams?.find((s: { codec_type: string }) => s.codec_type === 'video')
125 const formatName: string = probeData.format?.format_name ?? ''
126 const isMp4Container = formatName.split(',').some(f => f === 'mp4' || f === 'mov')
127
128 const needsTranscode = videoStream?.codec_name !== 'h264'
129 || !isMp4Container
130 || !(await this.hasFaststartMoov(inputPath))
131
132 if (!needsTranscode) {
133 return videoUrl
134 }
135
136 this.logger.log({ videoUrl, codec: videoStream?.codec_name, formatName }, 'Transcoding video to H.264 faststart mp4')
137
138 await execa('ffmpeg', [
139 '-y',
140 '-i',
141 inputPath,
142 '-c:v',
143 'libx264',
144 '-preset',
145 'veryfast',
146 '-crf',
147 '23',
148 '-c:a',
149 'aac',
150 '-b:a',
151 '128k',
152 '-movflags',
153 '+faststart',
154 '-f',
155 'mp4',
156 outputPath,
157 ], {
158 timeout: 600000,
159 })
160
161 const objectPath = generateAssetPath({
162 userId,
163 userType: UserType.System,
164 type: AssetType.PublishMedia,
165 mimeType: 'video/mp4',
166 filename: 'compatible.mp4',
167 subPath: 'compatible-video',
168 })
169
170 await this.storage.putObject(objectPath, createReadStream(outputPath), 'video/mp4')
171
172 return this.storage.buildUrl(objectPath)
173 }
174 finally {
175 await rm(workDir, { recursive: true, force: true })
176 }
177 }
178
179 private async downloadVideo(videoUrl: string, targetPath: string): Promise<void> {
180 const controller = new AbortController()
181 const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS)
182 try {
183 const response = await fetch(videoUrl, {
184 headers: { 'user-agent': FFPROBE_USER_AGENT },
185 signal: controller.signal,
186 })
187 if (!response.ok || !response.body) {
188 throw new Error(`Failed to download video: HTTP ${response.status}`)
189 }
190
191 const declaredLength = Number(response.headers.get('content-length') ?? 0)
192 if (declaredLength > MAX_DOWNLOAD_BYTES) {
193 throw new Error(`Video too large to download: ${declaredLength} bytes (max ${MAX_DOWNLOAD_BYTES})`)
194 }
195
196 let receivedBytes = 0
197 await pipeline(
198 Readable.fromWeb(response.body as ReadableStream),
199 async function* (source) {
200 for await (const chunk of source) {
201 receivedBytes += (chunk as Buffer).length
202 if (receivedBytes > MAX_DOWNLOAD_BYTES) {
203 throw new Error(`Video download exceeded size limit of ${MAX_DOWNLOAD_BYTES} bytes`)
204 }
205 yield chunk
206 }
207 },
208 createWriteStream(targetPath),
209 )
210 }
211 finally {
212 clearTimeout(timer)
213 }
214 }
215
216 private async hasFaststartMoov(filePath: string): Promise<boolean> {
217 const handle = await open(filePath, 'r')
218 try {
219 let offset = 0
220 const header = Buffer.alloc(16)
221 for (;;) {
222 const { bytesRead } = await handle.read(header, 0, 8, offset)
223 if (bytesRead < 8) {
224 return false
225 }
226 let boxSize = header.readUInt32BE(0)
227 const boxType = header.toString('ascii', 4, 8)
228 if (boxSize === 1) {
229 const { bytesRead: largeBytesRead } = await handle.read(header, 8, 8, offset + 8)
230 if (largeBytesRead < 8) {
231 return false
232 }
233 boxSize = Number(header.readBigUInt64BE(8))
234 }
235 else if (boxSize === 0) {
236 boxSize = Number.MAX_SAFE_INTEGER
237 }
238 if (boxType === 'moov') {
239 return true
240 }
241 if (boxType === 'mdat') {
242 return false
243 }
244 if (boxSize < 8) {
245 return false
246 }
247 offset += boxSize
248 }
249 }
250 finally {
251 await handle.close()
252 }
253 }
254
255 async extractThumbnailFromUrl(videoUrl: string, timeInSeconds: number): Promise<Buffer> {
256 assertSafeVideoUrl(videoUrl)
257
258 const { stdout } = await execa('ffmpeg', [
259 '-ss',
260 String(timeInSeconds),
261 '-protocol_whitelist',
262 REMOTE_PROTOCOL_WHITELIST,
263 '-i',
264 videoUrl,
265 '-vframes',
266 '1',
267 '-f',
268 'image2pipe',
269 '-vcodec',
270 'png',
271 '-',
272 ], {
273 timeout: 60000,
274 encoding: 'buffer',
275 })
276
277 return Buffer.from(stdout)
278 }
279
280 async extractAndSaveThumbnail(
281 asset: Asset,
282 userId: string,
283 userType: UserType = UserType.User,
284 options?: ExtractThumbnailOptions,
285 ): Promise<{
286 thumbnailAsset: Asset
287 thumbnailUrl: string
288 }> {
289 const timeInSeconds = options?.timeInSeconds ?? 1
290 const videoUrl = this.storage.buildUrl(asset.path)
291
292 this.logger.debug({ assetId: asset.id, videoUrl, timeInSeconds }, 'Extracting thumbnail from video')
293
294 const thumbnailBuffer = await this.extractThumbnailFromUrl(videoUrl, timeInSeconds)
295
296 const pathOptions: PathGeneratorOptions = {
297 userId,
298 userType,
299 type: AssetType.VideoThumbnail,
300 mimeType: 'image/png',
301 filename: 'thumbnail.png',
302 subPath: `source-${asset.id}`,
303 }
304
305 const thumbnailPath = generateAssetPath(pathOptions)
306
307 await this.storage.putObject(thumbnailPath, thumbnailBuffer, 'image/png')
308
309 const thumbnailAsset = await this.assetRepository.create({
310 userId,
311 userType,
312 path: thumbnailPath,
313 type: AssetType.VideoThumbnail,
314 status: AssetStatus.Confirmed,
315 size: thumbnailBuffer.length,
316 mimeType: 'image/png',
317 filename: 'thumbnail.png',
318 })
319
320 const existingMetadata = asset.metadata as Record<string, unknown> | undefined
321 const hasVideoMetadata = existingMetadata?.['width'] && existingMetadata?.['height'] && existingMetadata?.['duration']
322
323 let videoMeta: Record<string, unknown> = existingMetadata ?? {}
324 if (!hasVideoMetadata) {
325 try {
326 const probed = await this.probeVideoMetadata(videoUrl)
327 videoMeta = { ...existingMetadata, ...probed }
328 }
329 catch (error) {
330 this.logger.warn({ assetId: asset.id, error }, 'Failed to probe video metadata for thumbnail')
331 }
332 }
333
334 await this.assetRepository.updateById(asset.id, {
335 metadata: {
336 ...videoMeta,
337 cover: thumbnailPath,
338 },
339 })
340
341 this.logger.debug({ assetId: asset.id, thumbnailAssetId: thumbnailAsset.id }, 'Thumbnail extracted and saved')
342
343 return {
344 thumbnailAsset,
345 thumbnailUrl: this.storage.buildUrl(thumbnailPath),
346 }
347 }
348 }
349
349 lines TYPESCRIPT