-
Notifications
You must be signed in to change notification settings - Fork 0
/
aligner.js
1244 lines (669 loc) · 30.1 KB
/
aligner.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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
* aligner.js
* openacousticdevices.info
* October 2024
*****************************************************************************/
'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');
/* Results constants */
const FIX_IDENTIFIER = "FIX";
const RECORD_IDENTIFIER = "RECORDING";
const MEDIAN_SAMPLERATE_IDENTIFIER = "MEDIAN";
const INTERPOLATION_SAMPLERATE_IDENTIFIER = "INTERPOLATION";
/* File buffer constants */
const NUMBER_OF_BYTES_IN_SAMPLE = 2;
const GUANO_BUFFER_SIZE = 32 * 1024;
const HEADER_BUFFER_SIZE = 32 * 1024;
const FILE_BUFFER_SIZE = 1024 * 1024;
/* Unit constants */
const MILLIHERTZ_IN_HERTZ = 1000;
/* Time constants */
const MINUTES_IN_HOUR = 60;
const SECONDS_IN_MINUTE = 60;
const MILLISECONDS_IN_SECOND = 1000;
/* GPS.TXT regex constants */
const TIMESTAMP_REGEX = /(\d\d)\/(\d\d)\/(\d{4}) (\d\d):(\d\d):(\d\d)\.(\d{3})/;
const TIME_SET_REGEX = /(\d\d\/\d\d\/\d{4} \d\d:\d\d:\d\d\.\d{3}) UTC: Time was set from GPS\./;
const TIME_UPDATED_REGEX = /(\d\d\/\d\d\/\d{4} \d\d:\d\d:\d\d\.\d{3}) UTC: Time was updated\. The internal clock was (\d+)ms (fast|slow)\./;
const TIME_NOT_UPDATED_REGEX = /(\d\d\/\d\d\/\d{4} \d\d:\d\d:\d\d\.\d{3}) UTC: Time was not updated\. The internal clock was correct\./;
const SAMPLE_RATE_REGEX = /(\d\d\/\d\d\/\d{4} \d\d:\d\d:\d\d\.\d{3}) UTC: Actual sample rate will be (\d+)\.(\d{3}) Hz\./;
const GPS_FIX_REGEX = /\d\d\/\d\d\/\d{4} \d\d:\d\d:\d\d\.\d{3} UTC: Received GPS fix - (\d+\.\d{6})°(N|S) (\d+\.\d{6})°(W|E)(?: \(.+\))? at (\d\d\/\d\d\/\d{4} \d\d:\d\d:\d\d\.\d{3}) UTC\./;
/* GUNAO regex constants */
const GUANO_LOCATION_REGEX_2 = /Loc Position:(\-?\d{1,2}\.\d{2}) (\-?\d{1,3}\.\d{2})/;
const GUANO_LOCATION_REGEX_6 = /Loc Position:(\-?\d{1,2}\.\d{6}) (\-?\d{1,3}\.\d{6})/;
const GUANO_TEMPERATURE_REGEX = /Temperature Int:(\-?\d+\.\d)/;
const GUANO_VOLTAGE_REGEX = /OAD\|Battery Voltage:(\d\.\d)/;
/* Header regex constants */
const HEADER_TIMEZONE_REGEX = /\(UTC([-|+]\d+)?:?(\d\d)?\)/;
const BATTERY_GREATER_THAN_REGEX = /greater than 4.9V/;
const BATTERY_LESS_THAN_REGEX = /less than 2.5V/;
const BATTERY_REGEX = /(\d\.\d)V/;
const TEMPERATURE_REGEX = /(-?\d+\.\d)C/;
/* Alignment constants */
const TIME_OFFSET_MULTIPLIER = 10;
const SAMPLE_RATE_CORRECTION = 2 / 48000000;
const MAXIMUM_SAMPLE_RATE_ERROR_FROM_WAV_FILE = 100 * MILLIHERTZ_IN_HERTZ;
const MAXIMUM_SAMPLE_RATE_DIVERGENCE_RATIO_FROM_MEDIAN = 400 / 48000000;
/* Buffers for reading data */
const guanoBuffer = Buffer.alloc(GUANO_BUFFER_SIZE);
const headerBuffer = Buffer.alloc(HEADER_BUFFER_SIZE);
const fileBuffer = Buffer.alloc(FILE_BUFFER_SIZE);
/* Summary constants */
const HEADER = 'Timestamp,Event,Latitude,Longitude,Time Offset (ms),Start Sample Rate (Hz),End Sample Rate (Hz),Sample Rate Calculation,Filename,Samples,Duration (s),Temperature (C),Battery Voltage (V),Comment\r\n';
/* Global variables */
let fixes = [];
let recordings = [];
let currentFix = null;
let medianSampleRate = 0;
/* Little-endian sample read and write functions */
function readInt16 (buffer, index) {
let value = buffer[index] + (buffer[index + 1] << 8);
if (value > 0x7FFF) value -= 0x10000;
return value;
}
function writeInt16 (buffer, index, value) {
buffer[index] = value & 0xFF;
buffer[index + 1] = (value >> 8) & 0xFF;
}
/* Function to sort the results file */
function resultsSorter (a, b) {
return a.timestamp - b.timestamp;
}
/* Function to parse date string in file header */
function parseHeaderTimezone (comment) {
let offset = null;
const match = comment.match(HEADER_TIMEZONE_REGEX);
if (match) {
offset = 0;
if (match[1]) {
const negative = match[1].includes('-');
const hours = parseInt(match[1], 10);
offset = hours * MINUTES_IN_HOUR * SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND;
if (match[2]) {
let minutes = parseInt(match[2], 10);
if (negative) minutes *= -1;
offset += minutes * SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND;
}
}
}
return offset;
}
/* Functions to parse and format timestamps */
function parseTimestamp (dateString) {
const match = dateString.match(TIMESTAMP_REGEX);
const timestamp = Date.UTC(match[3], match[2] - 1, match[1], match[4], match[5], match[6], match[7]);
return timestamp;
}
function digits (value, number) {
const string = '00000' + value;
return string.substr(string.length - number);
}
function formatTimestamp(timestamp, offset) {
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 (offset == 0) {
string += 'Z';
} else {
string += offset < 0 ? '-' : '+';
offset = Math.abs(offset / SECONDS_IN_MINUTE / MILLISECONDS_IN_SECOND);
const hours = Math.floor(offset / MINUTES_IN_HOUR);
string += digits(hours, 2) + ':';
const minutes = offset % MINUTES_IN_HOUR;
string += digits(minutes , 2);
}
return string;
}
/* Process a line from the GPS.TXT file from the standard firmware */
function processLine(line) {
const gpsFixMatch = line.match(GPS_FIX_REGEX);
if (gpsFixMatch) {
const timestamp = parseTimestamp(gpsFixMatch[5]);
const longitude = (gpsFixMatch[4] === 'W' ? '-' : '') + gpsFixMatch[3];
const latitude = (gpsFixMatch[2] === 'S' ? '-' : '') + gpsFixMatch[1];
if (currentFix === null) {
currentFix = {
event: FIX_IDENTIFIER
};
}
currentFix.timestamp = timestamp;
currentFix.longitude = longitude;
currentFix.latitude = latitude;
currentFix.timeOffset = null;
return;
}
const timeSetMatch = line.match(TIME_SET_REGEX);
if (timeSetMatch) {
const timestamp = parseTimestamp(timeSetMatch[1]);
if (currentFix !== null && timestamp === currentFix.timestamp + MILLISECONDS_IN_SECOND) {
currentFix.timestamp += MILLISECONDS_IN_SECOND;
currentFix.timeOffset = 0;
}
return;
}
const timeNotUpdatedMatch = line.match(TIME_NOT_UPDATED_REGEX);
if (timeNotUpdatedMatch) {
const timestamp = parseTimestamp(timeNotUpdatedMatch[1]);
if (currentFix !== null && timestamp === currentFix.timestamp + MILLISECONDS_IN_SECOND) {
currentFix.timestamp += MILLISECONDS_IN_SECOND;
currentFix.timeOffset = 0;
}
return;
}
const timeUpdatedMatch = line.match(TIME_UPDATED_REGEX);
if (timeUpdatedMatch) {
const timestamp = parseTimestamp(timeUpdatedMatch[1]);
if (currentFix !== null && timestamp === currentFix.timestamp + MILLISECONDS_IN_SECOND) {
currentFix.timestamp += MILLISECONDS_IN_SECOND;
let timeOffset = TIME_OFFSET_MULTIPLIER * parseInt(timeUpdatedMatch[2], 10);
timeOffset *= timeUpdatedMatch[3] === 'fast' ? -1 : 1;
if (timeOffset > 0) timeOffset += TIME_OFFSET_MULTIPLIER / 2;
if (timeOffset < 0) timeOffset -= TIME_OFFSET_MULTIPLIER / 2;
currentFix.timeOffset = timeOffset;
}
return;
}
const sampleRateMatch = line.match(SAMPLE_RATE_REGEX);
if (sampleRateMatch) {
const timestamp = parseTimestamp(sampleRateMatch[1]);
if (currentFix !== null && currentFix.timeOffset !== null && timestamp === currentFix.timestamp) {
const sampleRate = MILLIHERTZ_IN_HERTZ * parseInt(sampleRateMatch[2], 10) + parseInt(sampleRateMatch[3], 10);
currentFix.sampleRate = sampleRate;
fixes.push(currentFix);
currentFix = null;
}
}
}
/* Initialise by parsing the GPS.TXT file from the standard firmware */
function initialise (inputPath) {
/* Open input GPS.TXT file */
let fi;
try {
fi = fs.openSync(inputPath, 'r');
} catch (e) {
return {
success: false,
error: 'Could not open the GPS.TXT file.'
};
}
let fileSize;
try {
fileSize = fs.statSync(inputPath).size;
} catch (e) {
return {
success: false,
error: 'Could not read the GPS.TXT file size.'
};
}
if (fileSize === 0) {
return {
success: false,
error: 'The GPS.TXT file has zero size.'
};
}
/* Initialise fixes and recordings list */
fixes = [];
recordings = [];
/* Read each line */
try {
let buffer = '';
let numberOfBytesRead = 0;
while (numberOfBytesRead < fileSize) {
const numberOfBytes = Math.min(FILE_BUFFER_SIZE, fileSize - numberOfBytesRead);
fs.readSync(fi, fileBuffer, 0, numberOfBytes, null);
const newLines = buffer.concat(fileBuffer.slice(0, numberOfBytes)).toString().split(/\r?\n/);
buffer = newLines.pop();
while (newLines.length > 0) {
const line = newLines.shift();
processLine(line);
}
numberOfBytesRead += numberOfBytes;
}
} catch (e) {
return {
success: false,
error: 'Something went wrong parsing the GPS.TXT file.'
};
}
/* Check sufficient fixes */
if (fixes.length < 2) {
return {
success: false,
error: 'Insufficient fixes within the GPS.TXT file to estimate clock drift.'
};
}
/* Sort the fixes */
fixes = fixes.sort(resultsSorter);
/* Find the median sample rate */
let sampleRates = [];
for (let i = 0; i < fixes.length; i += 1) {
sampleRates.push(fixes[i].sampleRate);
}
sampleRates = sampleRates.sort();
const midPoint = Math.floor(fixes.length / 2);
medianSampleRate = sampleRates[midPoint];
/* Return success */
return {
success: true,
error: null
};
}
/* Finalise by writing the GPS.CVS file */
function finalise (outputPath) {
/* Sort the recordings */
const sortedRecordings = recordings.sort(resultsSorter);
/* Write the output file */
try {
/* Check the output path */
if (fs.lstatSync(outputPath).isDirectory() === false) {
return {
success: false,
error: 'Destination path for GPS.CSV is not a directory.'
};
}
/* Write the output file */
const fo = fs.openSync(path.join(outputPath, 'GPS.CSV'), 'w');
fs.writeSync(fo, HEADER);
let fixIndex = 0;
let recordingIndex = 0;
while (fixIndex < fixes.length) {
const currrentFix = fixes[fixIndex];
/* Write fix */
let line = formatTimestamp(currrentFix.timestamp, 0) + ',';
line += currrentFix.event + ',' + currrentFix.latitude + ',' + currrentFix.longitude + ',';
line += currrentFix.timeOffset < 0 ? '-' : '';
line += Math.floor(Math.abs(currrentFix.timeOffset) / TIME_OFFSET_MULTIPLIER) + '.' + Math.abs(currrentFix.timeOffset) % TIME_OFFSET_MULTIPLIER + ',';
line += Math.floor(currrentFix.sampleRate / MILLIHERTZ_IN_HERTZ) + '.' + digits(currrentFix.sampleRate % MILLIHERTZ_IN_HERTZ, 3) + ',,,,,,,\r\n';
fs.writeSync(fo, line);
/* Check next recording */
while (recordingIndex < sortedRecordings.length) {
const currentRecording = sortedRecordings[recordingIndex];
if (fixIndex < fixes.length - 1) {
const nextFix = fixes[fixIndex + 1];
if (currentRecording.timestamp > nextFix.timestamp) break;
}
/* Write the recording */
let line = formatTimestamp(currentRecording.timestamp + currentRecording.timezoneOffset, currentRecording.timezoneOffset) + ',';
line += currentRecording.event + ',';
line += (currentRecording.latitude ? currentRecording.latitude : '') + ',';
line += (currentRecording.longitude ? currentRecording.longitude : '') + ',';
line += currentRecording.timeOffset < 0 ? '-' : '';
line += Math.floor(Math.abs(currentRecording.timeOffset) / TIME_OFFSET_MULTIPLIER) + '.' + Math.abs(currentRecording.timeOffset) % TIME_OFFSET_MULTIPLIER + ',';
line += Math.floor(currentRecording.sampleRateStart / MILLIHERTZ_IN_HERTZ) + '.' + digits(currentRecording.sampleRateStart % MILLIHERTZ_IN_HERTZ, 3) + ',';
line += Math.floor(currentRecording.sampleRateEnd / MILLIHERTZ_IN_HERTZ) + '.' + digits(currentRecording.sampleRateEnd % MILLIHERTZ_IN_HERTZ, 3) + ',';
line += currentRecording.sampleRateCalculation + ',';
line += currentRecording.filename + ',';
line += currentRecording.samples + ',' + currentRecording.duration + ',';
line += (currentRecording.temperature ? currentRecording.temperature : '') + ',';
line += (currentRecording.voltage ? currentRecording.voltage : '') + ',';
line += (currentRecording.comment ? currentRecording.comment : '') + '\r\n';
fs.writeSync(fo, line);
/* Increment counter */
recordingIndex += 1;
}
/* Increment counter */
fixIndex += 1;
}
fs.closeSync(fo);
} catch (e) {
return {
success: false,
error: 'An error occurred while writing the GPS.CSV file.'
};
}
/* Return success */
return {
success: true,
error: null
};
}
/* Align a WAV file from the standard firmware */
function align (inputPath, outputPath, prefix, onlyProcessFilesBetweenFixes, callback) {
/* Check prefix parameter */
prefix = prefix || '';
if (typeof prefix !== 'string') {
return {
success: false,
error: 'Filename prefix must be a string.'
};
}
/* Check processOutsideFiles parameter */
onlyProcessFilesBetweenFixes = typeof onlyProcessFilesBetweenFixes === 'boolean' ? onlyProcessFilesBetweenFixes : true;
/* Open input WAV file */
let fi;
try {
fi = fs.openSync(inputPath, 'r');
} catch (e) {
return {
success: false,
error: 'Could not open input WAV 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 WAV file size.'
};
}
if (fileSize === 0) {
return {
success: false,
error: 'Input WAV file has zero size.'
};
}
/* Read the WAV file header */
try {
fs.readSync(fi, headerBuffer, 0, HEADER_BUFFER_SIZE, 0);
} catch (e) {
return {
success: false,
error: 'Could not read the input WAV file header.'
};
}
/* Check the header */
const headerCheck = wavHandler.readHeader(headerBuffer, fileSize);
if (headerCheck.success === false) return headerCheck;
/* Extract the header */
const header = headerCheck.header;
const comment = header.icmt.comment;
/* Check the filename against header */
const inputFilename = path.parse(inputPath).base;
const filenameCheck = filenameHandler.checkFilenameAgainstHeader(filenameHandler.SYNC, inputFilename, header.icmt.comment, header.iart.artist);
if (filenameCheck.success === false) return filenameCheck;
/* Extract and correct timestamp */
const localTimestamp = filenameCheck.originalTimestamp;
const timezoneOffset = parseHeaderTimezone(comment);
if (timezoneOffset === null) {
return {
success: false,
error: 'Cannot find timezone in the input WAV file header.'
};
}
const timestamp = localTimestamp - timezoneOffset;
/* Calculate sample rate and duration */
const sampleRate = header.wavFormat.samplesPerSecond;
const samples = header.data.size / NUMBER_OF_BYTES_IN_SAMPLE;
const duration = Math.round(samples / sampleRate * MILLISECONDS_IN_SECOND) / MILLISECONDS_IN_SECOND;
/* Determine temperature */
let temperature = null;
if (TEMPERATURE_REGEX.test(comment)) {
temperature = comment.match(TEMPERATURE_REGEX) ? comment.match(TEMPERATURE_REGEX)[1] : null;
}
/* Determine battery voltage */
let voltage = null;
if (BATTERY_REGEX.test(comment)) {
voltage = comment.match(BATTERY_GREATER_THAN_REGEX) ? '5.0' : comment.match(BATTERY_LESS_THAN_REGEX) ? '2.4' : comment.match(BATTERY_REGEX) ? comment.match(BATTERY_REGEX)[1] : null;
}
/* Read the GUANO if present */
let guano;
let latitude = null;
let longitude = null;
if (header.data.size + header.size < fileSize) {
const numberOfBytes = Math.min(fileSize - header.size - header.data.size, GUANO_BUFFER_SIZE);
try {
/* Read end of file into the buffer */
const numberOfBytesRead = fs.readSync(fi, guanoBuffer, 0, numberOfBytes, header.data.size + header.size);
if (numberOfBytesRead === numberOfBytes) {
/* Parse the GUANO header */
const guanoCheck = guanoHandler.readGuano(guanoBuffer, numberOfBytes);
if (guanoCheck.success) {
guano = guanoCheck.guano;
/* Read latitude and longitude */
const contents = guano.contents;
let locationMatch = contents.match(GUANO_LOCATION_REGEX_2);
if (locationMatch) {
latitude = locationMatch[1];
longitude = locationMatch[2];
} else {
locationMatch = contents.match(GUANO_LOCATION_REGEX_6);
if (locationMatch) {
latitude = locationMatch[1];
longitude = locationMatch[2];
}
}
/* Read additional fields */
const temperatureMatch = contents.match(GUANO_TEMPERATURE_REGEX);
const guanoTemperature = temperatureMatch ? temperatureMatch[1] : null;
const voltageMatch = contents.match(GUANO_VOLTAGE_REGEX);
const guanoVoltage = voltageMatch ? voltageMatch[1] : null;
/* No exceptions so copy across GUANO data */
if (temperature === null) temperature = guanoTemperature;
if (voltage === null) voltage = guanoVoltage;
}
}
} catch (e) {
guano = null;
}
}
/* Check if recording is before or after fixes */
let timeOffset = 0;
let sampleRateError = 0;
let sampleRateStart = 0;
let sampleRateEnd = 0;
const firstFix = fixes[0];
const lastFix = fixes[fixes.length - 1];
let sampleRateCalculation = INTERPOLATION_SAMPLERATE_IDENTIFIER;
if (timestamp < firstFix.timestamp) {
return {
success: false,
error: 'Recording is before first GPS fix. No correction possible.'
};
} else if (timestamp > lastFix.timestamp) {
if (onlyProcessFilesBetweenFixes) {
return {
success: false,
error: 'Recording is after last GPS fix.'
};
}
/* Calculate time offset */
const clockDrift = lastFix.timeOffset / (lastFix.timestamp - fixes[fixes.length - 2].timestamp);
timeOffset = Math.round(clockDrift * (timestamp - lastFix.timestamp));
/* Calculate sample rate error from median */
sampleRateError = Math.abs(lastFix.sampleRate - medianSampleRate);
/* Check sample rate error */
if (sampleRateError > MAXIMUM_SAMPLE_RATE_DIVERGENCE_RATIO_FROM_MEDIAN * medianSampleRate) {
/* Calculate start and end sample rate */
sampleRateStart = medianSampleRate;
sampleRateEnd = medianSampleRate;
sampleRateCalculation = MEDIAN_SAMPLERATE_IDENTIFIER;
/* Calculate sample rate error from WAV file sample rate */
sampleRateError = Math.abs(medianSampleRate - sampleRate * MILLIHERTZ_IN_HERTZ);
} else {
/* Calculate start and end sample rate */
sampleRateStart = lastFix.sampleRate;
sampleRateEnd = lastFix.sampleRate;
/* Calculate sample rate error from WAV file sample rate */
sampleRateError = Math.abs(lastFix.sampleRate - sampleRate * MILLIHERTZ_IN_HERTZ);
}
} else {
/* Find fixes on either side of the recording */
let index = 0;
while (timestamp > fixes[index].timestamp) index += 1;
const fixAfter = fixes[index];
const fixBefore = fixes[index - 1];
/* Check that recording timestamp does equal fix timestamp */
if (timestamp === fixBefore.timestamp || timestamp === fixAfter.timestamp) {
return {
success: false,
error: 'Recording has the same time as a GPS fix.'
};
}
/* Calculate time offset */
const clockDrift = fixAfter.timeOffset / (fixAfter.timestamp - fixBefore.timestamp);
timeOffset = Math.round(clockDrift * (timestamp - fixBefore.timestamp));
/* Calculate sample rate error from median */
const sampleRateErrorBefore = Math.abs(fixBefore.sampleRate - medianSampleRate);
const sampleRateErrorAfter = Math.abs(fixAfter.sampleRate - medianSampleRate);
sampleRateError = Math.max(sampleRateErrorBefore, sampleRateErrorAfter);
/* Check sample rate error */
if (sampleRateError > MAXIMUM_SAMPLE_RATE_DIVERGENCE_RATIO_FROM_MEDIAN * medianSampleRate) {
/* Calculate start and end sample rate */
sampleRateStart = medianSampleRate;
sampleRateEnd = medianSampleRate;
sampleRateCalculation = MEDIAN_SAMPLERATE_IDENTIFIER;
/* Calculate sample rate error from WAV file sample rate */
sampleRateError = Math.abs(medianSampleRate - sampleRate * MILLIHERTZ_IN_HERTZ);
} else {
/* Calculate start and end sample rate */
const sampleRateDrift = (fixAfter.sampleRate - fixBefore.sampleRate) / (fixAfter.timestamp - fixBefore.timestamp);
sampleRateStart = Math.round(fixBefore.sampleRate + sampleRateDrift * (timestamp - fixBefore.timestamp));
sampleRateEnd = Math.round(fixBefore.sampleRate + sampleRateDrift * (timestamp + duration * MILLISECONDS_IN_SECOND - fixBefore.timestamp));
/* Calculate sample rate error from WAV file sample rate */
const sampleRateErrorStart = Math.abs(sampleRateStart - sampleRate * MILLIHERTZ_IN_HERTZ);
const sampleRateErrorEnd = Math.abs(sampleRateEnd - sampleRate * MILLIHERTZ_IN_HERTZ);
sampleRateError = Math.max(sampleRateErrorStart, sampleRateErrorEnd);
}
}
/* Check the sample rate against WAV file */
if (sampleRateError > MAXIMUM_SAMPLE_RATE_ERROR_FROM_WAV_FILE) {
return {
success: false,
error: 'Sample rate does not match expected sample rate.'