-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
197 lines (159 loc) · 6.78 KB
/
index.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
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
const fs = require('fs')
const path = require('path')
const pkg = require('./package.json')
const fetch = require('node-fetch')
const { spawn } = require('child_process')
const nfp = require('node-fetch-progress')
const getBinary = (job, settings) => {
return new Promise((resolve, reject) => {
const { version } = pkg['ffmpeg-static']
const filename = `ffmpeg-${version}${process.platform == 'win32' ? '.exe' : ''}`
const fileurl = `https://github.com/eugeneware/ffmpeg-static/releases/download/${version}/${process.platform}-x64`
const output = path.join(settings.workpath, filename)
if (fs.existsSync(process.env.NEXRENDER_FFMPEG)) {
settings.logger.log(`> using external ffmpeg binary at: ${process.env.NEXRENDER_FFMPEG}`)
return resolve(process.env.NEXRENDER_FFMPEG)
}
if (fs.existsSync(output)) {
settings.logger.log(`> using an existing ffmpeg binary ${version} at: ${output}`)
return resolve(output)
}
settings.logger.log(`> ffmpeg binary ${version} is not found`)
settings.logger.log(`> downloading a new ffmpeg binary ${version} to: ${output}`)
const errorHandler = (error) =>
reject(
new Error({
reason: 'Unable to download file',
meta: { fileurl, error },
})
)
fetch(fileurl)
.then((res) => (res.ok ? res : Promise.reject({ reason: 'Initial error downloading file', meta: { fileurl, error: res.error } })))
.then((res) => {
const progress = new nfp(res)
progress.on('progress', (p) => {
process.stdout.write(
`${Math.floor(p.progress * 100)}% - ${p.doneh}/${p.totalh} - ${p.rateh} - ${p.etah} \r`
)
})
const stream = fs.createWriteStream(output)
res.body.on('error', errorHandler).pipe(stream)
stream.on('error', errorHandler).on('finish', () => {
settings.logger.log(`> ffmpeg binary ${version} was successfully downloaded`)
fs.chmodSync(output, 0o755)
resolve(output)
})
})
})
}
/* pars of snippet taken from https://github.com/xonecas/ffmpeg-node/blob/master/ffmpeg-node.js#L136 */
const constructParams = (job, settings, { input, output, params }) => {
let inputs = [input]
if (params && params.hasOwnProperty('-i')) {
const p = params['-i']
if (Array.isArray(p)) {
inputs.push(...p)
} else {
inputs.push(p)
}
delete params['-i']
}
inputs = inputs.map((i) => {
if (path.isAbsolute(i)) return i
return path.join(job.workpath, i)
})
settings.logger.log(`[${job.uid}] action-transcode: input file ${inputs[0]}`)
settings.logger.log(`[${job.uid}] action-transcode: output file ${output}`)
const baseParams = {
'-i': inputs,
'-ab': '128k',
'-ar': '44100',
}
params = Object.assign(
baseParams,
{
'-acodec': 'aac',
'-vcodec': 'libx264',
'-pix_fmt': 'yuv420p',
'-r': '25',
},
params,
{
'-y': output,
}
)
/* convert to plain array */
return Object.keys(params).reduce((cur, key) => {
const value = params[key]
if (Array.isArray(value)) {
value.forEach((item) => cur.push(key, item))
} else {
cur.push(key, value)
}
return cur
}, [])
}
const convertToMilliseconds = (h, m, s) => (h * 60 * 60 + m * 60 + s) * 1000
const getDuration = (regex, data) => {
const matches = data.match(regex)
if (matches) {
return convertToMilliseconds(parseInt(matches[1]), parseInt(matches[2]), parseInt(matches[3]))
}
return 0
}
const transcodeVideo = (job, settings, input) => {
return new Promise((resolve, reject) => {
let output = input.slice(0, -4) + '-transcoded.mp4'
settings.logger.log(`[${job.uid}] transcoding asset: ${input}`)
const params = constructParams(job, settings, { input, output })
const binary = getBinary(job, settings)
.then((binary) => {
if (settings.debug) {
settings.logger.log(`[${job.uid}] spawning ffmpeg process: ${binary} ${params.join(' ')}`)
}
const instance = spawn(binary, params)
let totalDuration = 0
instance.on('error', (err) => reject(new Error(`Error starting ffmpeg process: ${err}`)))
instance.stderr.on('data', (data) => {
const dataString = data.toString()
// settings.logger.log(`[${job.uid}] ${dataString}`)
if (totalDuration === 0) {
totalDuration = getDuration(/(\d+):(\d+):(\d+).(\d+), start:/, dataString)
}
currentProgress = getDuration(/time=(\d+):(\d+):(\d+).(\d+) bitrate=/, dataString)
if (totalDuration > 0 && currentProgress > 0) {
const currentPercentage = Math.ceil((currentProgress / totalDuration) * 100)
settings.logger.log(`[${job.uid}] [${output}] transcoding progress ${currentPercentage}%...`)
}
})
instance.stdout.on('data', (data) => settings.debug && settings.logger.log(`[${job.uid}] ${dataString}`))
/* on finish (code 0 - success, other - error) */
instance.on('close', (code) => {
if (code !== 0) {
return reject(new Error('Error in action-transcode module (ffmpeg) code : ' + code))
}
settings.logger.log(`[${job.uid}] Completed transcoding, new asset ${output}`)
resolve(output)
})
})
.catch((e) => {
return reject(new Error('Error in action-transcode module (ffmpeg) ' + e))
})
})
}
module.exports = async (job, settings, options, type) => {
settings.logger.log(`[${job.uid}] starting action-transcode action (ffmpeg)`)
var promises = []
return new Promise(async (resolve, reject) => {
for (asset of job.assets) {
if (asset.type === 'video') {
settings.logger.log(`[${job.uid}] ${asset.layerName}`)
let input = asset.dest
const output = await transcodeVideo(job, settings, input)
asset.dest = output
}
}
settings.logger.log(`[${job.uid}] completed transcoding all videos`)
resolve(job)
})
}