-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathindex.js
114 lines (96 loc) · 2.42 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
/**
* Module dependencies.
*/
var exec = require('child_process').exec;
var escape = require('shell-escape');
var debug = require('debug')('gify');
var mkdirp = require('mkdirp');
var uid = require('uid2');
var path = require('path');
/**
* Expose `gify()`.
*/
module.exports = gify;
/**
* Convert `input` file to `output` gif with the given `opts`:
*
* - `width` max width [500]
* - `height` max height [none]
* - `delay` between frames [0]
* - `rate` frame rate [10]
* - `start` start position in seconds [0]
* - `duration` length of video to convert [auto]
*
* @param {Type} name
* @return {Type}
* @api public
*/
function gify(input, output, opts, fn) {
if (!input) throw new Error('input filename required');
if (!output) throw new Error('output filename required');
// options
if ('function' == typeof opts) {
fn = opts;
opts = {};
} else {
opts = opts || {};
}
// dims
var w = opts.width;
var h = opts.height;
var rate = opts.rate || 10;
var delay = opts.delay || 'auto';
// auto delay
if ('auto' == delay) {
delay = 1000 / rate / 10 | 0;
}
// scale
var scale;
if (w) scale = w + ':-1';
else if (h) scale = '-1:' + h;
else scale = '500:-1';
// tmpfile(s)
var id = uid(10);
var dir = path.resolve('/tmp/' + id);
var tmp = path.join(dir, '/%04d.png');
// escape paths
input = escape([input]);
output = escape([output]);
// normalize
if (process.platform === 'win32') {
input = input.replace(/^'|'$/g, '"');
output = output.replace(/^'|'$/g, '"');
}
function gc(err) {
debug('remove %s', dir);
exec('rm -fr ' + dir);
fn(err);
}
debug('mkdir -p %s', dir);
mkdirp(dir, function(err){
if (err) return fn(err);
// convert to gif
var cmd = ['ffmpeg'];
cmd.push('-i', input);
cmd.push('-filter:v', 'scale=' + scale);
cmd.push('-r', String(rate));
if (opts.start) cmd.push('-ss', String(opts.start));
if (opts.duration) cmd.push('-t', String(opts.duration));
cmd.push(tmp);
cmd = cmd.join(' ');
debug('exec `%s`', cmd);
exec(cmd, function(err){
if (err) return gc(err);
var cmd;
var wildcard = path.join(dir, '/*.png');
cmd = ['gm', 'convert'];
cmd.push('-delay', String(delay || 0));
cmd.push('-loop', '0');
cmd.push(wildcard);
cmd.push(output);
cmd = cmd.join(' ');
debug('exec `%s`', cmd);
exec(cmd, gc);
});
});
}