-
-
Notifications
You must be signed in to change notification settings - Fork 325
/
Copy pathindex.js
257 lines (211 loc) · 8.49 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
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
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(new Error({
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('close', () => {
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, { preset, input, output, params }) => {
input = input || job.output;
if (!path.isAbsolute(output)) output = path.join(job.workpath, output);
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-encode: input file ${inputs[0]}`)
settings.logger.log(`[${job.uid}] action-encode: output file ${output}`)
const baseParams = {
'-i': inputs,
'-ab': '128k',
'-ar': '44100',
};
switch(preset) {
case 'mp4':
params = Object.assign(baseParams, {
'-acodec': 'aac',
'-vcodec': 'libx264',
'-pix_fmt' : 'yuv420p',
'-r': '25',
}, params, {
'-y': output
});
break;
case 'ogg':
params = Object.assign(baseParams, {
'-acodec': 'libvorbis',
'-vcodec': 'libtheora',
'-r': '25',
}, params, {
'-y': output
});
break;
case 'webm':
params = Object.assign(baseParams, {
'-acodec': 'libvorbis',
'-vcodec': 'libvpx',
'-b': '614400',
'-aspect': '16:9',
}, params, {
'-y': output
});
break;
case 'mp3':
params = Object.assign(baseParams, {
'-acodec': 'libmp3lame',
}, params, {
'-y': output
});
break;
case 'm4a':
params = Object.assign(baseParams, {
'-acodec': 'aac',
'-ab': '64k',
'-strict': '-2',
}, params, {
'-y': output
});
break;
case 'gif':
params = Object.assign({}, {
'-i': inputs,
'-filter_complex': `[0:v] fps=12,scale=w=480:h=-1,split [a][b];[a] palettegen [p];[b][p] paletteuse`,
}, params, {
'-y': output
});
break;
default:
params = Object.assign({}, {
'-i': inputs
}, params, {
'-y': output
});
break;
}
/* convert key-value pair to array */
/* replace ${workPath} with actual workpath */
/* handles flags, like -y, -vcodec, -an, etc. In which case, it returns only the key */
const parseKeyValuePair = (key, value) => {
// only relied on null check or empty string, since 0, true, false are all valid possible values
if (value === null || !String(value)) return [key];
return [key, String(value).replace('${workPath}', job.workpath)];
}
/* convert to plain array */
return Object.keys(params).reduce(
(cur, key) => {
const value = params[key];
if (Array.isArray(value)) {
value.forEach(item => cur.push(...parseKeyValuePair(key, item)));
} else {
cur.push(...parseKeyValuePair(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;
}
module.exports = (job, settings, options/*, type */) => {
settings.logger.log(`[${job.uid}] starting action-encode action (ffmpeg)`)
return new Promise((resolve, reject) => {
const params = constructParams(job, settings, options);
getBinary(job, settings).then(binary => {
if (settings.debug) {
settings.logger.log(`[${job.uid}] spawning ffmpeg process: ${binary} ${params.join(' ')}`);
}
const instance = spawn(binary, params, {windowsHide: true});
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);
}
let currentProgress = getDuration(/time=(\d+):(\d+):(\d+).(\d+) bitrate=/, dataString);
if (totalDuration > 0 && currentProgress > 0) {
const currentPercentage = Math.ceil(currentProgress / totalDuration * 100);
if (options.hasOwnProperty('onProgress') && typeof options['onProgress'] == 'function') {
options.onProgress(job, currentPercentage);
}
settings.logger.log(`[${job.uid}] encoding progress ${currentPercentage}%...`);
}
});
instance.stdout.on('data', (data) => settings.debug && settings.logger.log(`[${job.uid}] ${data.toString()}`));
/* on finish (code 0 - success, other - error) */
instance.on('close', (code) => {
if (code !== 0) {
return reject(new Error('Error in action-encode module (ffmpeg) code : ' + code))
}
if (options.hasOwnProperty('onComplete') && typeof options['onComplete'] == 'function') {
options.onComplete(job);
}
resolve(job)
});
}).catch(e => {
return reject(new Error('Error in action-encode module (ffmpeg) ' + e))
});
});
}