-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathffmpeg-wrapper.ts
More file actions
325 lines (289 loc) · 10.1 KB
/
ffmpeg-wrapper.ts
File metadata and controls
325 lines (289 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/**
* FFmpeg Wrapper Utility
*
* Provides high-level functions for executing FFmpeg commands:
* - Probe media files (get duration, codec, resolution, etc.)
* - Convert media files with progress tracking
* - Parse FFmpeg output for progress reporting
*/
import { spawn, type ChildProcess } from 'child_process'
import { getFFmpegPath, getFFprobePath } from './binary-checker'
export interface MediaInfo {
duration: number // in seconds
width?: number
height?: number
videoCodec?: string
audioCodec?: string
bitrate?: number
format?: string
}
export interface FFmpegConvertOptions {
inputPath: string
outputPath: string
format: string
quality: number // 1-100
audioOnly?: boolean // Extract audio only
onProgress?: (percent: number) => void
metadata?: Record<string, string> // Custom metadata
}
export interface FFmpegResult {
success: boolean
error?: string
stderr?: string
}
/**
* Probe a media file to get its information
*/
export async function probeMediaFile(filePath: string): Promise<MediaInfo | null> {
const ffprobePath = await getFFprobePath()
if (!ffprobePath) {
console.error('[ffmpeg-wrapper] ffprobe not available')
return null
}
return new Promise((resolve) => {
const args = [
'-v', 'quiet',
'-print_format', 'json',
'-show_format',
'-show_streams',
filePath
]
const child = spawn(ffprobePath, args)
let output = ''
child.stdout.on('data', (data) => {
output += data.toString()
})
child.on('close', (code) => {
if (code !== 0) {
console.error('[ffmpeg-wrapper] ffprobe failed')
resolve(null)
return
}
try {
const data = JSON.parse(output)
const videoStream = data.streams?.find((s: any) => s.codec_type === 'video')
const audioStream = data.streams?.find((s: any) => s.codec_type === 'audio')
const info: MediaInfo = {
duration: parseFloat(data.format?.duration || '0'),
width: videoStream?.width,
height: videoStream?.height,
videoCodec: videoStream?.codec_name,
audioCodec: audioStream?.codec_name,
bitrate: parseInt(data.format?.bit_rate || '0'),
format: data.format?.format_name,
}
resolve(info)
} catch (err) {
console.error('[ffmpeg-wrapper] Failed to parse ffprobe output:', err)
resolve(null)
}
})
child.on('error', (err) => {
console.error('[ffmpeg-wrapper] ffprobe error:', err)
resolve(null)
})
})
}
/**
* Parse FFmpeg progress from stderr output
*/
export function parseFFmpegProgress(line: string, totalDuration: number): number | null {
// FFmpeg outputs progress like: time=00:01:23.45
const timeMatch = line.match(/time=(\d{2}):(\d{2}):(\d{2}\.\d{2})/)
if (!timeMatch) return null
const [_, hours, minutes, seconds] = timeMatch
const currentSeconds =
parseInt(hours) * 3600 +
parseInt(minutes) * 60 +
parseFloat(seconds)
if (totalDuration <= 0) return 0
const percent = Math.min(100, (currentSeconds / totalDuration) * 100)
return Math.round(percent)
}
/**
* Build FFmpeg arguments based on quality and format
*/
export function buildFFmpegArgs(options: {
inputPath: string
outputPath: string
format: string
quality: number
isVideo: boolean
metadata?: Record<string, string>
}): string[] {
const { inputPath, outputPath, format, quality, isVideo, metadata } = options
const args: string[] = ['-i', inputPath, '-y'] // -y = overwrite without asking
// Map quality (1-100) to CRF and bitrate
let crf: number
let preset: string
let audioBitrate: string
if (quality >= 90) {
// High/Lossless
crf = quality >= 95 ? 0 : 18
preset = 'slow'
audioBitrate = '192k'
} else if (quality >= 70) {
// Medium
crf = 23
preset = 'medium'
audioBitrate = '128k'
} else {
// Low
crf = 28
preset = 'fast'
audioBitrate = '96k'
}
if (isVideo) {
// Video conversion
switch (format.toLowerCase()) {
case 'mp4':
args.push('-c:v', 'libx264', '-crf', crf.toString(), '-preset', preset)
args.push('-c:a', 'aac', '-b:a', audioBitrate)
break
case 'mkv':
args.push('-c:v', 'libx264', '-crf', crf.toString(), '-preset', preset)
args.push('-c:a', 'aac', '-b:a', audioBitrate)
break
case 'webm':
args.push('-c:v', 'libvpx-vp9', '-crf', crf.toString(), '-b:v', '0')
args.push('-c:a', 'libopus', '-b:a', audioBitrate)
break
case 'avi':
args.push('-c:v', 'mpeg4', '-qscale:v', Math.floor((100 - quality) / 10).toString())
args.push('-c:a', 'libmp3lame', '-b:a', audioBitrate)
break
case 'mov':
args.push('-c:v', 'libx264', '-crf', crf.toString(), '-preset', preset)
args.push('-c:a', 'aac', '-b:a', audioBitrate)
break
case 'gif':
// Special case for GIF
args.push('-vf', 'fps=10,scale=480:-1:flags=lanczos')
args.push('-c:v', 'gif')
break
case '3gp':
args.push('-c:v', 'h263', '-c:a', 'aac', '-b:a', '64k')
args.push('-s', '352x288') // Standard 3GP resolution
break
case 'flv':
args.push('-c:v', 'flv', '-c:a', 'libmp3lame', '-b:a', audioBitrate)
break
case 'wmv':
args.push('-c:v', 'wmv2', '-c:a', 'wmav2', '-b:a', audioBitrate)
break
default:
// Generic conversion
args.push('-c:v', 'libx264', '-crf', crf.toString())
args.push('-c:a', 'aac', '-b:a', audioBitrate)
}
} else {
// Audio-only conversion
switch (format.toLowerCase()) {
case 'mp3':
args.push('-c:a', 'libmp3lame', '-b:a', audioBitrate)
break
case 'aac':
case 'm4a':
args.push('-c:a', 'aac', '-b:a', audioBitrate)
break
case 'ogg':
args.push('-c:a', 'libvorbis', '-q:a', Math.floor(quality / 20).toString())
break
case 'flac':
args.push('-c:a', 'flac')
break
case 'wav':
args.push('-c:a', 'pcm_s16le')
break
case 'wma':
args.push('-c:a', 'wmav2', '-b:a', audioBitrate)
break
default:
args.push('-c:a', 'aac', '-b:a', audioBitrate)
}
}
// Add metadata tags if provided
if (metadata) {
for (const [key, value] of Object.entries(metadata)) {
if (value) {
args.push('-metadata', `${key}=${value}`)
}
}
}
args.push(outputPath)
return args
}
/**
* Execute FFmpeg conversion
*/
export async function executeFFmpeg(options: FFmpegConvertOptions): Promise<FFmpegResult> {
const ffmpegPath = await getFFmpegPath()
if (!ffmpegPath) {
return {
success: false,
error: 'FFmpeg not available. Please install FFmpeg first.',
}
}
// Probe the input file to get duration for progress calculation
const mediaInfo = await probeMediaFile(options.inputPath)
const totalDuration = mediaInfo?.duration || 0
// Determine if this is a video or audio conversion.
// audioOnly forces audio-only args even when source has a video stream.
const isVideo = !!(mediaInfo?.videoCodec) && !options.audioOnly
const args = buildFFmpegArgs({
inputPath: options.inputPath,
outputPath: options.outputPath,
format: options.format,
quality: options.quality,
isVideo,
metadata: options.metadata,
})
console.log('[ffmpeg-wrapper] Executing:', ffmpegPath, args.join(' '))
return new Promise((resolve) => {
const child: ChildProcess = spawn(ffmpegPath, args)
let stderrOutput = ''
let lastProgressUpdate = 0
child.stderr?.on('data', (data) => {
const line = data.toString()
stderrOutput += line
// Parse and emit progress
if (options.onProgress && totalDuration > 0) {
const progress = parseFFmpegProgress(line, totalDuration)
if (progress !== null && Date.now() - lastProgressUpdate > 500) {
options.onProgress(progress)
lastProgressUpdate = Date.now()
}
}
})
child.on('close', (code) => {
if (code === 0) {
resolve({ success: true })
} else {
// Extract error message from stderr
const errorMatch = stderrOutput.match(/Error.*$/m)
const error = errorMatch ? errorMatch[0] : 'FFmpeg conversion failed'
resolve({
success: false,
error,
stderr: stderrOutput,
})
}
})
child.on('error', (err) => {
resolve({
success: false,
error: err.message,
})
})
// Timeout after 30 minutes for very large files
setTimeout(() => {
if (!child.killed) {
child.kill('SIGTERM')
resolve({
success: false,
error: 'Conversion timeout (30 minutes maximum)',
})
}
}, 30 * 60 * 1000)
})
}