-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
80 lines (69 loc) · 2.17 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
var concat = require('concat-stream');
var ffmpeg = require('fluent-ffmpeg');
var PluginError = require('plugin-error');
var path = require('path');
var through2 = require('through2');
module.exports = function (format, handler) {
if (typeof format === 'function') {
handler = format;
format = null;
}
if (format && !handler) {
handler = function (cmd) { return cmd; }
}
if (!format && !handler) {
var msg = 'must include a file format, an ffmpeg handler or both';
throw new PluginError('gulp-fluent-ffmpeg', msg);
}
return through2.obj(function (file, enc, callback) {
var self = this;
// finishes with file and passes it to the next plugin
function next() {
self.push(file);
callback();
}
// runs a modified ffmpeg command on an input/output
function run(input, output) {
var cmd = handler(ffmpeg());
if (format) cmd.format(format);
cmd.input(input);
cmd.output(output);
cmd.on('error', function() {
self.emit.apply(self, ['error'].concat(Array.prototype.slice.call(arguments)))
});
cmd.run();
}
if (file.isNull()) {
return next();
}
// ensure the vinyl file extension is updated
// when the audio is transcoded to another format "e.x. mp3 -> ogg"
if (format) {
var filename = path.basename(file.path, path.extname(file.path));
file.path = path.join(file.path, '..', filename + '.' + format);
}
// we need to pipe the old file contents into ffmpeg,
// buffer the output from ffmpeg, and then set the
// new file contents to the buffered output
if (file.isBuffer()) {
var input = through2();
var output = concat(function (buf) {
if (!Buffer.isBuffer(buf)) buf = null;
file.contents = buf;
next();
});
run(input, output);
input.push(file.contents);
input.push(null);
return;
}
// we need to pipe the old file contents into ffmpeg
// and then set the new file contents to ffmpeg's output
if (file.isStream()) {
var input = file.contents;
var output = file.contents = through2();
run(input, output);
return next();
}
});
};