-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.js
473 lines (358 loc) · 13.1 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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
[wx-voice]
Convert audio files between Tencent apps (Weixin / Wechat, QQ) and Silk codec with other general format such as MP3 and M4A
Github: https://github.com/Ang-YC/wx-voice
Author: AngYC <me@angyc.com>
*/
'use strict';
const EventEmitter = require('events');
const { spawn } = require('child_process');
const Ffmpeg = require('fluent-ffmpeg');
const os = require('os');
const fs = require('fs');
const path = require('path');
const which = require('which');
const dataUri = require('strong-data-uri');
const readChunk = require('read-chunk');
const randomatic = require('randomatic');
class WxVoice extends EventEmitter {
constructor(tempDir = os.tmpdir(), ffmpegPath) {
super();
this._tempDir = path.resolve(tempDir);
this._ffmpegPath = ffmpegPath;
// Check if dependencies are available
this._checkDependencies();
}
decode(input, output, options, callback) {
var ext, buffer,
fileFormat;
// Make it into absolute path
input = path.resolve(input);
output = path.resolve(output);
// Set options default to {}
if (options === undefined) {
options = {};
}
// Set format as extension if undefined
if (options.format === undefined) {
ext = path.extname(output);
if (ext[0] == ".")
ext = ext.substr(1);
options.format = ext;
}
// Callback after decode is done
callback = validateFunction(callback);
// Check if file exists and get file format
try {
buffer = readChunk.sync(input, 0, 4100);
fileFormat = fileType(buffer);
} catch (e) {
this.emit("error", e);
return callback();
}
// Check if file is silk, webm or others
if (fileFormat && fileFormat.mime == "audio/silk") {
// Default frequency
var outputPCM = (options.format == "pcm"),
silkFrequency = (outputPCM && options.frequency) ? options.frequency : 24000;
// Use Silk if it can be decoded
this._decodeSilk(input, silkFrequency, (tempFile) => {
input = tempFile || input;
// Output raw PCM directly
if (outputPCM && tempFile) {
copy(tempFile, output, (err) => {
this._deleteTempFile(tempFile);
callback(err ? undefined : output);
});
// Else Continue for other formats
} else {
this._convert(tempFile != undefined, false, input, output, options, (res) => {
this._deleteTempFile(tempFile);
callback(res);
});
}
});
} else {
// Use WebM output if it is WebM
this._tryWebM(input, (tempFile) => {
input = tempFile || input;
this._convert(false, false, input, output, options, (res) => {
this._deleteTempFile(tempFile);
callback(res);
});
});
}
}
encode(input, output, options, callback) {
var ext, tempFile;
// Make it into absolute path
input = path.resolve(input);
output = path.resolve(output);
// Set options default to {}
if (options === undefined) {
options = {};
}
// Set format as extension if undefined
if (options.format === undefined) {
ext = path.extname(output);
if (ext[0] == ".")
ext = ext.substr(1);
options.format = ext;
}
// Callback after encode is done
callback = validateFunction(callback);
// Check if file exists
if (!fs.existsSync(input)) {
this.emit("error", "Error: ENOENT: no such file or directory, open '" + input + "'");
return callback();
}
if (options.format == "silk" || options.format == "silk_amr") {
tempFile = this._getTempFile(input + ".pcm");
this._convert(false, true, input, tempFile, options, (tempOutput) => {
if (tempOutput) {
this._encodeSilk(tempOutput, output, options.format, (res) => {
this._deleteTempFile(tempOutput);
callback(res);
});
} else {
callback();
}
});
} else if (options.format == "webm") {
tempFile = this._getTempFile(input + ".temp.webm");
this._convert(false, true, input, tempFile, options, (tempOutput) => {
if (tempOutput) {
this._encodeWebM(tempOutput, output, (res) => {
this._deleteTempFile(tempOutput);
callback(res);
});
} else {
callback();
}
});
} else {
this.emit("error", new Error(options.format + " is not a valid encode format, only silk, silk_amr and webm allowed"));
return callback();
}
}
duration(filePath, callback) {
Ffmpeg.ffprobe(filePath, (err, metadata) => {
if (err) return callback(0);
if (metadata && metadata.format) {
var duration = parseFloat(metadata.format.duration);
duration = (isNaN(duration)) ? 0 : duration;
}
callback(duration);
});
}
_convert(rawInput, rawOutput, input, output, options, callback) {
var started = false,
format = options.format,
bitrate = options.bitrate,
frequency = options.frequency,
channels = options.channels,
ffmpeg = Ffmpeg(input)
.on("start", onStart)
.on("error", onError)
.on("end", onEnd);
// Additional parameters for raw
if (rawInput) {
ffmpeg = ffmpeg.inputFormat("s16le").inputOptions(["-ar 24000", "-ac 1"]);
} else if (rawOutput) {
if (format == "silk" || format == "silk_amr") {
format = "s16le";
ffmpeg = ffmpeg.outputOptions(["-ar 24000", "-ac 1"]);
} else if (format == "webm") {
ffmpeg = ffmpeg.outputOptions(["-ar 48000", "-ac 1"]).audioCodec("opus");
}
}
// Other settings
if (bitrate) { ffmpeg = ffmpeg.audioBitrate(bitrate); }
if (frequency) { ffmpeg = ffmpeg.audioFrequency(frequency); }
if (channels) { ffmpeg = ffmpeg.audioChannels(channels); }
// Format dependent
if (format == "m4a") {
ffmpeg = ffmpeg.audioCodec("aac");
} else if (format == "pcm") {
ffmpeg = ffmpeg.format("s16le");
} else {
ffmpeg = ffmpeg.format(format);
}
// Output
ffmpeg.noVideo().save(output);
function onStart(commandLine) {
started = true;
}
function onError(err, stdout, stderr) {
started = false;
callback();
}
function onEnd(stdout, stderr) {
if (started) {
started = false;
callback(output);
}
}
}
_decodeSilk(input, frequency, callback) {
var output = this._getTempFile(input + ".pcm"),
decoder = spawn(this._getSilkSDK("decoder"), [input, output, "-Fs_API", frequency]);
// Allow it to output
decoder.stdout.on('data', (data) => { });
decoder.stderr.on('data', (data) => { });
decoder.on('close', (code) => {
if (code == 1) { // Error occured
callback();
} else { // Success
callback(output);
}
});
}
_encodeSilk(input, output, type, callback) {
var flag = (type == "silk_amr" ? "-tencent_amr" : "-tencent"),
encoder = spawn(this._getSilkSDK("encoder"), [input, output, flag]);
// Allow it to output
encoder.stdout.on('data', (data) => { });
encoder.stderr.on('data', (data) => { });
encoder.on('close', (code) => {
if (code == 1) { // Error occured
callback();
} else { // Success
callback(output);
}
});
}
_tryWebM(input, callback) {
var output = this._getTempFile(input + ".webm"),
base64 = "";
fs.readFile(input, (err, data) => {
if (err) return callback();
// Convert to string and check if Data URI is WebM
base64 = data.toString();
if (base64.startsWith("data:audio/webm;base64,")) {
this._parseWebM(base64, output, callback);
} else {
callback();
}
});
}
_parseWebM(base64, output, callback) {
var buffer;
// Convert to buffer
try {
buffer = dataUri.decode(base64);
} catch (e) {
return callback();
}
// Write to file
fs.writeFile(output, buffer, (err) => {
if (err) return callback();
callback(output);
});
}
_encodeWebM(input, output, callback) {
var uri = "";
fs.readFile(input, (err, data) => {
if (err) return callback();
uri = dataUri.encode(data, "audio/webm");
// Write to file
fs.writeFile(output, uri, (err) => {
if (err) return callback();
callback(output);
});
});
}
_checkDependencies() {
var silkDecoder = this._getSilkSDK("decoder"),
silkEncoder = this._getSilkSDK("encoder"),
ffmpegPath = this._ffmpegPath;
// Check if Silk SDK is available
if (!fs.existsSync(silkDecoder) || !fs.existsSync(silkEncoder)) {
throw new Error("Silk SDK not found, make sure you compiled using command: wx-voice compile");
}
if (ffmpegPath && fs.existsSync(ffmpegPath)) {
this._ffmpegPath = path.resolve(ffmpegPath);
Ffmpeg.setFfmpegPath(this._ffmpegPath);
} else if (ffmpegPath = this._getFfmpegPath()) {
this._ffmpegPath = path.resolve(ffmpegPath);
} else {
throw new Error("FFMPEG not found");
}
}
_getSilkSDK(type) {
return path.resolve(__dirname, "silk", type);
}
_getFfmpegPath() {
// Get FFMPEG Path (Sync version of _getFfmpegPath in fluent-ffmpeg)
var path;
// Search in FFMPEG_PATH
if (process.env.FFMPEG_PATH && fs.existsSync(process.env.FFMPEG_PATH)) {
path = process.env.FFMPEG_PATH;
// Search in PATH, return null if not found
} else {
path = which.sync("ffmpeg", { nothrow: true });
}
// Return undefined
if (path === null || path === "") path = undefined;
return path;
}
_getTempFile(fileName, noPrefix) {
var file = path.basename(fileName);
if (!noPrefix)
file = randomatic("a0", 16) + "_" + file;
return path.resolve(this._tempDir, file);
}
_deleteTempFile(fileName) {
if (fileName) {
fileName = this._getTempFile(fileName, true);
fs.unlink(fileName, () => {});
}
}
}
// Utililities
function fileType(input) {
const buf = new Uint8Array(input);
if (!(buf && buf.length > 1)) {
return null;
}
const check = (header) => {
for (let i = 0; i < header.length; i++) {
if (header[i] !== buf[i]) {
return false;
}
}
return true;
};
if (check([0x23, 0x21, 0x53, 0x49, 0x4C, 0x4B, 0x0A]) || // Skype V1: #!SILK\n (https://tools.ietf.org/html/draft-spittka-silk-payload-format-00)
check([0x23, 0x21, 0x53, 0x49, 0x4C, 0x4B, 0x5F, 0x56, 0x33]) || // Skype V3: #!SILK_V3
check([0x02, 0x23, 0x21, 0x53, 0x49, 0x4C, 0x4B, 0x5F, 0x56, 0x33]) || // Tencent variation: .#!SILK_V3
check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A, 0x02, 0x23, 0x21, 0x53, 0x49, 0x4C, 0x4B, 0x5F, 0x56, 0x33])) { // Tencent AMR variation: #!AMR\n.#!SILK_V3
return {
ext: 'sil',
mime: 'audio/silk'
};
}
return null;
}
function isFunction(f) {
return (f && typeof f === 'function');
}
function validateFunction(f) {
return (isFunction(f) ? f : function() { });
}
function copy(source, target, callback) {
var completed = false;
var rd = fs.createReadStream(source);
var wr = fs.createWriteStream(target);
rd.on("error", done);
wr.on("error", done);
wr.on("close", (ex) => { done(); });
rd.pipe(wr);
function done(err) {
if (!completed) {
completed = true;
callback(err);
}
}
}
module.exports = WxVoice;