-
Notifications
You must be signed in to change notification settings - Fork 2
/
waudsprite.js
279 lines (249 loc) · 8.92 KB
/
waudsprite.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
var fs = require('fs')
var path = require('path')
var async = require('async')
var _ = require('underscore')._
var defaults = {
output: "sprite",
path: "",
export: "m4a",
format: null,
autoplay: null,
loop: [],
gap: 1,
minlength: 0,
bitrate: 128,
vbr: -1,
samplerate: 44100,
channels: 1,
rawparts: "",
logger: {
debug: function () {
},
info: function () {
},
log: function () {
}
}
};
module.exports = function (files) {
if (files.length === 1 && files[0].indexOf("*.") > -1) {
var filesList = files[0].split(/[\/\\]/);
var extension;
var basePath = "./";
if (filesList.length > 1) {
var lastElement = filesList.pop();
extension = lastElement.substring(1, lastElement.length);
basePath = filesList.join("/");
}
else extension = filesList[0].substring(1, filesList[0].length);
files = [];
getRecursiveFiles(basePath);
}
var opts = {}, callback = function () {
};
if (arguments.length == 2) {
callback = arguments[1];
}
else if (arguments.length >= 3) {
opts = arguments[1];
callback = arguments[2];
}
if (!files || !files.length) return callback(new Error("No input files specified."));
opts = _.extend({}, defaults, opts);
// make sure output directory exists
var outputDir = path.dirname(opts.output);
if (!fs.existsSync(outputDir)) {
require("mkdirp").sync(outputDir);
}
var offsetCursor = 0;
var wavArgs = ["-ar", opts.samplerate, "-ac", opts.channels, "-f", "s16le"];
var tempFile = mktemp("audiosprite");
opts.logger.debug("Created temporary file", {file: tempFile});
var json = {
src: "", sprite: []
};
spawn("ffmpeg", ["-version"]).on("exit", function (code) {
if (code) {
callback(new Error("ffmpeg was not found on your path"));
}
processFiles();
});
function getRecursiveFiles(folder) {
try {
var dirfiles = fs.readdirSync(folder);
for (var i = 0; i < dirfiles.length; i++) {
var stats = fs.statSync(folder + "/" + dirfiles[i]);
if (stats.isDirectory()) getRecursiveFiles(folder + "/" + dirfiles[i]);
else {
var name = folder + "/" + dirfiles[i];
if (dirfiles[i].indexOf(extension) > -1) files.push(name);
}
}
}
catch (e) {
console.log("can't read directory - " + folder);
}
}
function mktemp(prefix) {
var tmpdir = require("os").tmpDir() || ".";
return path.join(tmpdir, prefix + "." + Math.random().toString().substr(2));
}
function spawn(name, opt) {
opts.logger.debug("Spawn", {cmd: [name].concat(opt).join(" ")});
return require("child_process").spawn(name, opt);
}
function pad(num, size) {
var str = num.toString();
while (str.length < size) {
str = "0" + str;
}
return str;
}
function makeRawAudioFile(src, cb) {
var dest = mktemp("audiosprite");
opts.logger.debug("Start processing", {file: src});
fs.exists(src, function (exists) {
if (exists) {
var ffmpeg = spawn("ffmpeg", ["-i", path.resolve(src)]
.concat(wavArgs).concat("pipe:"));
ffmpeg.stdout.pipe(fs.createWriteStream(dest, {flags: "w"}));
ffmpeg.on("exit", function (code, signal) {
if (code) {
return cb({
msg: "File could not be added",
file: src,
retcode: code,
signal: signal
});
}
cb(null, dest);
})
}
else {
cb({msg: "File does not exist", file: src});
}
});
}
function appendFile(name, src, dest, cb) {
var size = 0;
var reader = fs.createReadStream(src);
var writer = fs.createWriteStream(dest, {
flags: "a"
});
reader.on("data", function (data) {
size += data.length;
});
reader.on("close", function () {
var originalDuration = size / opts.samplerate / opts.channels / 2;
opts.logger.info("File added OK", {file: src, duration: originalDuration});
var extraDuration = Math.max(0, opts.minlength - originalDuration);
var duration = originalDuration + extraDuration;
json.sprite.push({
name: name,
start: offsetCursor,
duration: duration,
loop: name === opts.autoplay || opts.loop.indexOf(name) !== -1
});
offsetCursor += originalDuration;
appendSilence(opts.gap > 0 ? extraDuration + Math.ceil(duration) - duration + opts.gap : 0, dest, cb);
});
reader.pipe(writer);
}
function appendSilence(duration, dest, cb) {
var buffer = new Buffer(Math.round(opts.samplerate * 2 * opts.channels * duration));
buffer.fill(0);
var writeStream = fs.createWriteStream(dest, {flags: "a"});
writeStream.end(buffer);
writeStream.on("close", function () {
opts.logger.info("Silence gap added", {duration: duration});
offsetCursor += duration;
cb();
})
}
function exportFile(src, dest, ext, opt, store, cb) {
var outfile = dest + "." + ext;
spawn("ffmpeg", ["-y", "-ar", opts.samplerate, "-ac", opts.channels, "-f", "s16le", "-i", src]
.concat(opt).concat(outfile))
.on("exit", function (code, signal) {
if (code) {
return cb({
msg: "Error exporting file",
format: ext,
retcode: code,
signal: signal
});
}
opts.logger.info("Exported " + ext + " OK", {file: outfile});
if (store) {
json.src = path.basename(outfile);
}
cb();
});
}
function processFiles() {
var formats = {
aiff: []
, wav: []
, ac3: ["-acodec", "ac3", "-ab", opts.bitrate + "k"]
, mp3: ["-ar", opts.samplerate, "-f", "mp3"]
, mp4: ["-ab", opts.bitrate + "k"]
, m4a: ["-ab", opts.bitrate + "k"]
, ogg: ["-acodec", "libvorbis", "-f", "ogg", "-ab", opts.bitrate + "k"]
};
if (opts.vbr >= 0 && opts.vbr <= 9) {
formats.mp3 = formats.mp3.concat(["-aq", opts.vbr]);
}
else {
formats.mp3 = formats.mp3.concat(["-ab", opts.bitrate + "k"]);
}
if (opts.export.length) {
formats = opts.export.split(",").reduce(function (memo, val) {
if (formats[val]) {
memo[val] = formats[val];
}
return memo;
}, {});
}
var rawparts = opts.rawparts.length ? opts.rawparts.split(",") : null;
var i = 0;
async.forEachSeries(files, function (file, cb) {
i++;
makeRawAudioFile(file, function (err, tmp) {
if (err) {
return cb(err);
}
function tempProcessed() {
fs.unlinkSync(tmp);
cb();
}
var name = path.basename(file).replace(/\.[a-zA-Z0-9]+$/, "");
appendFile(name, tmp, tempFile, function (err) {
if (rawparts != null ? rawparts.length : void 0) {
async.forEachSeries(rawparts, function (ext, cb) {
opts.logger.debug("Start export slice", {name: name, format: ext, i: i})
exportFile(tmp, opts.output + "_" + pad(i, 3), ext, formats[ext]
, false, cb)
}, tempProcessed);
} else {
tempProcessed();
}
})
})
}, function (err) {
if (err) {
console.log(err);
return callback(new Error("Error adding file"));
}
async.forEachSeries(Object.keys(formats), function (ext, cb) {
opts.logger.debug("Start export", {format: ext});
exportFile(tempFile, opts.output, ext, formats[ext], true, cb);
}, function (err) {
if (err) {
return callback(new Error(err.msg));
}
fs.unlinkSync(tempFile);
callback(null, json);
});
});
}
}