-
Notifications
You must be signed in to change notification settings - Fork 0
/
expander.js
839 lines (457 loc) · 20.5 KB
/
expander.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
/****************************************************************************
* expander.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;
/* Expansion constants */
const AUDIOMOTH_SEGMENT_SIZE = 32 * 1024;
const ENCODED_BLOCK_SIZE_IN_BYTES = 512;
const NUMBER_OF_BYTES_IN_SAMPLE = 2;
const FILE_BUFFER_SIZE = 32 * 1024;
const HEADER_BUFFER_SIZE = 32 * 1024;
const UINT32_SIZE_IN_BITS = 32;
/* 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 blankBuffer = Buffer.alloc(FILE_BUFFER_SIZE);
const headerBuffer = Buffer.alloc(HEADER_BUFFER_SIZE);
/* Check for silent buffer */
function isFullOfZeros (buffer, length) {
let i, value;
for (i = 0; i < length / NUMBER_OF_BYTES_IN_SAMPLE; i += 1) {
value = buffer.readInt16LE(NUMBER_OF_BYTES_IN_SAMPLE * i);
if (value !== 0) return false;
}
return true;
}
/* Decode the encoded block */
function readEncodedBlock (buffer) {
let i, value, numberOfBlocks;
numberOfBlocks = 0;
for (i = 0; i < UINT32_SIZE_IN_BITS; i += 1) {
value = buffer.readInt16LE(NUMBER_OF_BYTES_IN_SAMPLE * i);
if (value === 1) {
numberOfBlocks += (1 << i);
} else if (value !== -1) {
return 0;
}
}
for (i = UINT32_SIZE_IN_BITS; i < ENCODED_BLOCK_SIZE_IN_BYTES / NUMBER_OF_BYTES_IN_SAMPLE; i += 1) {
value = buffer.readInt16LE(NUMBER_OF_BYTES_IN_SAMPLE * i);
if (value !== 0) {
return 0;
}
}
return numberOfBlocks;
}
/* Date functions */
function digits (value, number) {
const string = '00000' + value;
return string.substr(string.length - number);
}
function formatFilename (timestamp, milliseconds) {
let filename;
const date = new Date(timestamp);
filename = date.getUTCFullYear() + digits(date.getUTCMonth() + 1, 2) + digits(date.getUTCDate(), 2) + '_' + digits(date.getUTCHours(), 2) + digits(date.getUTCMinutes(), 2) + digits(date.getUTCSeconds(), 2);
if (milliseconds) filename += '_' + digits(date.getUTCMilliseconds(), 3);
filename += '.WAV';
return filename;
}
function formatTimestamp (timestamp, milliseconds) {
const date = new Date(timestamp);
let 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);
if (milliseconds) string += '.' + digits(date.getUTCMilliseconds(), 3);
return string;
}
/* Write the output file */
function writeOutputFile (fi, fileSummary, 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 i = 0;
let index = offset;
while (i < fileSummary.length && index < offset + length) {
/* Skip forward through file summary components */
if (fileSummary[i].outputOffset + fileSummary[i].outputBytes - 1 < index) {
i += 1;
continue;
}
/* Determine the number of bytes to write */
let numberOfBytes = Math.min(FILE_BUFFER_SIZE, fileSummary[i].outputOffset + fileSummary[i].outputBytes - index);
numberOfBytes = Math.min(numberOfBytes, offset + length - index);
/* Read from input file, and then write file buffer or blank buffer */
if (fileSummary[i].type === 'AUDIO') {
fs.readSync(fi, fileBuffer, 0, numberOfBytes, header.size + index - fileSummary[i].outputOffset + fileSummary[i].inputOffset);
fs.writeSync(fo, fileBuffer, 0, numberOfBytes, null);
} else {
fs.writeSync(fo, blankBuffer, 0, numberOfBytes, null);
}
/* Increment bytes written and move to next file summary component if appropriate */
index += numberOfBytes;
if (index === fileSummary[i].outputOffset + fileSummary[i].outputBytes) i += 1;
/* 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);
}
/* Expand a T.WAV file */
function expand (inputPath, outputPath, prefix, expansionType, maximumFileDuration, generateSilentFiles, alignToSecondTransitions, callback) {
/* Check parameter */
prefix = prefix || '';
maximumFileDuration = maximumFileDuration || SECONDS_IN_DAY;
generateSilentFiles = generateSilentFiles || false;
alignToSecondTransitions = alignToSecondTransitions || false;
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 (expansionType !== 'DURATION' && expansionType !== 'EVENT') {
return {
success: false,
error: 'Expansion type must be DURATION or EVENT.'
};
}
if (typeof generateSilentFiles !== 'boolean') {
return {
success: false,
error: 'Generate silent files flag must be a boolean.'
};
}
if (typeof alignToSecondTransitions !== 'boolean') {
return {
success: false,
error: 'Align to second transitions flag must be a boolean.'
};
}
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 header */
const header = headerCheck.header;
/* Check the filename against header */
const inputFilename = path.parse(inputPath).base;
const filenameCheck = filenameHandler.checkFilenameAgainstHeader(filenameHandler.EXPAND, inputFilename, header.icmt.comment, header.iart.artist);
if (filenameCheck.success === false) return filenameCheck;
/* Extract original timestamp and existing prefix */
const existingPrefix = filenameCheck.existingPrefix;
const originalTimestamp = filenameCheck.originalTimestamp;
/* Determine settings from the input file */
const inputFileDataSize = header.data.size;
const inputFileHeaderSize = header.size;
/* Read the input file to generate summary data */
let progress = 0;
const fileSummary = [];
let inputFileBytesRead = 0;
try {
/* Read first bytes to ensure 512-byte alignment with start of encoded blocks */
if (header.size % ENCODED_BLOCK_SIZE_IN_BYTES !== 0) {
const numberOfBytes = Math.min(inputFileDataSize, ENCODED_BLOCK_SIZE_IN_BYTES - header.size % ENCODED_BLOCK_SIZE_IN_BYTES);
const numberOfBytesRead = fs.readSync(fi, fileBuffer, 0, numberOfBytes, header.size);
if (numberOfBytesRead !== numberOfBytes) throw new Error('Could not read expected number of bytes.');
inputFileBytesRead += numberOfBytes;
fileSummary.push({
type: isFullOfZeros(fileBuffer, numberOfBytes) ? 'SILENT' : 'AUDIO',
inputBytes: numberOfBytes,
outputBytes: numberOfBytes
});
}
/* Read each block or segment */
while (inputFileBytesRead < inputFileDataSize) {
/* Check if this is the first or last segment */
const firstSegment = inputFileBytesRead + header.size < AUDIOMOTH_SEGMENT_SIZE;
const lastSegment = inputFileDataSize - inputFileBytesRead < AUDIOMOTH_SEGMENT_SIZE;
/* Read in at least the encoded block size */
const numberOfBytes = Math.min(inputFileDataSize - inputFileBytesRead, ENCODED_BLOCK_SIZE_IN_BYTES);
const numberOfBytesRead = fs.readSync(fi, fileBuffer, 0, numberOfBytes, inputFileBytesRead + header.size);
if (numberOfBytesRead !== numberOfBytes) throw new Error('Could not read expected number of bytes.');
inputFileBytesRead += numberOfBytes;
/* Update the details of the next file summary element */
let type, inputBytes, outputBytes;
if (numberOfBytes < ENCODED_BLOCK_SIZE_IN_BYTES) {
/* If bytes read is less than encode block size it may be silent or audio data */
type = (firstSegment || lastSegment) && isFullOfZeros(fileBuffer, numberOfBytes) ? 'SILENT' : 'AUDIO';
inputBytes = numberOfBytes;
outputBytes = numberOfBytes;
} else {
/* Check if the encoded block encodes a silent period */
const numberOfBlocks = readEncodedBlock(fileBuffer);
if (numberOfBlocks > 0) {
/* Add the silent period */
type = 'SILENT';
inputBytes = ENCODED_BLOCK_SIZE_IN_BYTES;
outputBytes = numberOfBlocks * ENCODED_BLOCK_SIZE_IN_BYTES;
} else {
/* Add audio block */
type = (firstSegment || lastSegment) && isFullOfZeros(fileBuffer, ENCODED_BLOCK_SIZE_IN_BYTES) ? 'SILENT' : 'AUDIO';
inputBytes = ENCODED_BLOCK_SIZE_IN_BYTES;
outputBytes = ENCODED_BLOCK_SIZE_IN_BYTES;
}
}
if (fileSummary.length === 0 || type !== fileSummary[fileSummary.length - 1].type) {
/* Add new block */
fileSummary.push({
type: type,
inputBytes: inputBytes,
outputBytes: outputBytes
});
} else {
/* Append to existing block */
fileSummary[fileSummary.length - 1].inputBytes += inputBytes;
fileSummary[fileSummary.length - 1].outputBytes += outputBytes;
}
/* Update the progress callback */
const nextProgress = Math.round(50 * inputFileBytesRead / inputFileDataSize);
if (nextProgress !== progress) {
progress = nextProgress;
if (callback) callback(progress);
}
}
} catch (e) {
return {
success: false,
error: 'An error occurred while processing the input file. '
};
}
/* Count the total output bytes */
let totalInputBytes = 0;
let totalOutputBytes = 0;
for (let i = 0; i < fileSummary.length; i += 1) {
fileSummary[i].inputOffset = totalInputBytes;
fileSummary[i].outputOffset = totalOutputBytes;
totalInputBytes += fileSummary[i].inputBytes;
totalOutputBytes += fileSummary[i].outputBytes;
}
/* Show the pruned output */
for (let i = 0; i < fileSummary.length; i += 1) {
if (DEBUG) console.log(fileSummary[i]);
}
/* Make the initial empty output file list */
const outputFileList = [];
/* Generate the output files */
if (expansionType === 'DURATION') {
/* Main loop generating files */
let numberOfBytesProcessed = 0;
let timestamp = originalTimestamp;
while (numberOfBytesProcessed < totalOutputBytes) {
/* Determine the number of bytes to write */
const numberOfBytes = Math.min(maximumFileDuration * header.wavFormat.samplesPerSecond * NUMBER_OF_BYTES_IN_SAMPLE, totalOutputBytes - numberOfBytesProcessed);
/* Check if the file has audio content */
let i = 0;
let hasAudio = false;
while (i < fileSummary.length) {
if (fileSummary[i].type === 'AUDIO' && numberOfBytesProcessed <= fileSummary[i].outputOffset + fileSummary[i].outputBytes - 1 && numberOfBytesProcessed + numberOfBytes - 1 >= fileSummary[i].outputOffset) hasAudio = true;
i += 1;
}
/* Add the output file if appropriate */
if (hasAudio || generateSilentFiles || maximumFileDuration === SECONDS_IN_DAY) {
outputFileList.push({
timestamp: timestamp,
milliseconds: false,
offset: numberOfBytesProcessed,
length: numberOfBytes
});
}
timestamp += maximumFileDuration * MILLISECONDS_IN_SECOND;
numberOfBytesProcessed += numberOfBytes;
}
}
if (expansionType === 'EVENT') {
/* Main loop generating files */
let i = 0;
let numberOfBytesProcessed = 0;
while (i < fileSummary.length && numberOfBytesProcessed < totalOutputBytes) {
/* Skip if segment is silent */
if (fileSummary[i].type === 'SILENT') {
numberOfBytesProcessed = fileSummary[i].outputOffset + fileSummary[i].outputBytes;
i += 1;
continue;
}
/* Determine which file to write next */
if (alignToSecondTransitions) {
/* Roll back the start time to the second transition */
numberOfBytesProcessed -= numberOfBytesProcessed % (header.wavFormat.samplesPerSecond * NUMBER_OF_BYTES_IN_SAMPLE);
/* Roll forward to the appropriate segment */
let j = i;
while (j < fileSummary.length - 1) {
if (fileSummary[j + 1].type === 'AUDIO') {
if (fileSummary[j + 1].outputOffset < numberOfBytesProcessed + header.wavFormat.samplesPerSecond * NUMBER_OF_BYTES_IN_SAMPLE) {
i = j + 1;
} else {
break;
}
}
j += 1;
}
}
/* Calculate the number of bytes to write */
const numberOfBytes = Math.min(maximumFileDuration * header.wavFormat.samplesPerSecond * NUMBER_OF_BYTES_IN_SAMPLE, fileSummary[i].outputOffset + fileSummary[i].outputBytes - numberOfBytesProcessed);
/* Determine time offset */
const timeOffset = Math.round(numberOfBytesProcessed / header.wavFormat.samplesPerSecond / NUMBER_OF_BYTES_IN_SAMPLE * MILLISECONDS_IN_SECOND);
/* Add the output file */
outputFileList.push({
timestamp: originalTimestamp + timeOffset,
milliseconds: alignToSecondTransitions === false,
offset: numberOfBytesProcessed,
length: numberOfBytes
});
/* Update the bytes processed and file summary counters */
numberOfBytesProcessed += numberOfBytes;
if (numberOfBytesProcessed === fileSummary[i].outputOffset + fileSummary[i].outputBytes) i += 1;
}
}
/* 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 (inputFileDataSize + inputFileHeaderSize < fileSize) {
const numberOfBytes = Math.min(fileSize - inputFileHeaderSize - inputFileDataSize, HEADER_BUFFER_SIZE);
try {
/* Read end of file into the buffer */
const numberOfBytesRead = fs.readSync(fi, fileBuffer, 0, numberOfBytes, inputFileDataSize + inputFileHeaderSize);
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 */
try {
if (outputFileList.length === 1 && outputFileList[0].offset === 0 && outputFileList[0].length === totalOutputBytes) {
const filename = (prefix === '' ? '' : prefix + '_') + existingPrefix + formatFilename(originalTimestamp, false);
const outputCallback = function (value) {
const nextProgress = 50 + Math.round(50 * value);
if (nextProgress > progress) {
progress = nextProgress;
if (callback) callback(progress);
}
};
writeOutputFile(fi, fileSummary, path.join(outputPath, filename), header, guano, null, null, 0, totalOutputBytes, outputCallback);
} else {
for (let i = 0; i < outputFileList.length; i += 1) {
const comment = 'Expanded from ' + path.basename(inputPath) + ' as file ' + (i + 1) + ' of ' + outputFileList.length + '.';
const filename = (prefix === '' ? '' : prefix + '_') + existingPrefix + formatFilename(outputFileList[i].timestamp, outputFileList[i].milliseconds);
const newContents = contents ? contents.replace(TIMESTAMP_REGEX, formatTimestamp(outputFileList[i].timestamp, outputFileList[i].milliseconds)) : null;
const outputCallback = function (value) {
const nextProgress = 50 + Math.round(50 * (i + value) / outputFileList.length);
if (nextProgress > progress) {
progress = nextProgress;
if (callback) callback(progress);
}
};
writeOutputFile(fi, fileSummary, 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 processing the duration-based output files. '
};
}
if (callback && progress < 100) callback(100);
/* Close the input file */
fs.closeSync(fi);
/* Return success */
return {
success: true,
error: null
};
}
/* Exports */
exports.expand = expand;