UNPKG

6.19 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 if (stderr.includes('nothing was encoded')) {
105 const err = new Error(`ffmpeg failed to encode file\nffmpeg stderr:\n\n${stderr}`)
106 reject(err)
107 }
108 })
109 ffmpeg.on('close', resolve)
110 })
111}
112
113/**
114 * Spawn an instance of ffmpeg and generate a thumbnail
115 * @func ffmpegStreamExecute
116 * @param {String} path The path of the ffmpeg binary
117 * @param {Array<string>} args An array of arguments for ffmpeg
118 * @param {stream.Readable} [rstream] A readable stream to pipe data to
119 * the standard input of ffmpeg
120 * @returns {Promise} Promise that resolves to ffmpeg stdout
121 */
122function ffmpegStreamExecute (path, args, rstream) {
123 const ffmpeg = spawn(path, args, { shell: true })
124
125 if (rstream) {
126 rstream.pipe(ffmpeg.stdin)
127 }
128
129 return Promise.resolve(ffmpeg.stdout)
130}
131
132/**
133 * Return a duplex stream
134 * @func ffmpegDuplexExecute
135 * @param {String} path The path of the ffmpeg binary
136 * @param {Array<string>} args An array of arguments for ffmpeg
137 * the standard input of ffmpeg
138 * @returns {stream.Duplex} A duplex stream :)
139 */
140function ffmpegDuplexExecute (path, args) {
141 const ffmpeg = spawn(path, args, { shell: true })
142
143 return duplexify(ffmpeg.stdin, ffmpeg.stdout)
144}
145
146/**
147 * Generates a thumbnail from the first frame of a video file
148 * @func genThumbnail
149 * @param {String|stream.Readable} input Path to video, or a read stream
150 * @param {String|stream.Writeable} output Output path of the thumbnail
151 * @param {String} size The size of the thumbnail, eg. '240x240'
152 * @param {Object} [config={}] A configuration object
153 * @param {String} [config.path='ffmpeg'] Path of the ffmpeg binary
154 * @param {String} [config.seek='00:00:00'] Time to seek for videos
155 * @returns {Promise|stream.Duplex} Resolves on completion, or rejects on error
156 */
157function genThumbnail (input, output, size, config = {}) {
158 const ffmpegPath = config.path || process.env.FFMPEG_PATH || 'ffmpeg'
159 const seek = config.seek || '00:00:00'
160 const rstream = typeof input === 'string' ? null : input
161 const wstream = typeof output === 'string' ? null : output
162
163 let args = ''
164 if (config.args) {
165 args = config.args
166 } else {
167 const parsedSize = parseSize(size)
168
169 args = buildArgs(
170 typeof input === 'string' ? `"${input}"` : 'pipe:0',
171 typeof output === 'string' ? `"${output}"` : '-f singlejpeg pipe:1',
172 parsedSize,
173 seek
174 )
175 }
176
177 if ((input === null && output === null) || config.args) {
178 return ffmpegDuplexExecute(ffmpegPath, args)
179 }
180 if (output === null) {
181 return ffmpegStreamExecute(ffmpegPath, args, rstream)
182 }
183
184 return ffmpegExecute(ffmpegPath, args, rstream, wstream)
185}
186
187module.exports = genThumbnail