-
Notifications
You must be signed in to change notification settings - Fork 0
/
splitter.js
452 lines (247 loc) · 10.3 KB
/
splitter.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
/****************************************************************************
* splitter.js
* openacousticdevices.info
* February 2021
*****************************************************************************/
'use strict';
const fs = require('fs');
const path = require('path');
const wavHandler = require('./wavHandler.js');
const guanoHandler = require('./guanoHandler.js');
const filenameHandler = require('./filenameHandler.js');
/* Debug constant */
const DEBUG = false;
/* File buffer constants */
const NUMBER_OF_BYTES_IN_SAMPLE = 2;
const HEADER_BUFFER_SIZE = 32 * 1024;
const FILE_BUFFER_SIZE = 32 * 1024;
/* Time constants */
const SECONDS_IN_DAY = 24 * 60 * 60;
const MILLISECONDS_IN_SECOND = 1000;
const TIMESTAMP_REGEX = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d/;
/* Buffers for reading data */
const fileBuffer = Buffer.alloc(FILE_BUFFER_SIZE);
const headerBuffer = Buffer.alloc(HEADER_BUFFER_SIZE);
/* Date functions */
function digits (value, number) {
const string = '00000' + value;
return string.substring(string.length - number, string.length);
}
function formatFilename (timestamp, existingPostfix) {
const date = new Date(timestamp);
let filename = date.getUTCFullYear() + digits(date.getUTCMonth() + 1, 2) + digits(date.getUTCDate(), 2) + '_' + digits(date.getUTCHours(), 2) + digits(date.getUTCMinutes(), 2) + digits(date.getUTCSeconds(), 2);
filename += existingPostfix + '.WAV';
return filename;
}
function formatTimestamp (timestamp) {
const date = new Date(timestamp);
const string = date.getUTCFullYear() + '-' + digits(date.getUTCMonth() + 1, 2) + '-' + digits(date.getUTCDate(), 2) + 'T' + digits(date.getUTCHours(), 2) + ':' + digits(date.getUTCMinutes(), 2) + ':' + digits(date.getUTCSeconds(), 2);
return string;
}
/* Write the output file */
function writeOutputFile (fi, outputPath, header, guano, comment, contents, offset, length, callback) {
if (DEBUG) {
console.log('Path: ' + outputPath);
console.log('Comment: ' + comment);
console.log('Contents: ' + contents);
console.log('Offset: ' + offset);
console.log('Length: ' + length);
console.log('Duration: ' + Math.round(length / header.wavFormat.samplesPerSecond / NUMBER_OF_BYTES_IN_SAMPLE * MILLISECONDS_IN_SECOND));
}
const fo = fs.openSync(outputPath, 'w');
/* Update WAV header and GUANO */
if (comment) wavHandler.updateComment(header, comment);
if (guano && contents) guanoHandler.updateContents(guano, contents);
wavHandler.updateSizes(header, guano, length);
/* Write the WAV header */
wavHandler.writeHeader(headerBuffer, header);
fs.writeSync(fo, headerBuffer, 0, header.size, null);
/* Write the data */
let index = offset;
while (index < offset + length) {
/* Determine the number of bytes to write */
const numberOfBytes = Math.min(FILE_BUFFER_SIZE, offset + length - index);
/* Read from input file, and then write file buffer */
fs.readSync(fi, fileBuffer, 0, numberOfBytes, header.size + index);
fs.writeSync(fo, fileBuffer, 0, numberOfBytes, null);
/* Increment bytes written and move to next file summary component if appropriate */
index += numberOfBytes;
/* Callback with progress */
if (callback) callback((index - offset) / length);
}
/* Write the GUANO */
if (guano) {
guanoHandler.writeGuano(fileBuffer, guano);
fs.writeSync(fo, fileBuffer, 0, guano.size, null);
}
/* Close the output file */
fs.closeSync(fo);
}
/* Split a WAV file */
function split (inputPath, outputPath, prefix, maximumFileDuration, callback) {
/* Check parameter */
prefix = prefix || '';
maximumFileDuration = maximumFileDuration || SECONDS_IN_DAY;
if (maximumFileDuration !== Math.round(maximumFileDuration)) {
return {
success: false,
error: 'Maximum file duration must be an integer.'
};
}
if (maximumFileDuration <= 0) {
return {
success: false,
error: 'Maximum file duration must be greater than zero.'
};
}
if (typeof prefix !== 'string') {
return {
success: false,
error: 'Filename prefix must be a string.'
};
}
/* Open input file */
let fi;
try {
fi = fs.openSync(inputPath, 'r');
} catch (e) {
return {
success: false,
error: 'Could not open input file.'
};
}
/* Check the output path */
outputPath = outputPath || path.parse(inputPath).dir;
if (fs.lstatSync(outputPath).isDirectory() === false) {
return {
success: false,
error: 'Destination path is not a directory.'
};
}
/* Find the input file size */
let fileSize;
try {
fileSize = fs.statSync(inputPath).size;
} catch (e) {
return {
success: false,
error: 'Could not read input file size.'
};
}
if (fileSize === 0) {
return {
success: false,
error: 'Input file has zero size.'
};
}
/* Read the header */
try {
fs.readSync(fi, headerBuffer, 0, FILE_BUFFER_SIZE, 0);
} catch (e) {
return {
success: false,
error: 'Could not read the input WAV header.'
};
}
/* Check the header */
const headerCheck = wavHandler.readHeader(headerBuffer, fileSize);
if (headerCheck.success === false) return headerCheck;
/* Extract the header */
const header = headerCheck.header;
/* Check the filename against header */
const inputFilename = path.parse(inputPath).base;
const filenameCheck = filenameHandler.checkFilenameAgainstHeader(filenameHandler.SPLIT, inputFilename, header.icmt.comment, header.iart.artist);
if (filenameCheck.success === false) return filenameCheck;
/* Extract original timestamp and existing prefix and postfix */
const existingPostfix = filenameCheck.existingPostfix;
const existingPrefix = filenameCheck.existingPrefix;
const originalTimestamp = filenameCheck.originalTimestamp;
/* Determine settings from the input file */
const inputFileDataSize = header.data.size;
/* Make the initial empty output file list */
const outputFileList = [];
/* Main loop generating files */
let numberOfBytesProcessed = 0;
let timestamp = originalTimestamp;
while (numberOfBytesProcessed < inputFileDataSize) {
/* Determine the number of bytes to write */
const numberOfBytes = Math.min(maximumFileDuration * header.wavFormat.samplesPerSecond * NUMBER_OF_BYTES_IN_SAMPLE, inputFileDataSize - numberOfBytesProcessed);
/* Add the output file if appropriate */
outputFileList.push({
timestamp: timestamp,
offset: numberOfBytesProcessed,
length: numberOfBytes
});
timestamp += maximumFileDuration * MILLISECONDS_IN_SECOND;
numberOfBytesProcessed += numberOfBytes;
}
/* Show the pruned output */
for (let i = 0; i < outputFileList.length; i += 1) {
if (DEBUG) console.log(outputFileList[i]);
}
/* Read the GUANO if present */
let guano, contents;
if (header.data.size + header.size < fileSize) {
const numberOfBytes = Math.min(fileSize - header.size - header.data.size, HEADER_BUFFER_SIZE);
try {
/* Read end of file into the buffer */
const numberOfBytesRead = fs.readSync(fi, fileBuffer, 0, numberOfBytes, header.data.size + header.size);
if (numberOfBytesRead === numberOfBytes) {
/* Parse the GUANO header */
const guanoCheck = guanoHandler.readGuano(fileBuffer, numberOfBytes);
if (guanoCheck.success) {
guano = guanoCheck.guano;
contents = guano.contents;
}
}
} catch (e) {
guano = null;
contents = null;
}
}
/* Write the output files */
let progress = 0;
try {
if (outputFileList.length === 1 && outputFileList[0].offset === 0 && outputFileList[0].length === inputFileDataSize) {
const filename = (prefix === '' ? '' : prefix + '_') + existingPrefix + formatFilename(originalTimestamp, existingPostfix);
const outputCallback = function (value) {
const nextProgress = Math.round(100 * value);
if (nextProgress > progress) {
progress = nextProgress;
if (callback) callback(progress);
}
};
writeOutputFile(fi, path.join(outputPath, filename), header, guano, null, null, 0, inputFileDataSize, outputCallback);
} else {
for (let i = 0; i < outputFileList.length; i += 1) {
if (callback && i > 0) callback(Math.round(i / outputFileList.length * 100));
const comment = 'Split from ' + path.basename(inputPath) + ' as file ' + (i + 1) + ' of ' + outputFileList.length + '.';
const filename = (prefix === '' ? '' : prefix + '_') + existingPrefix + formatFilename(outputFileList[i].timestamp, existingPostfix);
const newContents = contents ? contents.replace(TIMESTAMP_REGEX, formatTimestamp(outputFileList[i].timestamp)) : null;
const outputCallback = function (value) {
const nextProgress = Math.round(100 * (i + value) / outputFileList.length);
if (nextProgress > progress) {
progress = nextProgress;
if (callback) callback(progress);
}
};
writeOutputFile(fi, path.join(outputPath, filename), header, guano, comment, newContents, outputFileList[i].offset, outputFileList[i].length, outputCallback);
}
}
} catch (e) {
return {
success: false,
error: 'An error occurred while splitting files. '
};
}
if (callback && progress < 100) callback(100);
/* Close the input file */
fs.closeSync(fi);
/* Return success */
return {
success: true,
error: null
};
}
/* Export split */
exports.split = split;