/
ffmpeg.js
82 lines (64 loc) · 1.97 KB
/
ffmpeg.js
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
import {spawn, execFile} from 'child_process'
import {dirname, basename, extname} from 'path'
import {mkdirSync, existsSync} from 'fs'
import { join } from 'path'
import {tmpdir} from 'os'
process.env['PATH'] += ':' + process.env['LAMBDA_TASK_ROOT']
export function ffprobe(file) {
return new Promise((resolve, reject) => {
const args = [
'-v', 'quiet',
'-print_format', 'json',
'-show_format',
'-show_streams',
'-i', file
]
const opts = {}
const cb = (error, stdout) => {
if (error) {
reject(error)
}
const result = JSON.parse(stdout)
if (!result.streams) {
return reject('This file has no streams')
}
const isValidFile = result.streams.some(({codec_type, duration}) =>
(codec_type === 'video' || codec_type === 'audio')
)
if (!isValidFile) {
return reject('FFprobe: no valid media stream found')
} else {
console.log('Valid file found. FFProbe finished')
return resolve(result)
}
}
execFile('ffprobe', args, opts, cb)
.on('error', reject)
})
}
export function ffmpeg(file, extension, ffmpegArgs) {
return new Promise((resolve, reject) => {
// Create output dir
const outputDirectory = join(tmpdir(), `ffmpeg-output-${Math.random().toString(36).substring(7)}`)
if (!existsSync(outputDirectory)) {
mkdirSync(outputDirectory)
}
const args = [
'-y',
'-loglevel',
'warning',
'-i',
file,
...(ffmpegArgs || []),
`${join(outputDirectory, basename(file, extname(file)))}.${extension}`,
]
console.log('Running: ffmpeg', args.join(' '))
const opts = {}
const child = spawn('ffmpeg', args, opts)
.on('message', msg => console.log(msg))
.on('error', reject)
.on('close', () => resolve(outputDirectory))
child.stdout.on('data', data => process.stdout.write(data))
child.stderr.on('data', data => process.stdout.write(data))
})
}