forked from xdf-modules/libxdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xdf.cpp
1095 lines (914 loc) · 37.5 KB
/
xdf.cpp
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
//libxdf is a static C++ library to load XDF files
//Copyright (C) 2017 Yida Lin
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
//If you have questions, contact author at [email protected]
#include "xdf.h"
#include <iostream>
#include <fstream>
#include <pugixml.hpp> //pugi XML parser
#include <sstream>
#include <algorithm>
#include "smarc/smarc.h" //resampling library
#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
#include <numeric> //std::accumulate
#include <functional> // bind2nd
#include <cmath>
Xdf::Xdf()
{
}
int Xdf::load_xdf(std::string filename)
{
clock_t time;
time = clock();
/* //uncompress if necessary
char ext[_MAX_EXT]; //for file extension
_splitpath_s ( argv[1], NULL, NULL, NULL, NULL, NULL, NULL, ext, NULL );
if (strcmp(ext, ".xdfz") == 0)
{
//uncompress
}
*/
std::vector<int> idmap; //remaps stream id's onto indices in streams
//===================================================================
//========================= parse the file ==========================
//===================================================================
std::ifstream file(filename, std::ios::in | std::ios::binary);
if (file.is_open())
{
//read [MagicCode]
std::string magicNumber;
for (char c; file >> c;)
{
magicNumber.push_back(c);
if (magicNumber.size() == 4)
break;
}
if (magicNumber.compare("XDF:"))
{
std::cout << "This is not a valid XDF file.('" << filename << "')\n";
return -1;
}
//for each chunk
while (1)
{
uint64_t ChLen = readLength(file);//chunk length
if (ChLen == 0)
break;
uint16_t tag; //read tag of the chunk, 6 possibilities
readBin(file, &tag);
switch (tag)
{
case 1: //[FileHeader]
{
char* buffer = new char[ChLen - 2];
file.read(buffer, ChLen - 2);
fileHeader = buffer;
pugi::xml_document doc;
doc.load_buffer_inplace(buffer, ChLen - 2);
pugi::xml_node info = doc.child("info");
version = info.child("version").text().as_float();
delete[] buffer;
}
break;
case 2: //read [StreamHeader] chunk
{
//read [StreamID]
uint32_t streamID;
int index;
Xdf::readBin(file, &streamID);
std::vector<int>::iterator it {std::find(idmap.begin(),idmap.end(),streamID)};
if (it == idmap.end())
{
index = idmap.size();
idmap.emplace_back(streamID);
streams.emplace_back();
}
else
index = std::distance(idmap.begin(), it);
pugi::xml_document doc;
//read [Content]
char* buffer = new char[ChLen - 6];
file.read(buffer, ChLen - 6);
streams[index].streamHeader = buffer;
doc.load_buffer_inplace(buffer, ChLen - 6);
pugi::xml_node info = doc.child("info");
pugi::xml_node desc = info.child("desc");
streams[index].info.channel_count = info.child("channel_count").text().as_int();
streams[index].info.nominal_srate = info.child("nominal_srate").text().as_double();
streams[index].info.name = info.child("name").text().get();
streams[index].info.type = info.child("type").text().get();
streams[index].info.channel_format = info.child("channel_format").text().get();
for (auto channel = desc.child("channels").child("channel"); channel; channel = channel.next_sibling("channel"))
{
streams[index].info.channels.emplace_back();
for (auto const &entry : channel.children())
streams[index].info.channels.back().emplace(entry.name(), entry.child_value());
}
if (streams[index].info.nominal_srate > 0)
streams[index].sampling_interval = 1 / streams[index].info.nominal_srate;
else
streams[index].sampling_interval = 0;
delete[] buffer;
}
break;
case 3: //read [Samples] chunk
{
//read [StreamID]
uint32_t streamID;
int index;
Xdf::readBin(file, &streamID);
std::vector<int>::iterator it {std::find(idmap.begin(),idmap.end(),streamID)};
if (it == idmap.end())
{
index = idmap.size();
idmap.emplace_back(streamID);
streams.emplace_back();
}
else
index = std::distance(idmap.begin(), it);
//read [NumSampleBytes], [NumSamples]
uint64_t numSamp = readLength(file);
//check the data type
if (streams[index].info.channel_format.compare("float32") == 0)
{
//if the time series is empty
if (streams[index].time_series.empty())
streams[index].time_series.resize(streams[index].info.channel_count);
//for each sample
for (size_t i = 0; i < numSamp; i++)
{
//read or deduce time stamp
auto tsBytes = readBin<uint8_t>(file);
double ts; //temporary time stamp
if (tsBytes == 8)
{
Xdf::readBin(file, &ts);
streams[index].time_stamps.emplace_back(ts);
}
else
{
ts = streams[index].last_timestamp + streams[index].sampling_interval;
streams[index].time_stamps.emplace_back(ts);
}
streams[index].last_timestamp = ts;
//read the data
for (int v = 0; v < streams[index].info.channel_count; ++v)
{
float data;
Xdf::readBin(file, &data);
streams[index].time_series[v].emplace_back(data);
}
}
}
else if (streams[index].info.channel_format.compare("double64") == 0)
{
//if the time series is empty
if (streams[index].time_series.empty())
streams[index].time_series.resize(streams[index].info.channel_count);
//for each sample
for (size_t i = 0; i < numSamp; i++)
{
//read or deduce time stamp
auto tsBytes = readBin<uint8_t>(file);
double ts; //temporary time stamp
if (tsBytes == 8)
{
Xdf::readBin(file, &ts);
streams[index].time_stamps.emplace_back(ts);
}
else
{
ts = streams[index].last_timestamp + streams[index].sampling_interval;
streams[index].time_stamps.emplace_back(ts);
}
streams[index].last_timestamp = ts;
//read the data
for (int v = 0; v < streams[index].info.channel_count; ++v)
{
double data;
Xdf::readBin(file, &data);
streams[index].time_series[v].emplace_back(data);
}
}
}
else if (streams[index].info.channel_format.compare("int8") == 0)
{
//if the time series is empty
if (streams[index].time_series.empty())
streams[index].time_series.resize(streams[index].info.channel_count);
//for each sample
for (size_t i = 0; i < numSamp; i++)
{
//read or deduce time stamp
auto tsBytes = readBin<uint8_t>(file);
double ts; //temporary time stamp
if (tsBytes == 8)
{
Xdf::readBin(file, &ts);
streams[index].time_stamps.emplace_back(ts);
}
else
{
ts = streams[index].last_timestamp + streams[index].sampling_interval;
streams[index].time_stamps.emplace_back(ts);
}
streams[index].last_timestamp = ts;
//read the data
for (int v = 0; v < streams[index].info.channel_count; ++v)
{
int8_t data;
Xdf::readBin(file, &data);
streams[index].time_series[v].emplace_back(data);
}
}
}
else if (streams[index].info.channel_format.compare("int16") == 0)
{
//if the time series is empty
if (streams[index].time_series.empty())
streams[index].time_series.resize(streams[index].info.channel_count);
//for each sample
for (size_t i = 0; i < numSamp; i++)
{
//read or deduce time stamp
auto tsBytes = readBin<uint8_t>(file);
double ts; //temporary time stamp
if (tsBytes == 8)
{
Xdf::readBin(file, &ts);
streams[index].time_stamps.emplace_back(ts);
}
else
{
ts = streams[index].last_timestamp + streams[index].sampling_interval;
streams[index].time_stamps.emplace_back(ts);
}
streams[index].last_timestamp = ts;
//read the data
for (int v = 0; v < streams[index].info.channel_count; ++v)
{
int16_t data;
Xdf::readBin(file, &data);
streams[index].time_series[v].emplace_back(data);
}
}
}
else if (streams[index].info.channel_format.compare("int32") == 0)
{
//if the time series is empty
if (streams[index].time_series.empty())
streams[index].time_series.resize(streams[index].info.channel_count);
//for each sample
for (size_t i = 0; i < numSamp; i++)
{
//read or deduce time stamp
auto tsBytes = readBin<uint8_t>(file);
double ts; //temporary time stamp
if (tsBytes == 8)
{
Xdf::readBin(file, &ts);
streams[index].time_stamps.emplace_back(ts);
}
else
{
ts = streams[index].last_timestamp + streams[index].sampling_interval;
streams[index].time_stamps.emplace_back(ts);
}
streams[index].last_timestamp = ts;
//read the data
for (int v = 0; v < streams[index].info.channel_count; ++v)
{
int32_t data;
Xdf::readBin(file, &data);
streams[index].time_series[v].emplace_back(data);
}
}
}
else if (streams[index].info.channel_format.compare("int64") == 0)
{
//if the time series is empty
if (streams[index].time_series.empty())
streams[index].time_series.resize(streams[index].info.channel_count);
//for each sample
for (size_t i = 0; i < numSamp; i++)
{
//read or deduce time stamp
auto tsBytes = readBin<uint8_t>(file);
double ts; //temporary time stamp
if (tsBytes == 8)
{
Xdf::readBin(file, &ts);
streams[index].time_stamps.emplace_back(ts);
}
else
{
ts = streams[index].last_timestamp + streams[index].sampling_interval;
streams[index].time_stamps.emplace_back(ts);
}
streams[index].last_timestamp = ts;
//read the data
for (int v = 0; v < streams[index].info.channel_count; ++v)
{
int64_t data;
Xdf::readBin(file, &data);
streams[index].time_series[v].emplace_back(data);
}
}
}
else if (streams[index].info.channel_format.compare("string") == 0)
{
//for each event
for (size_t i = 0; i < numSamp; i++)
{
//read or deduce time stamp
auto tsBytes = readBin<uint8_t>(file);
double ts; //temporary time stamp
if (tsBytes == 8)
Xdf::readBin(file, &ts);
else
ts = streams[index].last_timestamp + streams[index].sampling_interval;
//read the event
auto length = Xdf::readLength(file);
char* buffer = new char[length + 1];
file.read(buffer, length);
buffer[length] = '\0';
eventMap.emplace_back(std::make_pair(buffer, ts), index);
delete[] buffer;
streams[index].last_timestamp = ts;
}
}
}
break;
case 4: //read [ClockOffset] chunk
{
uint32_t streamID;
int index;
Xdf::readBin(file, &streamID);
std::vector<int>::iterator it {std::find(idmap.begin(),idmap.end(),streamID)};
if (it == idmap.end())
{
index = idmap.size();
idmap.emplace_back(streamID);
streams.emplace_back();
}
else
index = std::distance(idmap.begin(), it);
double collectionTime;
double offsetValue;
Xdf::readBin(file, &collectionTime);
Xdf::readBin(file, &offsetValue);
streams[index].clock_times.emplace_back(collectionTime);
streams[index].clock_values.emplace_back(offsetValue);
}
break;
case 6: //read [StreamFooter] chunk
{
pugi::xml_document doc;
//read [StreamID]
uint32_t streamID;
int index;
Xdf::readBin(file, &streamID);
std::vector<int>::iterator it {std::find(idmap.begin(),idmap.end(),streamID)};
if (it == idmap.end())
{
index = idmap.size();
idmap.emplace_back(streamID);
streams.emplace_back();
}
else
index = std::distance(idmap.begin(), it);
char* buffer = new char[ChLen - 6];
file.read(buffer, ChLen - 6);
streams[index].streamFooter = buffer;
doc.load_buffer_inplace(buffer, ChLen - 6);
pugi::xml_node info = doc.child("info");
streams[index].info.first_timestamp = info.child("first_timestamp").text().as_double();
streams[index].info.last_timestamp = info.child("last_timestamp").text().as_double();
streams[index].info.measured_srate = info.child("measured_srate").text().as_double();
streams[index].info.sample_count = info.child("sample_count").text().as_int();
delete[] buffer;
}
break;
case 5: //skip other chunk types (Boundary, ...)
file.seekg(ChLen - 2, file.cur);
break;
default:
std::cout << "Unknown chunk encountered.\n";
break;
}
}
//calculate how much time it takes to read the data
clock_t halfWay = clock() - time;
std::cout << "it took " << halfWay << " clicks (" << ((float)halfWay) / CLOCKS_PER_SEC << " seconds)"
<< " reading XDF data" << std::endl;
//==========================================================
//=============find the min and max time stamps=============
//==========================================================
syncTimeStamps();
findMinMax();
findMajSR();
getHighestSampleRate();
loadSampleRateMap();
calcTotalChannel();
loadDictionary();
calcEffectiveSrate();
//loading finishes, close file
file.close();
}
else
{
std::cout << "Unable to open file" << std::endl;
return 1;
}
return 0;
}
void Xdf::syncTimeStamps()
{
// Sync time stamps
for (auto &stream : this->streams)
{
if (!stream.clock_times.empty())
{
size_t m = 0; // index iterating through stream.time_stamps
size_t n = 0; // index iterating through stream.clock_times
while (m < stream.time_stamps.size())
{
if (stream.clock_times[n] < stream.time_stamps[m])
{
while (n < stream.clock_times.size() - 1 && stream.clock_times[n+1] < stream.time_stamps[m])
{
n++;
}
stream.time_stamps[m] += stream.clock_values[n];
}
else if (n == 0)
{
stream.time_stamps[m] += stream.clock_values[n];
}
m++;
}
}
}
// Sync event time stamps
for (auto &elem : this->eventMap)
{
if (!this->streams[elem.second].clock_times.empty())
{
size_t k = 0; // index iterating through streams[elem.second].clock_times
while (k < this->streams[elem.second].clock_times.size() - 1)
{
if (this->streams[elem.second].clock_times[k+1] < elem.first.second)
{
k++;
}
else
{
break;
}
}
elem.first.second += this->streams[elem.second].clock_values[k]; // apply the last offset value to the timestamp; if there hasn't yet been an offset value take the first recorded one
}
}
// Update first and last time stamps in stream footer
for (size_t k = 0; k < this->streams.size(); k++)
{
if (streams[k].info.channel_format.compare("string") == 0)
{
double min = NAN;
double max = NAN;
for (auto const &elem : this->eventMap)
{
if (elem.second == (int)k)
{
if (std::isnan(min) || elem.first.second < min)
{
min = elem.first.second;
}
if (std::isnan(max) || elem.first.second > max)
{
max = elem.first.second;
}
}
}
streams[k].info.first_timestamp = min;
streams[k].info.last_timestamp = max;
}
else
{
streams[k].info.first_timestamp = streams[k].time_stamps.front();
streams[k].info.last_timestamp = streams[k].time_stamps.back();
}
}
}
void Xdf::resample(int userSrate)
{
//if user entered a preferred sample rate, we resample all the channels to that sample rate
//Otherwise, we resample all channels to the sample rate that has the most channels
clock_t time = clock();
#define BUF_SIZE 8192
for (auto &stream : streams)
{
if (!stream.time_series.empty() &&
stream.info.nominal_srate != userSrate &&
stream.info.nominal_srate != 0)
{
int fsin = stream.info.nominal_srate; // input samplerate
int fsout = userSrate; // output samplerate
double bandwidth = 0.95; // bandwidth
double rp = 0.1; // passband ripple factor
double rs = 140; // stopband attenuation
double tol = 0.000001; // tolerance
// initialize smarc filter
struct PFilter* pfilt = smarc_init_pfilter(fsin, fsout, bandwidth, rp,
rs, tol, NULL, 0);
if (pfilt == NULL)
continue;
// initialize smarc filter state
struct PState* pstate = smarc_init_pstate(pfilt);
for (auto &row : stream.time_series)
{
// initialize buffers
int read = 0;
int written = 0;
const int OUT_BUF_SIZE = (int) smarc_get_output_buffer_size(pfilt, row.size());
double* inbuf = new double[row.size()];
double* outbuf = new double[OUT_BUF_SIZE];
std::copy(row.begin(), row.end(), inbuf);
read = row.size();
// resample signal block
written = smarc_resample(pfilt, pstate, inbuf, read, outbuf, OUT_BUF_SIZE);
// do what you want with your output
row.resize(written);
std::copy ( outbuf, outbuf+written, row.begin() );
// flushing last values
written = smarc_resample_flush(pfilt, pstate, outbuf, OUT_BUF_SIZE);
// do what you want with your output
row.resize(row.size() + written);
std::copy ( outbuf, outbuf+written, row.begin() + row.size() - written );
// you are done with converting your signal.
// If you want to reuse the same converter to process another signal
// just reset the state:
smarc_reset_pstate(pstate,pfilt);
delete[] inbuf;
delete[] outbuf;
}
// release smarc filter state
smarc_destroy_pstate(pstate);
// release smarc filter
smarc_destroy_pfilter(pfilt);
}
}
//resampling finishes here
//======================================================================
//===========Calculating total length & total channel count=============
//======================================================================
calcTotalLength(userSrate);
adjustTotalLength();
time = clock() - time;
std::cout << "it took " << time << " clicks (" << ((float)time) / CLOCKS_PER_SEC << " seconds)"
<< " resampling" << std::endl;
}
//function of reading the length of each chunk
uint64_t Xdf::readLength(std::ifstream &file)
{
uint8_t bytes;
Xdf::readBin(file, &bytes);
uint64_t length = 0;
switch (bytes)
{
case 1:
length = readBin<uint8_t>(file);
break;
case 4:
length = readBin<uint32_t>(file);
break;
case 8:
length = readBin<uint64_t>(file);
break;
default:
std::cout << "Invalid variable-length integer length ("
<< static_cast<int>(bytes) << ") encountered.\n";
return 0;
}
return length;
}
void Xdf::findMinMax()
{
//find the smallest timestamp of all streams
for (auto const &stream : streams)
{
if (!std::isnan(stream.info.first_timestamp))
{
minTS = stream.info.first_timestamp;
break;
}
}
for (auto const &stream : streams)
{
if (!std::isnan(stream.info.first_timestamp) && stream.info.first_timestamp < minTS)
minTS = stream.info.first_timestamp;
}
//find the max timestamp of all streams
for (auto const &stream : streams)
{
if (!std::isnan(stream.info.last_timestamp) && stream.info.last_timestamp > maxTS)
maxTS = stream.info.last_timestamp;
}
}
void Xdf::findMajSR()
{
// find out which sample rate has the most channels
typedef int sampRate;
typedef int numChannel;
std::vector<std::pair<sampRate, numChannel> > srateMap; //<srate, numChannels> pairs of all the streams
//find out whether a sample rate already exists in srateMap
for (auto const &stream : streams)
{
if (stream.info.nominal_srate != 0)
{
std::vector<std::pair<sampRate, numChannel> >::iterator it {std::find_if(srateMap.begin(), srateMap.end(),
[&](const std::pair<sampRate, numChannel> &element)
{return element.first == stream.info.nominal_srate; })} ;
//if it doesn't, add it here
if (it == srateMap.end())
srateMap.emplace_back(stream.info.nominal_srate, stream.info.channel_count);
//if it already exists, add additional channel numbers to that sample rate
else
{
int index (std::distance(srateMap.begin(),it)) ;
srateMap[index].second += stream.info.channel_count;
}
}
}
if(srateMap.size() > 0){
//search the srateMap to see which sample rate has the most channels
int index (std::distance(srateMap.begin(),
std::max_element(srateMap.begin(),srateMap.end(),
[] (const std::pair<sampRate, numChannel> &largest,
const std::pair<sampRate, numChannel> &first)
{ return largest.second < first.second; })));
majSR = srateMap[index].first; //the sample rate that has the most channels
} else {
majSR = 0; //if there are no streams with a fixed sample reate
}
}
void Xdf::calcTotalChannel()
{
//calculating total channel count, and indexing them onto streamMap
for (size_t c = 0; c < streams.size(); c++)
{
if(!streams[c].time_series.empty())
{
totalCh += streams[c].info.channel_count;
for (int i = 0; i < streams[c].info.channel_count; i++)
streamMap.emplace_back(c);
}
}
}
void Xdf::calcTotalLength(int sampleRate)
{
totalLen = (maxTS - minTS) * sampleRate;
}
void Xdf::freeUpTimeStamps()
{
//free up as much memory as possible
for (auto &stream : streams)
{
//we don't need to keep all the time stamps unless it's a stream with irregular samples
//filter irregular streams and string streams
if (stream.info.nominal_srate != 0 && !stream.time_stamps.empty() && stream.info.channel_format.compare("string"))
{
std::vector<double> nothing;
//however we still need to keep the first time stamp of each stream to decide at which position the signal should start
nothing.emplace_back(stream.time_stamps.front());
stream.time_stamps.swap(nothing);
}
}
}
void Xdf::adjustTotalLength()
{
for (auto const &stream : streams)
{
if(!stream.time_series.empty())
{
if (totalLen < stream.time_series.front().size())
totalLen = stream.time_series.front().size();
}
}
}
void Xdf::getHighestSampleRate()
{
for (auto const &stream : streams)
{
if (stream.info.nominal_srate > maxSR)
maxSR = stream.info.nominal_srate;
}
}
void Xdf::loadSampleRateMap()
{
for (auto const &stream : streams)
sampleRateMap.emplace(stream.info.nominal_srate);
}
void Xdf::detrend()
{
for (auto &stream : streams)
{
for (auto &row : stream.time_series)
{
long double init = 0.0;
long double mean = std::accumulate(row.begin(), row.end(), init) / row.size();
for(auto &val: row) val -= mean;
offsets.emplace_back(mean);
}
}
}
void Xdf::calcEffectiveSrate()
{
for (auto &stream : streams)
{
if (stream.info.nominal_srate)
{
try
{
stream.info.effective_sample_rate
= stream.info.sample_count /
(stream.info.last_timestamp - stream.info.first_timestamp);
if (stream.info.effective_sample_rate)
effectiveSampleRateVector.emplace_back(stream.info.effective_sample_rate);
pugi::xml_document doc;
doc.load_string(stream.streamFooter.c_str());
pugi::xml_node sampleCount = doc.child("info").child("sample_count");
pugi::xml_node effectiveSampleRate
= doc.child("info").insert_child_after("effective_sample_rate", sampleCount);
effectiveSampleRate.append_child(pugi::node_pcdata)
.set_value(std::to_string(stream.info.effective_sample_rate).c_str());
std::stringstream buffer;
doc.save(buffer);
stream.streamFooter = buffer.str();
}
catch (std::exception &e)
{
std::cerr << "Error calculating effective sample rate. "
<< e.what() << std::endl;
}
}
}
}
int Xdf::writeEventsToXDF(std::string file_path)
{
if (userAddedStream)
{
std::fstream file;
file.open(file_path, std::ios::app | std::ios::binary);
if (file.is_open())
{
//start to append to new XDF file
//first write a stream header chunk
//Num Length Bytes
file.put(4);
//length
int length = streams[userAddedStream].streamHeader.size() + 6; //+6 because of the length int itself and short int tag
file.write((char*)&length, 4);
//tag
short tag = 2;
file.write((char*)&tag, 2);
//streamNumber
int streamNumber = userAddedStream + 1; //+1 because the stream IDs in XDF are 1 based instead of 0 based
file.write((char*)&streamNumber, 4);
//content
file.write(streams[userAddedStream].streamHeader.c_str(), length - 6);//length - 6 is the string length
//write samples chunk
//Num Length Bytes
file.put(8);
//length
//add the bytes of all following actions together
int64_t stringTotalLength = 0;
for (auto const &event : userCreatedEvents)
stringTotalLength += event.first.size();
int64_t sampleChunkLength = 2 + 4 + 1 + 4 +
userCreatedEvents.size() *
(1 + 8 + 1 + 4) + stringTotalLength;
file.write((char*)&sampleChunkLength, 8);
//tag
tag = 3;
file.write((char*)&tag, 2);
//streamNumber
file.write((char*)&streamNumber, 4);
//content
//NumSamplesBytes
file.put(4);
//Num Samples
int numSamples = userCreatedEvents.size();
file.write((char*)&numSamples, 4);
//samples
for (auto const &event : userCreatedEvents)
{
//TimeStampBytes
file.put(8);
//Optional Time Stamp
double timeStamp = event.second;
file.write((char*)&timeStamp, 8);
//Num Length Bytes
file.put(4);
//Length
int stringLength = event.first.length();
file.write((char*)&stringLength, 4);
//String Content
file.write(event.first.c_str(), stringLength);
}
file.close();
}
else
{
std::cerr << "Unable to open file." << std::endl;