-
Notifications
You must be signed in to change notification settings - Fork 70
/
index.js
441 lines (368 loc) · 11.5 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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
'use strict'
const fs = require('fs-extra')
const execa = require('execa')
const ora = require('ora')
const ow = require('ow')
const path = require('path')
const pluralize = require('pluralize')
const puppeteer = require('puppeteer')
const tempy = require('tempy')
const { spawn } = require('child_process')
const { sprintf } = require('sprintf-js')
const { cssifyObject } = require('css-in-js-utils')
const lottieScript = fs.readFileSync(require.resolve('lottie-web/build/player/lottie.min'), 'utf8')
const injectLottie = `
<script>
${lottieScript}
</script>
`
/**
* Renders the given Lottie animation via Puppeteer.
*
* You must pass either `path` or `animationData` to specify the Lottie animation.
*
* `output` must be one of the following:
* - An image to capture the first frame only (png or jpg)
* - An image pattern (eg. sprintf format 'frame-%d.png' or 'frame-%012d.jpg')
* - An mp4 video file (requires FFmpeg to be installed)
* - A GIF file (requires Gifski to be installed)
*
* @name renderLottie
* @function
*
* @param {object} opts - Configuration options
* @param {string} opts.output - Path or pattern to store result
* @param {object} [opts.animationData] - JSON exported animation data
* @param {string} [opts.path] - Relative path to the JSON file containing animation data
* @param {number} [opts.width] - Optional output width
* @param {number} [opts.height] - Optional output height
* @param {object} [opts.jpegQuality=90] - JPEG quality for frames (does nothing if using png)
* @param {object} [opts.quiet=false] - Set to true to disable console output
* @param {number} [opts.deviceScaleFactor=1] - Window device scale factor
* @param {string} [opts.renderer='svg'] - Which lottie-web renderer to use
* @param {object} [opts.rendererSettings] - Optional lottie renderer settings
* @param {object} [opts.puppeteerOptions] - Optional puppeteer launch settings
* @param {object} [opts.gifskiOptions] - Optional gifski settings (only for GIF outputs)
* @param {object} [opts.style={}] - Optional JS [CSS styles](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference) to apply to the animation container
* @param {object} [opts.inject={}] - Optionally injects arbitrary string content into the head, style, or body elements.
* @param {string} [opts.inject.head] - Optionally injected into the document <head>
* @param {string} [opts.inject.style] - Optionally injected into a <style> tag within the document <head>
* @param {string} [opts.inject.body] - Optionally injected into the document <body>
* @param {object} [opts.browser] - Optional puppeteer instance to reuse
* @param {object} [opts.progress] - Optional callback to report rendering progress, will be called with the following parameters: (frame, totalFrames)
* @return {Promise}
*/
module.exports = async (opts) => {
const {
output,
animationData = undefined,
path: animationPath = undefined,
jpegQuality = 90,
quiet = false,
deviceScaleFactor = 1,
renderer = 'svg',
rendererSettings = { },
style = { },
inject = { },
puppeteerOptions = { },
ffmpegOptions = {
crf: 20,
profileVideo: 'main',
preset: 'medium'
},
gifskiOptions = {
quality: 80,
fast: false
},
progress = undefined
} = opts
let {
width = undefined,
height = undefined
} = opts
ow(output, ow.string.nonEmpty, 'output')
ow(deviceScaleFactor, ow.number.integer.positive, 'deviceScaleFactor')
ow(renderer, ow.string.oneOf([ 'svg', 'canvas', 'html' ], 'renderer'))
ow(rendererSettings, ow.object.plain, 'rendererSettings')
ow(puppeteerOptions, ow.object.plain, 'puppeteerOptions')
ow(ffmpegOptions, ow.object.exactShape({
crf: ow.number.is((val) => {
return val >= 0 && val <= 51
}),
profileVideo: ow.string.oneOf(['baseline', 'main', 'high', 'high10', 'high422', 'high444']),
preset: ow.string.oneOf([
'ultrafast',
'superfast',
'veryfast',
'faster',
'fast',
'medium',
'slow',
'slower',
'veryslow',
'placebo'])
}))
ow(style, ow.object.plain, 'style')
ow(inject, ow.object.plain, 'inject')
const ext = path.extname(output).slice(1).toLowerCase()
const isApng = (ext === 'apng')
const isGif = (ext === 'gif')
const isMp4 = (ext === 'mp4')
const isPng = (ext === 'png')
const isJpg = (ext === 'jpg' || ext === 'jpeg')
if (!(isApng || isGif || isMp4 || isPng || isJpg)) {
throw new Error(`Unsupported output format "${output}"`)
}
const tempDir = isGif ? tempy.directory() : undefined
const tempOutput = isGif
? path.join(tempDir, 'frame-%012d.png')
: output
const frameType = (isJpg ? 'jpeg' : 'png')
const isMultiFrame = isApng || isMp4 || /%d|%\d{2,3}d/.test(tempOutput)
let lottieData = animationData
if (animationPath) {
if (animationData) {
throw new Error('"animationData" and "path" are mutually exclusive')
}
ow(animationPath, ow.string.nonEmpty, 'path')
lottieData = fs.readJsonSync(animationPath)
} else if (animationData) {
ow(animationData, ow.object.plain.nonEmpty, 'animationData')
} else {
throw new Error('Must pass either "animationData" or "path"')
}
const fps = ~~lottieData.fr
const { w = 640, h = 480 } = lottieData
const aR = w / h
ow(fps, ow.number.integer.positive, 'animationData.fr')
ow(w, ow.number.integer.positive, 'animationData.w')
ow(h, ow.number.integer.positive, 'animationData.h')
if (!(width && height)) {
if (width) {
height = width / aR
} else if (height) {
width = height * aR
} else {
width = w
height = h
}
}
width = width | 0
height = height | 0
const html = `
<html>
<head>
<meta charset="UTF-8">
${inject.head || ''}
${injectLottie}
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background: transparent;
${width ? 'width: ' + width + 'px;' : ''}
${height ? 'height: ' + height + 'px;' : ''}
overflow: hidden;
}
#root {
${cssifyObject(style)}
}
${inject.style || ''}
</style>
</head>
<body>
${inject.body || ''}
<div id="root"></div>
<script>
const animationData = ${JSON.stringify(lottieData)}
let animation = null
let duration
let numFrames
function onReady () {
animation = lottie.loadAnimation({
container: document.getElementById('root'),
renderer: '${renderer}',
loop: false,
autoplay: false,
rendererSettings: ${JSON.stringify(rendererSettings)},
animationData
})
duration = animation.getDuration()
numFrames = animation.getDuration(true)
var div = document.createElement('div')
div.className = 'ready'
document.body.appendChild(div)
}
document.addEventListener('DOMContentLoaded', onReady)
</script>
</body>
</html>
`
// useful for testing purposes
// fs.writeFileSync('test.html', html)
const spinnerB = !quiet && ora('Loading browser').start()
const browser = opts.browser || await puppeteer.launch({
...puppeteerOptions
})
const page = await browser.newPage()
if (!quiet) {
page.on('console', console.log.bind(console))
page.on('error', console.error.bind(console))
}
await page.setViewport({
deviceScaleFactor,
width,
height
})
await page.setContent(html)
await page.waitForSelector('.ready')
const duration = await page.evaluate(() => duration)
const numFrames = await page.evaluate(() => numFrames)
const pageFrame = page.mainFrame()
const rootHandle = await pageFrame.$('#root')
const screenshotOpts = {
omitBackground: true,
type: frameType,
quality: frameType === 'jpeg' ? jpegQuality : undefined
}
if (spinnerB) {
spinnerB.succeed()
}
const numOutputFrames = isMultiFrame ? numFrames : 1
const framesLabel = pluralize('frame', numOutputFrames)
const spinnerR = !quiet && ora(`Rendering ${numOutputFrames} ${framesLabel}`).start()
let ffmpegP
let ffmpeg
let ffmpegStdin
if (isApng || isMp4) {
ffmpegP = new Promise((resolve, reject) => {
const ffmpegArgs = [
'-v', 'error',
'-stats',
'-hide_banner',
'-y'
]
if (isApng) {
ffmpegArgs.push(
'-f', 'image2pipe', '-c:v', 'png', '-r', `${fps}`, '-i', '-',
'-plays', '0'
)
}
if (isMp4) {
let scale = `scale=${width}:-2`
if (width % 2 !== 0) {
if (height % 2 === 0) {
scale = `scale=-2:${height}`
} else {
scale = `scale=${width + 1}:-2`
}
}
ffmpegArgs.push(
'-f', 'lavfi', '-i', `color=c=black:size=${width}x${height}`,
'-f', 'image2pipe', '-c:v', 'png', '-r', `${fps}`, '-i', '-',
'-filter_complex', `[0:v][1:v]overlay[o];[o]${scale}:flags=bicubic[out]`,
'-map', '[out]',
'-c:v', 'libx264',
'-profile:v', ffmpegOptions.profileVideo,
'-preset', ffmpegOptions.preset,
'-crf', ffmpegOptions.crf,
'-movflags', 'faststart',
'-pix_fmt', 'yuv420p',
'-r', fps
)
}
ffmpegArgs.push(
'-frames:v', `${numOutputFrames}`,
'-an', output
)
console.log(ffmpegArgs.join(' '))
ffmpeg = spawn(process.env.FFMPEG_PATH || 'ffmpeg', ffmpegArgs)
const { stdin, stdout, stderr } = ffmpeg
if (!quiet) {
stdout.pipe(process.stdout)
}
stderr.pipe(process.stderr)
stdin.on('error', (err) => {
if (err.code !== 'EPIPE') {
return reject(err)
}
})
ffmpeg.on('exit', async (status) => {
if (status) {
return reject(new Error(`FFmpeg exited with status ${status}`))
} else {
return resolve()
}
})
ffmpegStdin = stdin
})
}
for (let frame = 0; frame < numFrames; ++frame) {
const frameOutputPath = isMultiFrame
? sprintf(tempOutput, frame + 1)
: tempOutput
// eslint-disable-next-line no-undef
await page.evaluate((frame) => animation.goToAndStop(frame, true), frame)
const screenshot = await rootHandle.screenshot({
path: (isApng || isMp4) ? undefined : frameOutputPath,
...screenshotOpts
})
if(progress) {
progress(frame, numFrames)
}
// single screenshot
if (!isMultiFrame) {
break
}
if (isApng || isMp4) {
if (ffmpegStdin.writable) {
ffmpegStdin.write(screenshot)
}
}
}
await rootHandle.dispose()
if (opts.browser) {
await page.close()
} else {
await browser.close()
}
if (spinnerR) {
spinnerR.succeed()
}
if (isApng || isMp4) {
const spinnerF = !quiet && ora(`Generating ${isApng ? 'animated png' : 'mp4'} with FFmpeg`).start()
ffmpegStdin.end()
await ffmpegP
if (spinnerF) {
spinnerF.succeed()
}
} else if (isGif) {
const spinnerG = !quiet && ora(`Generating GIF with Gifski`).start()
const framePattern = tempOutput.replace('%012d', '*')
const escapePath = arg => arg.replace(/(\s+)/g, '\\$1')
const params = [
'-o', escapePath(output),
'--fps', Math.min(gifskiOptions.fps || fps, 50), // most of viewers do not support gifs with FPS > 50
gifskiOptions.fast && '--fast',
'--quality', gifskiOptions.quality,
'--quiet',
escapePath(framePattern)
].filter(Boolean)
const executable = process.env.GIFSKI_PATH || 'gifski'
const cmd = [ executable ].concat(params).join(' ')
await execa.shell(cmd)
if (spinnerG) {
spinnerG.succeed()
}
}
if (tempDir) {
await fs.remove(tempDir)
}
return {
numFrames,
duration
}
}