forked from doomjs/opl3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
427 lines (360 loc) · 13.1 KB
/
cli.js
File metadata and controls
427 lines (360 loc) · 13.1 KB
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
#!/usr/bin/env node
var fs = require('fs');
var chalk = require('chalk');
var ProgressBar = require('progress');
var yargs = require('yargs');
var Duration = require('duration');
var mkdirp = require('mkdirp');
var path = require('path');
var async = require('async');
var glob = require('glob');
var numeral = require('numeral');
try{ var lame = require('lame'); }catch(err){}
try{ var opus = require('node-opus'); }catch(err){}
try{ var ogg = require('ogg'); }catch(err){}
try{ var vorbis = require('vorbis'); }catch(err){}
try{ var Speaker = require('speaker'); }catch(err){}
var opl3 = require('./index');
var Player = opl3.Player;
var LAA = opl3.format.LAA;
var MUS = opl3.format.MUS;
var DRO = opl3.format.DRO;
var IMF = opl3.format.IMF;
var RAW = opl3.format.RAW;
var ROL = opl3.format.ROL;
var WAV = opl3.WAV;
var package = require('./package.json');
var argv = yargs.usage(chalk.cyan('\nOPL3 emulator v' + package.version) + '\n\u001b[97mUsage:\u001b[39m\u001b[49m opl3 <input file> [OPTIONS]')
.example('opl3 D_E1M1.mus');
if (typeof lame != 'undefined') argv = argv.describe('mp3', 'Export to MP3/Lame');
argv = argv.describe('wav', 'Export to WAV');
if (typeof ogg != 'undefined' && typeof vorbis != 'undefined') argv = argv.describe('ogg', 'Export to OGG/Vorbis');
if (typeof opus != 'undefined') argv = argv.describe('opus', 'Export to OGG/Opus');
argv = argv.describe('mid', 'Export to MIDI')
.describe('laa', 'Use LAA format')
.describe('mus', 'Use MUS format')
.describe('dro', 'Use DRO format')
.describe('imf', 'Use IMF format')
.describe('raw', 'Use RAW format')
.describe('rol', 'Use ROL format')
.describe('genmidi', 'Use external GENMIDI lump (only MUS format)')
.describe('normalize', 'PCM audio normalization (default on, turn off with -n0)');
if (typeof Speaker != 'undefined') argv = argv.describe('play', 'Play after processing');
argv = argv.describe('output', 'Output directory')
.describe('help', 'You read that just now')
.alias('h', 'help')
.alias('i', 'genmidi')
.alias('n', 'normalize');
if (typeof Speaker != 'undefined') argv = argv.alias('p', 'play');
argv = argv.alias('o', 'output')
.epilog(chalk.cyan('Copyright (c) 2016 IDDQD@doom.js'))
.updateStrings({
'Options:': '\u001b[97mOptions:\u001b[39m\u001b[49m',
'Examples:': '\u001b[97mExamples:\u001b[39m\u001b[49m'
})
.wrap(yargs.terminalWidth() - 1)
.argv;
if (argv.help) yargs.showHelp();
else{
var start = Date.now();
if (process.argv.length < 3){
yargs.showHelp();
console.log(chalk.red('Input file required!'));
process.exit(1);
}
console.log();
console.log(chalk.cyan('OPL3 emulator v' + package.version));
if (typeof argv.normalize == 'undefined') argv.normalize = 1;
if (!(argv.wav || argv.mp3 || argv.ogg || argv.opus || argv.mid || argv.play)){
argv.wav = true;
argv.mp3 = true;
argv.ogg = true;
argv.opus = true;
argv.mid = true;
}
if (typeof lame == 'undefined') argv.mp3 = false;
if (typeof ogg == 'undefined' || typeof vorbis == 'undefined') argv.ogg = false;
if (typeof opus == 'undefined') argv.opus = false;
if (typeof Speaker == 'undefined') argv.play = false;
var Midi = null;
if (argv.mid) Midi = require('jsmidgen');
var deleteTempFiles = true;
glob(argv._[0], function(err, files){
if (err) throw err;
if (files.length < 1){
console.log(chalk.red('Input file not found!'));
process.exit(1);
}
var clearTempFiles = function(callback){
if (deleteTempFiles){
var tasks = [];
files.forEach(function(filename){
tasks.push(function(next){
var tmpFilename = path.join(argv.output || path.dirname(filename), path.basename(filename + '.tmp'));
fs.unlink(tmpFilename, next);
});
tasks.push(function(next){
var tmp32Filename = path.join(argv.output || path.dirname(filename), path.basename(filename + '.tmp32'));
fs.unlink(tmp32Filename, next);
});
});
async.parallel(tasks, callback);
}else callback();
};
process.on('SIGINT', function(){
clearTempFiles(function(err){
if (err) throw err;
process.exit(1);
});
});
var genmidi = null;
var fileTasks = [];
if (argv.genmidi){
fileTasks.push(function(next){
console.log('Using GENMIDI lump', chalk.yellow(path.resolve(argv.genmidi)));
fs.readFile(argv.genmidi, function(err, buffer){
if (err) return next(err);
genmidi = buffer;
next();
});
});
}
async.series(fileTasks.concat(files.map(function(filename){
var outputDir = argv.output || path.dirname(filename);
mkdirp.sync(outputDir);
filename = path.resolve(filename);
return function(next){
var midiFormat;
if (argv.laa || filename.split('.').pop().toLowerCase() == 'laa') midiFormat = LAA;
else if (argv.mus || filename.split('.').pop().toLowerCase() == 'mus') midiFormat = MUS;
else if (argv.dro || filename.split('.').pop().toLowerCase() == 'dro') midiFormat = DRO;
else if (argv.imf || filename.split('.').pop().toLowerCase() == 'imf') midiFormat = IMF;
else if (argv.raw || filename.split('.').pop().toLowerCase() == 'raw') midiFormat = RAW;
else if (argv.rol || filename.split('.').pop().toLowerCase() == 'rol') midiFormat = ROL;
else{
console.log(chalk.red('Unknown file format!'));
process.exit(1);
}
var pcmBuffer = null;
var midiBuffer = null;
var len = 0;
var tasks = [];
tasks.push(function(callback){
fs.readFile(filename, function(err, buffer){
if (err) return next(err);
var bar = new ProgressBar('Processing ' + chalk.yellow(filename) + ' [:bar] :percent :etas', {
width: 20,
total: buffer.length
});
var player = new Player(midiFormat, {
Midi: Midi,
onlyMidi: argv.mid && !(argv.wav || argv.mp3 || argv.ogg || argv.opus || argv.play),
normalization: typeof argv.normalize == 'undefined' || argv.normalize,
sampleRate: 48000,
instruments: genmidi
});
var converter = new opl3.ConvertTo32Bit();
var tmpWriter = fs.createWriteStream(path.join(outputDir, path.basename(filename + '.tmp')));
var tmp32Writer = fs.createWriteStream(path.join(outputDir, path.basename(filename + '.tmp32')));
if (argv.normalize){
var normbar;
player.normalizer.pipe(tmpWriter);
if (argv.ogg || argv.opus){
player.normalizer.pipe(converter);
converter.pipe(tmp32Writer);
}
}else{
player.pipe(tmpWriter);
if (argv.ogg || argv.opus){
player.pipe(converter);
converter.pipe(tmp32Writer);
}
}
player.load(buffer, function(err, result){
if (err) throw err;
if (result){
pcmBuffer = result;
len = result.byteLength;
}
callback();
});
player.on('error', callback);
player.on('progress', function(perc){
bar.update(perc / 100);
});
player.on('midi', function(midi){
midiBuffer = new Buffer(midi);
});
player.on('normalization', function(perc){
if (!normbar){
normbar = new ProgressBar('Normalizing ' + chalk.yellow(filename) + ' [:bar] :percent :etas', {
width: 20,
total: 100
});
}
normbar.update(perc / 100);
});
player.on('gain', function(scale){
console.log('Normalization gain ' + chalk.green('x' + numeral(scale).format('0.00')));
});
});
});
if (argv.mid){
tasks.push(function(callback){
if (midiBuffer){
var midiFilename = typeof argv.mid == 'string' ? argv.mid : path.join(outputDir, path.basename(filename.slice(0, filename.lastIndexOf('.')) + '.mid'));
mkdirp.sync(path.dirname(midiFilename));
midiFilename = path.resolve(midiFilename);
fs.writeFile(midiFilename, midiBuffer, 'binary', function(err){
if (err) return callback(err);
console.log('MIDI exported to ' + chalk.yellow(midiFilename));
callback();
});
}else callback();
});
}
if (argv.wav){
tasks.push(function(callback){
var wavFilename = typeof argv.wav == 'string' ? argv.wav : path.join(outputDir, path.basename(filename.slice(0, filename.lastIndexOf('.')) + '.wav'));
mkdirp.sync(path.dirname(wavFilename));
wavFilename = path.resolve(wavFilename);
fs.writeFile(wavFilename, new Buffer(WAV(pcmBuffer, { sampleRate: 48000, bitDepth: 16 })), function(err){
if (err) throw err;
console.log('WAV exported to ' + chalk.yellow(wavFilename));
callback();
});
});
}
if (argv.mp3){
tasks.push(function(callback){
var bar = new ProgressBar('Encoding ' + chalk.yellow(filename) + ' to MP3/Lame [:bar] :percent :etas', {
width: 20,
total: 100
});
var encoder = new lame.Encoder({
// input
channels: 2, // 2 channels (left and right)
bitDepth: 16, // 16-bit samples
sampleRate: 48000 // 48,000 Hz sample rate
});
var mp3Filename = typeof argv.mp3 == 'string' ? argv.mp3 : path.join(outputDir, path.basename(filename.slice(0, filename.lastIndexOf('.')) + '.mp3'));
mkdirp.sync(path.dirname(mp3Filename));
mp3Filename = path.resolve(mp3Filename);
var writer = fs.createWriteStream(mp3Filename);
var reader = fs.createReadStream(path.join(outputDir, path.basename(filename + '.tmp')));
reader.pipe(encoder);
encoder.pipe(writer);
var pos = 0;
reader.on('data', function(chunk){
pos += chunk.length;
bar.update(pos / len);
});
reader.on('end', function(){
encoder.end();
callback();
});
reader.on('error', function(err){
console.log(chalk.red('Failed to export ' + mp3Filename));
callback(err);
});
});
}
if (argv.ogg){
tasks.push(function(callback){
var bar = new ProgressBar('Encoding ' + chalk.yellow(filename) + ' to OGG/Vorbis [:bar] :percent :etas', {
width: 20,
total: 100
});
var oe = new ogg.Encoder();
var ve = new vorbis.Encoder({
sampleRate: 48000
});
var oggFilename = typeof argv.ogg == 'string' ? argv.ogg : path.join(outputDir, path.basename(filename.slice(0, filename.lastIndexOf('.')) + '.ogg'));
mkdirp.sync(path.dirname(oggFilename));
var writer = fs.createWriteStream(oggFilename);
var reader = fs.createReadStream(path.join(outputDir, path.basename(filename + '.tmp32')));
reader.pipe(ve);
ve.pipe(oe.stream());
oe.pipe(writer);
var pos = 0;
reader.on('data', function(chunk){
pos += chunk.length;
bar.update(pos / (len * 2));
});
reader.on('end', function(){
callback();
});
reader.on('error', function(err){
console.log(chalk.red('Failed to export ' + oggFilename));
callback(err);
});
});
}
if (argv.opus){
tasks.push(function(callback){
var bar = new ProgressBar('Encoding ' + chalk.yellow(filename) + ' to OGG/Opus [:bar] :percent :etas', {
width: 20,
total: 100
});
var oe = new ogg.Encoder();
var pe = new opus.Encoder(48000, 2);
var opusFilename = typeof argv.opus == 'string' ? argv.opus : path.join(outputDir, path.basename(filename.slice(0, filename.lastIndexOf('.')) + '.opus'));
mkdirp.sync(path.dirname(opusFilename));
var writer = fs.createWriteStream(opusFilename);
var reader = fs.createReadStream(path.join(outputDir, path.basename(filename + '.tmp')));
reader.pipe(pe);
pe.pipe(oe.stream());
oe.pipe(writer);
var pos = 0;
reader.on('data', function(chunk){
pos += chunk.length;
bar.update(pos / len);
});
reader.on('end', function(){
callback();
});
reader.on('error', function(err){
console.log(chalk.red('Failed to export ' + opusFilename));
callback(err);
});
});
}
if (argv.play){
tasks.push(function(callback){
var bar = new ProgressBar(chalk.magenta('Playing audio ') + chalk.yellow(filename) + ' [:bar] :percent :etas', {
width: 20,
total: 100
});
var speaker = new Speaker({
channels: 2, // 2 channels
bitDepth: 16, // 16-bit samples
sampleRate: 48000 // 48,000 Hz sample rate
});
var reader = fs.createReadStream(path.join(outputDir, path.basename(filename + '.tmp')));
reader.pipe(speaker);
var pos = 0;
reader.on('data', function(chunk){
pos += chunk.length;
bar.update(pos / len);
});
reader.on('end', function(){
speaker.end();
callback();
});
reader.on('error', function(err){
console.log(chalk.red('Failed to play ' + filename));
callback(err);
});
});
}
async.series(tasks, function(err){
if (err) return next(err);
clearTempFiles(next);
});
};
})), function(err){
if (err) console.log(chalk.red(err));
console.log('Finished in ' + chalk.green(new Duration(new Date(0), new Date(Date.now() - start)).toString(1)));
});
});
}