UNPKG

5.91 kBJavaScriptView Raw
1'use strict'
2
3const { spawn } = require('child_process')
4const duplexify = require('duplexify')
5
6/**
7 * Parse a size string (eg. '240x?')
8 * @func parseSize
9 * @param {String} sizeStr A string in the form of '240x100' or '50%'
10 * @returns {Object} Object containing numeric values of the width and height
11 * of the thumbnail, or the scaling percentage
12 * @throws {Error} Throws on malformed size string
13 */
14function parseSize (sizeStr) {
15 const invalidSizeString = new Error('Invalid size string')
16 const percentRegex = /(\d+)%/g
17 const sizeRegex = /(\d+|\?)x(\d+|\?)/g
18 let size
19
20 const percentResult = percentRegex.exec(sizeStr)
21 const sizeResult = sizeRegex.exec(sizeStr)
22
23 if (percentResult) {
24 size = { percentage: Number.parseInt(percentResult[1]) }
25 } else if (sizeResult) {
26 const sizeValues = sizeResult.map(x => x === '?' ? null : Number.parseInt(x))
27
28 size = {
29 width: sizeValues[1],
30 height: sizeValues[2]
31 }
32 } else {
33 throw invalidSizeString
34 }
35
36 if (size.width === null && size.height === null) {
37 throw invalidSizeString
38 }
39
40 return size
41}
42
43/**
44 * Return an array of string arguments to be passed to ffmpeg
45 * @func buildArgs
46 * @param {String} input The input argument for ffmpeg
47 * @param {String} output The output path for the generated thumbnail
48 * @param {Object} size A size object returned from parseSize
49 * @param {Number} [size.height] The thumbnail height, in pixels
50 * @param {Number} [size.width] The thumbnail width, in pixels
51 * @param {Number} [size.percentage] The thumbnail scaling percentage
52 * @param {String} seek The time to seek, formatted as hh:mm:ss[.ms]
53 * @returns {Array<string>} Array of arguments for ffmpeg
54 */
55function buildArgs (input, output, { width, height, percentage }, seek) {
56 const scaleArg = (percentage)
57 ? `-vf scale=iw*${percentage / 100}:ih*${percentage / 100}`
58 : `-vf scale=${width || -1}:${height || -1}`
59
60 return [
61 '-y',
62 `-i ${input}`,
63 '-vframes 1',
64 `-ss ${seek}`,
65 scaleArg,
66 output
67 ]
68}
69
70/**
71 * Spawn an instance of ffmpeg and generate a thumbnail
72 * @func ffmpegExecute
73 * @param {String} path The path of the ffmpeg binary
74 * @param {Array<string>} args An array of arguments for ffmpeg
75 * @param {stream.Readable} [rstream] A readable stream to pipe data to
76 * the standard input of ffmpeg
77 * @param {stream.Writable} [wstream] A writable stream to receive data from
78 * the standard output of ffmpeg
79 * @returns {Promise} Promise that resolves once thumbnail is generated
80 */
81function ffmpegExecute (path, args, rstream, wstream) {
82 const ffmpeg = spawn(path, args, { shell: true })
83 let stderr = ''
84
85 return new Promise((resolve, reject) => {
86 if (rstream) {
87 rstream.pipe(ffmpeg.stdin)
88 }
89 if (wstream) {
90 ffmpeg.stdout.pipe(wstream)
91 }
92
93 ffmpeg.stderr.on('data', (data) => {
94 stderr += data.toString()
95 })
96 ffmpeg.stderr.on('error', (err) => {
97 reject(err)
98 })
99 ffmpeg.on('exit', (code, signal) => {
100 if (code !== 0) {
101 const err = new Error(`ffmpeg exited ${code}\nffmpeg stderr:\n\n${stderr}`)
102 reject(err)
103 }
104 })
105 ffmpeg.on('close', resolve)
106 })
107}
108
109/**
110 * Spawn an instance of ffmpeg and generate a thumbnail
111 * @func ffmpegStreamExecute
112 * @param {String} path The path of the ffmpeg binary
113 * @param {Array<string>} args An array of arguments for ffmpeg
114 * @param {stream.Readable} [rstream] A readable stream to pipe data to
115 * the standard input of ffmpeg
116 * @returns {Promise} Promise that resolves to ffmpeg stdout
117 */
118function ffmpegStreamExecute (path, args, rstream) {
119 const ffmpeg = spawn(path, args, { shell: true })
120
121 if (rstream) {
122 rstream.pipe(ffmpeg.stdin)
123 }
124
125 return Promise.resolve(ffmpeg.stdout)
126}
127
128/**
129 * Return a duplex stream
130 * @func ffmpegDuplexExecute
131 * @param {String} path The path of the ffmpeg binary
132 * @param {Array<string>} args An array of arguments for ffmpeg
133 * the standard input of ffmpeg
134 * @returns {stream.Duplex} A duplex stream :)
135 */
136function ffmpegDuplexExecute (path, args) {
137 const ffmpeg = spawn(path, args, { shell: true })
138
139 return duplexify(ffmpeg.stdin, ffmpeg.stdout)
140}
141
142/**
143 * Generates a thumbnail from the first frame of a video file
144 * @func genThumbnail
145 * @param {String|stream.Readable} input Path to video, or a read stream
146 * @param {String|stream.Writeable} output Output path of the thumbnail
147 * @param {String} size The size of the thumbnail, eg. '240x240'
148 * @param {Object} [config={}] A configuration object
149 * @param {String} [config.path='ffmpeg'] Path of the ffmpeg binary
150 * @param {String} [config.seek='00:00:00'] Time to seek for videos
151 * @returns {Promise|stream.Duplex} Resolves on completion, or rejects on error
152 */
153function genThumbnail (input, output, size, config = {}) {
154 const ffmpegPath = config.path || process.env.FFMPEG_PATH || 'ffmpeg'
155 const seek = config.seek || '00:00:00'
156 const rstream = typeof input === 'string' ? null : input
157 const wstream = typeof output === 'string' ? null : output
158
159 const parsedSize = parseSize(size)
160 const args = buildArgs(
161 typeof input === 'string' ? `"${input}"` : 'pipe:0',
162 typeof output === 'string' ? `"${output}"` : '-f singlejpeg pipe:1',
163 parsedSize,
164 seek
165 )
166
167 if (input === null && output === null) {
168 return ffmpegDuplexExecute(ffmpegPath, args)
169 }
170 if (output === null) {
171 return ffmpegStreamExecute(ffmpegPath, args, rstream)
172 }
173
174 return ffmpegExecute(ffmpegPath, args, rstream, wstream)
175}
176
177module.exports = genThumbnail