-
-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathFSEQFile.cpp
1926 lines (1741 loc) · 71.7 KB
/
FSEQFile.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
// This #define must be before any #include's
#define _FILE_OFFSET_BITS 64
#define __STDC_FORMAT_MACROS
#include <cstring>
#include <memory>
#include <vector>
#include <atomic>
#include <condition_variable>
#include <list>
#include <map>
#include <mutex>
#include <thread>
#include <chrono>
using namespace std::literals;
using namespace std::chrono_literals;
using namespace std::literals::chrono_literals;
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#ifdef _MSC_VER
#include <wx/wx.h>
int gettimeofday(struct timeval* tp, struct timezone* tzp) {
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
// This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
// until 00:00:00 January 1, 1970
static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t)file_time.dwLowDateTime);
time += ((uint64_t)file_time.dwHighDateTime) << 32;
tp->tv_sec = (long)((time - EPOCH) / 10000000L);
tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
return 0;
}
#define ftello _ftelli64
#define fseeko _fseeki64
#else
#include <sys/time.h>
#include <unistd.h>
#endif
#include "FSEQFile.h"
static void SetThreadName(const std::string& name) {
#ifdef PLATFORM_OSX
pthread_setname_np(name.c_str());
#else
pthread_setname_np(pthread_self(), name.c_str());
#endif
}
#if defined(PLATFORM_OSX)
#define PLATFORM_UNKNOWN
#endif
#if defined(PLATFORM_PI) || defined(PLATFORM_BBB) || defined(PLATFORM_BB64) || defined(PLATFORM_UNKNOWN) || defined(PLATFORM_DEBIAN) || defined(PLATFORM_FEDORA) || defined(PLATFORM_UBUNTU) || defined(PLATFORM_MINT)
// for FPP, use FPP logging
#include "Warnings.h"
#include "log.h"
inline void AddSlowStorageWarning() {
WarningHolder::AddWarningTimeout("FSEQ Data Block not available - Likely slow storage", 90);
}
#else
// compiling within xLights, use log4cpp
#define PLATFORM_UNKNOWN
#include <log4cpp/Category.hh>
template<typename... Args>
static void LogErr(int i, const char* fmt, Args... args) {
static log4cpp::Category& fseq_logger_base = log4cpp::Category::getInstance(std::string("log_base"));
char buf[256];
const char* nfmt = fmt;
if (fmt[strlen(fmt) - 1] == '\n') {
strcpy(buf, fmt);
buf[strlen(fmt) - 1] = 0;
nfmt = buf;
}
fseq_logger_base.error(nfmt, args...);
}
template<typename... Args>
static void LogInfo(int i, const char* fmt, Args... args) {
static log4cpp::Category& fseq_logger_base = log4cpp::Category::getInstance(std::string("log_base"));
char buf[256];
const char* nfmt = fmt;
if (fmt[strlen(fmt) - 1] == '\n') {
strcpy(buf, fmt);
buf[strlen(fmt) - 1] = 0;
nfmt = buf;
}
fseq_logger_base.info(nfmt, args...);
}
template<typename... Args>
static void LogDebug(int i, const char* fmt, Args... args) {
static log4cpp::Category& fseq_logger_base = log4cpp::Category::getInstance(std::string("log_base"));
char buf[256];
const char* nfmt = fmt;
if (fmt[strlen(fmt) - 1] == '\n') {
strcpy(buf, fmt);
buf[strlen(fmt) - 1] = 0;
nfmt = buf;
}
fseq_logger_base.debug(nfmt, args...);
}
inline void AddSlowStorageWarning() {
}
#define VB_SEQUENCE 1
#define VB_ALL 0
#endif
#ifndef NO_ZSTD
#include <zstd.h>
#endif
#ifndef NO_ZLIB
#include <zlib.h>
#endif
using FrameData = FSEQFile::FrameData;
inline void DumpHeader(const char* title, unsigned char data[], int len) {
int x = 0;
char tmpStr[128];
snprintf(tmpStr, 128, "%s: (%d bytes)\n", title, len);
LogInfo(VB_ALL, tmpStr);
for (int y = 0; y < len; y++) {
if (x == 0) {
snprintf(tmpStr, 128, "%06x: ", y);
}
snprintf(tmpStr + strlen(tmpStr), 128 - strlen(tmpStr), "%02x ", (int)(data[y] & 0xFF));
x++;
if (x == 16) {
x = 0;
snprintf(tmpStr + strlen(tmpStr), 128 - strlen(tmpStr), "\n");
LogInfo(VB_ALL, tmpStr);
}
}
if (x != 0) {
snprintf(tmpStr + strlen(tmpStr), 128 - strlen(tmpStr), "\n");
LogInfo(VB_ALL, tmpStr);
}
}
inline uint64_t GetTime(void) {
struct timeval now_tv;
gettimeofday(&now_tv, NULL);
return now_tv.tv_sec * 1000000LL + now_tv.tv_usec;
}
inline long roundTo4Internal(long i) {
long remainder = i % 4;
if (remainder == 0) {
return i;
}
return i + 4 - remainder;
}
inline uint32_t read4ByteUInt(const uint8_t* data) {
uint32_t r = (data[0]) + (data[1] << 8) + (data[2] << 16) + (data[3] << 24);
return r;
}
inline uint32_t read3ByteUInt(const uint8_t* data) {
uint32_t r = (data[0]) + (data[1] << 8) + (data[2] << 16);
return r;
}
inline uint32_t read2ByteUInt(const uint8_t* data) {
uint32_t r = (data[0]) + (data[1] << 8);
return r;
}
inline void write2ByteUInt(uint8_t* data, uint32_t v) {
data[0] = (uint8_t)(v & 0xFF);
data[1] = (uint8_t)((v >> 8) & 0xFF);
}
inline void write3ByteUInt(uint8_t* data, uint32_t v) {
data[0] = (uint8_t)(v & 0xFF);
data[1] = (uint8_t)((v >> 8) & 0xFF);
data[2] = (uint8_t)((v >> 16) & 0xFF);
}
inline void write4ByteUInt(uint8_t* data, uint32_t v) {
data[0] = (uint8_t)(v & 0xFF);
data[1] = (uint8_t)((v >> 8) & 0xFF);
data[2] = (uint8_t)((v >> 16) & 0xFF);
data[3] = (uint8_t)((v >> 24) & 0xFF);
}
static const int V1FSEQ_MINOR_VERSION = 0;
static const int V1FSEQ_MAJOR_VERSION = 1;
static const int V2FSEQ_MINOR_VERSION = 0;
static const int V2FSEQ_MAJOR_VERSION = 2;
static const int V1ESEQ_MINOR_VERSION = 0;
static const int V1ESEQ_MAJOR_VERSION = 2;
static const int V1ESEQ_HEADER_IDENTIFIER = 'E';
static const int V1ESEQ_CHANNEL_DATA_OFFSET = 20;
static const int V1ESEQ_STEP_TIME = 50;
FSEQFile* FSEQFile::openFSEQFile(const std::string& fn) {
FILE* seqFile = fopen((const char*)fn.c_str(), "rb");
if (seqFile == NULL) {
LogErr(VB_SEQUENCE, "Error pre-reading FSEQ file (%s), fopen returned NULL\n", fn.c_str());
return nullptr;
}
fseeko(seqFile, 0L, SEEK_SET);
// An initial read request of 8 bytes covers the file identifier, version fields and channel data offset
// This is the minimum needed to validate the file and prepare the proper sized buffer for a larger read
static const int initialReadLen = 8;
unsigned char headerPeek[initialReadLen];
int bytesRead = fread(headerPeek, 1, initialReadLen, seqFile);
#ifndef PLATFORM_UNKNOWN
posix_fadvise(fileno(seqFile), 0, 0, POSIX_FADV_SEQUENTIAL);
posix_fadvise(fileno(seqFile), 0, 1024 * 1024, POSIX_FADV_WILLNEED);
#endif
// Validate bytesRead covers at least the initial read length
if (bytesRead < initialReadLen) {
LogErr(VB_SEQUENCE, "Error pre-reading FSEQ file (%s) header, required %d bytes but read %d\n", fn.c_str(), initialReadLen, bytesRead);
DumpHeader("File hader peek:", headerPeek, bytesRead);
fclose(seqFile);
return nullptr;
}
// Validate the 4 byte file format identifier is supported
if ((headerPeek[0] != 'P' && headerPeek[0] != 'F' && headerPeek[0] != V1ESEQ_HEADER_IDENTIFIER) || headerPeek[1] != 'S' || headerPeek[2] != 'E' || headerPeek[3] != 'Q') {
LogErr(VB_SEQUENCE, "Error pre-reading FSEQ file (%s) header, invalid identifier\n", fn.c_str());
DumpHeader("File header peek:", headerPeek, bytesRead);
fclose(seqFile);
return nullptr;
}
uint64_t seqChanDataOffset = read2ByteUInt(&headerPeek[4]);
int seqVersionMinor = headerPeek[6];
int seqVersionMajor = headerPeek[7];
// Test for a ESEQ file (identifier[0] == 'E')
// ESEQ files are uncompressed V2 FSEQ files with a custom header
if (headerPeek[0] == V1ESEQ_HEADER_IDENTIFIER) {
seqChanDataOffset = V1ESEQ_CHANNEL_DATA_OFFSET;
seqVersionMajor = V1ESEQ_MAJOR_VERSION;
seqVersionMinor = V1ESEQ_MINOR_VERSION;
}
// Read the full header size (beginning at 0 and ending at seqChanDataOffset)
std::vector<uint8_t> header(seqChanDataOffset);
fseeko(seqFile, 0L, SEEK_SET);
bytesRead = fread(&header[0], 1, seqChanDataOffset, seqFile);
if (bytesRead != seqChanDataOffset) {
LogErr(VB_SEQUENCE, "Error reading FSEQ file (%s) header, length is %d bytes but read %d\n", fn.c_str(), seqChanDataOffset, bytesRead);
DumpHeader("File header:", &header[0], bytesRead);
fclose(seqFile);
return nullptr;
}
// Validate the major version is supported
// Return a file wrapper to handle version specific metadata
FSEQFile* file = nullptr;
if (seqVersionMajor == V1FSEQ_MAJOR_VERSION) {
file = new V1FSEQFile(fn, seqFile, header);
} else if (seqVersionMajor == V2FSEQ_MAJOR_VERSION) {
file = new V2FSEQFile(fn, seqFile, header);
} else {
LogErr(VB_SEQUENCE, "Error opening FSEQ file (%s), unknown version %d.%d\n", fn.c_str(), seqVersionMajor, seqVersionMinor);
DumpHeader("File header:", &header[0], bytesRead);
fclose(seqFile);
return nullptr;
}
file->dumpInfo();
return file;
}
FSEQFile* FSEQFile::createFSEQFile(const std::string& fn,
int version,
CompressionType ct,
int level) {
if (version == V1FSEQ_MAJOR_VERSION) {
V1FSEQFile* f = new V1FSEQFile(fn);
if (!f->m_seqFile) {
delete f;
f = nullptr;
}
return f;
} else if (version == V2FSEQ_MAJOR_VERSION) {
V2FSEQFile* f = new V2FSEQFile(fn, ct, level);
if (!f->m_seqFile) {
delete f;
f = nullptr;
}
return f;
}
LogErr(VB_SEQUENCE, "Error creating FSEQ file (%s), unknown version %d\n", fn.c_str(), version);
return nullptr;
}
std::string FSEQFile::getMediaFilename(const std::string& fn) {
std::unique_ptr<FSEQFile> file(FSEQFile::openFSEQFile(fn));
if (file) {
return file->getMediaFilename();
}
return "";
}
std::string FSEQFile::getMediaFilename() const {
for (auto& a : m_variableHeaders) {
if (a.code[0] == 'm' && a.code[1] == 'f') {
const char* d = (const char*)&a.data[0];
return d;
}
}
return "";
}
static const int FSEQ_DEFAULT_STEP_TIME = 50;
static const int FSEQ_VARIABLE_HEADER_SIZE = 4;
FSEQFile::FSEQFile(const std::string& fn) :
m_filename(fn),
m_seqNumFrames(0),
m_seqChannelCount(0),
m_seqStepTime(FSEQ_DEFAULT_STEP_TIME),
m_variableHeaders(),
m_uniqueId(0),
m_seqFileSize(0),
m_memoryBuffer(),
m_seqChanDataOffset(0),
m_memoryBufferPos(0) {
if (fn == "-memory-") {
m_seqFile = nullptr;
m_memoryBuffer.reserve(1024 * 1024);
} else {
m_seqFile = fopen((const char*)fn.c_str(), "wb");
}
}
void FSEQFile::dumpInfo(bool indent) {
char ind[5] = " ";
if (!indent) {
ind[0] = 0;
}
LogDebug(VB_SEQUENCE, "%sSequence File Information\n", ind);
LogDebug(VB_SEQUENCE, "%sseqFilename : %s\n", ind, m_filename.c_str());
LogDebug(VB_SEQUENCE, "%sseqVersion : %d.%d\n", ind, m_seqVersionMajor, m_seqVersionMinor);
LogDebug(VB_SEQUENCE, "%sseqChanDataOffset : %d\n", ind, m_seqChanDataOffset);
LogDebug(VB_SEQUENCE, "%sseqChannelCount : %d\n", ind, m_seqChannelCount);
LogDebug(VB_SEQUENCE, "%sseqNumPeriods : %d\n", ind, m_seqNumFrames);
LogDebug(VB_SEQUENCE, "%sseqStepTime : %dms\n", ind, m_seqStepTime);
}
void FSEQFile::initializeFromFSEQ(const FSEQFile& fseq) {
m_seqNumFrames = fseq.m_seqNumFrames;
m_seqChannelCount = fseq.m_seqChannelCount;
m_seqStepTime = fseq.m_seqStepTime;
m_variableHeaders = fseq.m_variableHeaders;
m_uniqueId = fseq.m_uniqueId;
if (fseq.getVersionMajor() >= 2) {
const V2FSEQFile* v2 = dynamic_cast<const V2FSEQFile*>(&fseq);
if (!v2->m_sparseRanges.empty()) {
for (auto& a : v2->m_sparseRanges) {
m_seqChannelCount = std::max(m_seqChannelCount, (a.first + a.second));
}
}
}
}
FSEQFile::FSEQFile(const std::string& fn, FILE* file, const std::vector<uint8_t>& header) :
m_filename(fn),
m_seqFile(file),
m_uniqueId(0),
m_memoryBuffer(),
m_memoryBufferPos(0) {
fseeko(m_seqFile, 0L, SEEK_END);
m_seqFileSize = ftello(m_seqFile);
fseeko(m_seqFile, 0L, SEEK_SET);
if (header[0] == V1ESEQ_HEADER_IDENTIFIER) {
m_seqChanDataOffset = V1ESEQ_CHANNEL_DATA_OFFSET;
m_seqVersionMinor = V1ESEQ_MINOR_VERSION;
m_seqVersionMajor = V1ESEQ_MAJOR_VERSION;
m_seqChannelCount = read4ByteUInt(&header[8]);
m_seqStepTime = V1ESEQ_STEP_TIME;
m_seqNumFrames = (m_seqFileSize - V1ESEQ_CHANNEL_DATA_OFFSET) / m_seqChannelCount;
} else {
m_seqChanDataOffset = read2ByteUInt(&header[4]);
m_seqVersionMinor = header[6];
m_seqVersionMajor = header[7];
m_seqChannelCount = read4ByteUInt(&header[10]);
m_seqNumFrames = read4ByteUInt(&header[14]);
m_seqStepTime = header[18];
}
}
FSEQFile::~FSEQFile() {
if (m_seqFile) {
fclose(m_seqFile);
}
}
int FSEQFile::seek(uint64_t location, int origin) {
if (m_seqFile) {
return fseeko(m_seqFile, location, origin);
} else if (origin == SEEK_SET) {
m_memoryBufferPos = location;
} else if (origin == SEEK_CUR) {
m_memoryBufferPos += location;
} else if (origin == SEEK_END) {
m_memoryBufferPos = m_memoryBuffer.size();
}
return 0;
}
uint64_t FSEQFile::tell() {
if (m_seqFile) {
return ftello(m_seqFile);
}
return m_memoryBufferPos;
}
uint64_t FSEQFile::write(const void* ptr, uint64_t size) {
if (m_seqFile) {
return fwrite(ptr, 1, size, m_seqFile);
}
if ((m_memoryBufferPos + size) > m_memoryBuffer.size()) {
m_memoryBuffer.resize(m_memoryBufferPos + size);
}
memcpy(&m_memoryBuffer[m_memoryBufferPos], ptr, size);
m_memoryBufferPos += size;
return size;
}
uint64_t FSEQFile::read(void* ptr, uint64_t size) {
return fread(ptr, 1, size, m_seqFile);
}
void FSEQFile::preload(uint64_t pos, uint64_t size) {
#ifndef PLATFORM_UNKNOWN
if (posix_fadvise(fileno(m_seqFile), pos, size, POSIX_FADV_WILLNEED) != 0) {
LogErr(VB_SEQUENCE, "Could not advise kernel %d size: %d\n", (int)pos, (int)size);
}
#endif
}
inline bool isRecognizedStringVariableHeader(uint8_t a, uint8_t b) {
// mf - media filename
// sp - sequence producer
// see https://github.com/FalconChristmas/fpp/blob/master/docs/FSEQ_Sequence_File_Format.txt#L48 for more information
return (a == 'm' && b == 'f') || (a == 's' && b == 'p');
}
inline bool isRecognizedBinaryVariableHeader(uint8_t a, uint8_t b) {
// FC - FPP Commands
// FE - FPP Effects
// ED - Extended data
return (a == 'F' && b == 'C') || (a == 'F' && b == 'E') || (a == 'E' && b == 'D');
}
void FSEQFile::parseVariableHeaders(const std::vector<uint8_t>& header, int readIndex) {
const int VariableCodeSize = 2;
const int VariableLengthSize = 2;
// when encoding, the header size is rounded to the nearest multiple of 4
// this comparison ensures that there is enough bytes left to at least constitute a 2 byte length + 2 byte code
while (readIndex + FSEQ_VARIABLE_HEADER_SIZE < header.size()) {
int dataLength = read2ByteUInt(&header[readIndex]);
readIndex += VariableLengthSize;
uint8_t code0 = header[readIndex];
uint8_t code1 = header[readIndex + 1];
readIndex += VariableCodeSize;
VariableHeader vheader;
vheader.code[0] = code0;
vheader.code[1] = code1;
if (dataLength <= FSEQ_VARIABLE_HEADER_SIZE) {
// empty data, advance only the length of the 2 byte code
LogInfo(VB_SEQUENCE, "VariableHeader has 0 length data: %c%c", code0, code1);
} else if (code0 == 'E' && code1 == 'D') {
// The actual data is elsewhere in the file
code0 = header[readIndex];
code1 = header[readIndex + 1];
readIndex += VariableCodeSize;
vheader.code[0] = code0;
vheader.code[1] = code1;
vheader.extendedData = true;
uint64_t offset;
memcpy(&offset, &header[readIndex], 8);
uint32_t len;
memcpy(&len, &header[readIndex + 8], 4);
vheader.data.resize(len);
uint64_t t = tell();
seek(offset, SEEK_SET);
read(&vheader.data[0], len);
seek(t, SEEK_SET);
readIndex += 12;
} else if (readIndex + (dataLength - FSEQ_VARIABLE_HEADER_SIZE) > header.size()) {
// ensure the data length is contained within the header
// this is primarily protection against hand modified, or corrupted, sequence files
LogErr(VB_SEQUENCE, "VariableHeader '%c%c' has out of bounds data length: %d bytes, max length: %d bytes\n",
code0, code1, readIndex + dataLength, header.size());
// there is no reasonable way to recover from this error - the reported dataLength is longer than possible
// return from parsing variable headers and let the program attempt to read the rest of the file
return;
} else {
// log when reading unrecongized variable headers
dataLength -= FSEQ_VARIABLE_HEADER_SIZE;
if (!isRecognizedStringVariableHeader(code0, code1)) {
if (!isRecognizedBinaryVariableHeader(code0, code1)) {
LogDebug(VB_SEQUENCE, "Unrecognized VariableHeader code: %c%c, length: %d bytes\n", code0, code1, dataLength);
}
} else {
// print a warning if the data is not null terminated
// this is to assist debugging potential string related issues
// the data is not forcibly null terminated to avoid mutating unknown data
if (header.size() < readIndex + dataLength) {
LogErr(VB_SEQUENCE, "VariableHeader %c%c data exceeds header buffer size! %d > %d\n",
code0, code1, (readIndex + dataLength), header.size());
} else if (header[readIndex + dataLength - 1] != '\0') {
LogErr(VB_SEQUENCE, "VariableHeader %c%c data is not NULL terminated!\n", code0, code1);
}
}
vheader.data.resize(dataLength);
memcpy(&vheader.data[0], &header[readIndex], dataLength);
LogDebug(VB_SEQUENCE, "Read VariableHeader: %c%c, length: %d bytes\n", vheader.code[0], vheader.code[1], dataLength);
// advance the length of the data
// readIndex now points at the next VariableHeader's length (if any)
readIndex += dataLength;
}
m_variableHeaders.push_back(vheader);
}
}
void FSEQFile::finalize() {
fflush(m_seqFile);
}
static const int V1FSEQ_HEADER_SIZE = 28;
V1FSEQFile::V1FSEQFile(const std::string& fn) :
FSEQFile(fn),
m_dataBlockSize(0) {
m_seqVersionMinor = V1FSEQ_MINOR_VERSION;
m_seqVersionMajor = V1FSEQ_MAJOR_VERSION;
}
void V1FSEQFile::writeHeader() {
// Additional file format documentation available at:
// https://github.com/FalconChristmas/fpp/blob/master/docs/FSEQ_Sequence_File_Format.txt#L1
// Compute headerSize to include the header and variable headers
int headerSize = V1FSEQ_HEADER_SIZE;
headerSize += m_variableHeaders.size() * FSEQ_VARIABLE_HEADER_SIZE;
for (auto& a : m_variableHeaders) {
headerSize += a.data.size();
}
// Round to a product of 4 for better memory alignment
m_seqChanDataOffset = roundTo4Internal(headerSize);
// Use m_seqChanDataOffset for buffer size to avoid additional writes or buffer allocations
// It also comes pre-memory aligned to avoid additional padding
uint8_t* header = (uint8_t*)malloc(m_seqChanDataOffset);
memset(header, 0, m_seqChanDataOffset);
// File identifier (PSEQ) - 4 bytes
header[0] = 'P';
header[1] = 'S';
header[2] = 'E';
header[3] = 'Q';
// Channel data start offset - 2 bytes
write2ByteUInt(&header[4], m_seqChanDataOffset);
// File format version - 2 bytes
header[6] = m_seqVersionMinor;
header[7] = m_seqVersionMajor;
// Fixed header length - 2 bytes
// Unlike m_seqChanDataOffset this is a static value and does not include m_variableHeaders
write2ByteUInt(&header[8], V1FSEQ_HEADER_SIZE);
// Channel count - 4 bytes
write4ByteUInt(&header[10], m_seqChannelCount);
// Number of frames - 4 bytes
write4ByteUInt(&header[14], m_seqNumFrames);
// Step time in milliseconds - 1 byte
header[18] = m_seqStepTime;
// Flags (unused & reserved, should be 0) - 1 byte
header[19] = 0;
// Universe count (unused by fpp, should be 0) - 2 bytes
write2ByteUInt(&header[20], 0);
// Universe size (unused by fpp, should be 0) - 2 bytes
write2ByteUInt(&header[22], 0);
// Gamma (unused by fpp, should be 1) - 1 byte
header[24] = 1;
// Color order (unused by fpp, should be 2) - 1 byte
header[25] = 2;
// Unused and reserved field(s), should be 0 - 2 bytes
header[26] = 0;
header[27] = 0;
int writePos = V1FSEQ_HEADER_SIZE;
// Variable headers
// 4 byte size minimum (2 byte length + 2 byte code)
for (auto& a : m_variableHeaders) {
uint32_t len = FSEQ_VARIABLE_HEADER_SIZE + a.data.size();
write2ByteUInt(&header[writePos], len);
header[writePos + 2] = a.code[0];
header[writePos + 3] = a.code[1];
memcpy(&header[writePos + 4], &a.data[0], a.data.size());
writePos += len;
}
// Validate final write position matches expected channel data offset
if (roundTo4Internal(writePos) != m_seqChanDataOffset) {
LogErr(VB_SEQUENCE, "Final write position (%d, roundTo4 = %d) does not match channel data offset (%d)! This means the header size failed to compute an accurate buffer size.\n", writePos, roundTo4Internal(writePos), m_seqChanDataOffset);
}
// Write full header at once
// header buffer is sized to the value of m_seqChanDataOffset, which comes padded for memory alignment
// If writePos extends past m_seqChanDataOffset (in error), writing m_seqChanDataOffset prevents data overflow
write(header, m_seqChanDataOffset);
free(header);
LogDebug(VB_SEQUENCE, "Setup for writing v1 FSEQ\n");
dumpInfo(true);
}
V1FSEQFile::V1FSEQFile(const std::string& fn, FILE* file, const std::vector<uint8_t>& header) :
FSEQFile(fn, file, header) {
parseVariableHeaders(header, V1FSEQ_HEADER_SIZE);
// Use the last modified time for the uniqueId
struct stat stats;
fstat(fileno(file), &stats);
m_uniqueId = stats.st_mtime;
}
V1FSEQFile::~V1FSEQFile() {
}
class UncompressedFrameData : public FSEQFile::FrameData {
public:
UncompressedFrameData(uint32_t frame,
uint32_t sz,
const std::vector<std::pair<uint32_t, uint32_t>>& ranges) :
FrameData(frame),
m_ranges(ranges) {
m_size = sz;
m_data = (uint8_t*)malloc(sz);
}
virtual ~UncompressedFrameData() {
if (m_data != nullptr) {
free(m_data);
}
}
virtual bool readFrame(uint8_t* data, uint32_t maxChannels) override {
if (m_data == nullptr)
return false;
uint32_t offset = 0;
for (auto& rng : m_ranges) {
uint32_t toRead = rng.second;
if (offset + toRead <= m_size) {
uint32_t toCopy = std::min(toRead, maxChannels - rng.first);
memcpy(&data[rng.first], &m_data[offset], toCopy);
offset += toRead;
} else {
return false;
}
}
return true;
}
uint32_t m_size;
uint8_t* m_data;
std::vector<std::pair<uint32_t, uint32_t>> m_ranges;
};
void V1FSEQFile::prepareRead(const std::vector<std::pair<uint32_t, uint32_t>>& ranges, uint32_t startFrame) {
m_rangesToRead = ranges;
m_dataBlockSize = 0;
for (auto& rng : m_rangesToRead) {
// make sure we don't read beyond the end of the sequence data
int toRead = rng.second;
if ((rng.first + toRead) > m_seqChannelCount) {
toRead = m_seqChannelCount - rng.first;
rng.second = toRead;
}
m_dataBlockSize += toRead;
}
FrameData* f = getFrame(startFrame);
if (f) {
delete f;
}
}
FrameData* V1FSEQFile::getFrame(uint32_t frame) {
if (m_rangesToRead.empty()) {
std::vector<std::pair<uint32_t, uint32_t>> range;
range.push_back(std::pair<uint32_t, uint32_t>(0, m_seqChannelCount));
prepareRead(range, frame);
}
uint64_t offset = m_seqChannelCount;
offset *= frame;
offset += m_seqChanDataOffset;
UncompressedFrameData* data = new UncompressedFrameData(frame, m_dataBlockSize, m_rangesToRead);
if (seek(offset, SEEK_SET)) {
LogErr(VB_SEQUENCE, "Failed to seek to proper offset for channel data for frame %d! %" PRIu64 "\n", frame, offset);
return data;
}
uint32_t sz = 0;
// read the ranges into the buffer
for (auto& rng : data->m_ranges) {
if (rng.first < m_seqChannelCount) {
int toRead = rng.second;
uint64_t doffset = offset;
doffset += rng.first;
seek(doffset, SEEK_SET);
size_t bread = read(&data->m_data[sz], toRead);
if (bread != toRead) {
LogErr(VB_SEQUENCE, "Failed to read channel data for frame %d! Needed to read %d but read %d\n",
frame, toRead, (int)bread);
}
sz += toRead;
}
}
return data;
}
void V1FSEQFile::addFrame(uint32_t frame,
const uint8_t* data) {
write(data, m_seqChannelCount);
}
void V1FSEQFile::finalize() {
FSEQFile::finalize();
}
uint32_t V1FSEQFile::getMaxChannel() const {
return m_seqChannelCount;
}
static const int V2FSEQ_HEADER_SIZE = 32;
static const int V2FSEQ_SPARSE_RANGE_SIZE = 6;
static const int V2FSEQ_COMPRESSION_BLOCK_SIZE = 8;
#if !defined(NO_ZLIB) || !defined(NO_ZSTD)
static const int V2FSEQ_OUT_BUFFER_SIZE = 8 * 1024 * 1024; // 8MB output buffer
static const int V2FSEQ_OUT_BUFFER_FLUSH_SIZE = 4 * 1024 * 1024; // 50% full, flush it
static const int V2FSEQ_OUT_COMPRESSION_BLOCK_SIZE = 64 * 1024; // 64KB blocks
#endif
class V2Handler {
public:
V2Handler(V2FSEQFile* f) :
m_file(f) {
m_seqChanDataOffset = f->m_seqChanDataOffset;
}
virtual ~V2Handler() {}
virtual uint8_t getCompressionType() = 0;
virtual FrameData* getFrame(uint32_t frame) = 0;
virtual uint32_t computeMaxBlocks(int max = 255) { return 0; }
virtual void addFrame(uint32_t frame, const uint8_t* data) = 0;
virtual std::string GetType() const = 0;
int seek(uint64_t location, int origin) {
return m_file->seek(location, origin);
}
uint64_t tell() {
return m_file->tell();
}
uint64_t write(const void* ptr, uint64_t size) {
return m_file->write(ptr, size);
}
uint64_t read(void* ptr, uint64_t size) {
return m_file->read(ptr, size);
}
void preload(uint64_t pos, uint64_t size) {
m_file->preload(pos, size);
}
virtual void prepareRead(uint32_t frame) {}
virtual void finalize() {
if (!m_file->getVariableHeaders().empty()) {
for (int x = 0; x < m_variableHeaderOffsets.size(); x++) {
if (m_variableHeaderOffsets[x] != 0) {
uint64_t curEnd = tell();
auto& h = m_file->getVariableHeaders()[x];
write(&h.data[0], h.data.size());
size_t cur = tell();
uint64_t off = m_variableHeaderOffsets[x];
seek(off, SEEK_SET);
write(&curEnd, 8);
seek(cur, SEEK_SET);
}
}
}
}
V2FSEQFile* m_file = nullptr;
uint64_t m_seqChanDataOffset = 0;
std::vector<uint64_t> m_variableHeaderOffsets;
};
class V2NoneCompressionHandler : public V2Handler {
public:
V2NoneCompressionHandler(V2FSEQFile* f) :
V2Handler(f) {}
virtual ~V2NoneCompressionHandler() {}
virtual uint8_t getCompressionType() override { return 0; }
virtual std::string GetType() const override { return "No Compression"; }
virtual void prepareRead(uint32_t frame) override {
FrameData* f = getFrame(frame);
if (f) {
delete f;
}
}
virtual FrameData* getFrame(uint32_t frame) override {
UncompressedFrameData* data = new UncompressedFrameData(frame, m_file->m_dataBlockSize, m_file->m_rangesToRead);
uint64_t offset = m_file->getChannelCount();
offset *= frame;
offset += m_seqChanDataOffset;
if (seek(offset, SEEK_SET)) {
LogErr(VB_SEQUENCE, "Failed to seek to proper offset for channel data! %" PRIu64 "\n", offset);
return data;
}
if (m_file->m_sparseRanges.empty()) {
uint32_t sz = 0;
// read the ranges into the buffer
for (auto& rng : data->m_ranges) {
if (rng.first < m_file->getChannelCount()) {
int toRead = rng.second;
uint64_t doffset = offset;
doffset += rng.first;
seek(doffset, SEEK_SET);
size_t bread = read(&data->m_data[sz], toRead);
if (bread != toRead) {
LogErr(VB_SEQUENCE, "Failed to read channel data! Needed to read %d but read %d\n", toRead, (int)bread);
}
sz += toRead;
}
}
} else {
size_t bread = read(data->m_data, m_file->m_dataBlockSize);
if (bread != m_file->m_dataBlockSize) {
LogErr(VB_SEQUENCE, "Failed to read channel data! Needed to read %d but read %d\n", m_file->m_dataBlockSize, (int)bread);
}
}
return data;
}
virtual void addFrame(uint32_t frame, const uint8_t* data) override {
if (m_file->m_sparseRanges.empty()) {
write(data, m_file->getChannelCount());
} else {
for (auto& a : m_file->m_sparseRanges) {
write(&data[a.first], a.second);
}
}
}
};
class V2CompressedHandler : public V2Handler {
public:
V2CompressedHandler(V2FSEQFile* f) :
V2Handler(f),
m_maxBlocks(0),
m_curBlock(99999),
m_framesPerBlock(0),
m_curFrameInBlock(0),
m_readThread(nullptr) {
if (!m_file->m_frameOffsets.empty()) {
m_maxBlocks = m_file->m_frameOffsets.size() - 1;
}
}
virtual ~V2CompressedHandler() {
if (m_readThread) {
m_readThreadRunning = false;
m_readSignal.notify_all();
m_readThread->join();
delete m_readThread;
}
for (auto& a : m_blockMap) {
if (a.second) {
free(a.second);
}
}
m_blockMap.clear();
}
virtual uint32_t computeMaxBlocks(int maxNumBlocks) override {
if (m_maxBlocks > 0) {
return m_maxBlocks;
}
// determine a good number of compression blocks
uint64_t datasize = m_file->getChannelCount();
uint64_t numFrames = m_file->getNumFrames();
datasize *= numFrames;
uint64_t numBlocks = datasize / V2FSEQ_OUT_COMPRESSION_BLOCK_SIZE;
if (numBlocks > maxNumBlocks) {
// need a lot of blocks, use as many as we can
numBlocks = maxNumBlocks;
} else if (numBlocks < 1) {
numBlocks = 1;
}
m_framesPerBlock = numFrames / numBlocks;
if (m_framesPerBlock < 2)
m_framesPerBlock = 2;
m_curFrameInBlock = 0;
m_curBlock = 0;
numBlocks = m_file->getNumFrames() / m_framesPerBlock + 1;
while (numBlocks > maxNumBlocks) {
m_framesPerBlock++;
numBlocks = m_file->getNumFrames() / m_framesPerBlock + 1;
}
// first block is going to be smaller, so add some blocks
if (numBlocks < (maxNumBlocks - 1)) {
numBlocks += 2;
} else if (numBlocks < maxNumBlocks) {
numBlocks++;
}
m_maxBlocks = numBlocks;
m_curBlock = 0;
return m_maxBlocks;
}
virtual void finalize() override {
uint64_t lastFrame = tell();
uint64_t off = V2FSEQ_HEADER_SIZE;
seek(off, SEEK_SET);
int count = m_file->m_frameOffsets.size();
if (count == 0) {
// not good, count should never be 0 unless no frames were written,
// this really should never happen, but I've seen fseq files without the
// blocks filled in so I know it DOES happen, just haven't figured out
// how it's possible yet.
LogErr(VB_SEQUENCE, "Error writing fseq file. No compressed blocks created.\n");
// we'll use the offset to the data for the 0 frame
seek(0, SEEK_SET);
uint8_t header[10];
read(header, 10);
int seqChanDataOffset = read2ByteUInt(&header[4]);
seek(off, SEEK_SET);
m_file->m_frameOffsets.push_back(std::pair<uint32_t, uint64_t>(0, seqChanDataOffset));
count++;
}
m_file->m_frameOffsets.push_back(std::pair<uint32_t, uint64_t>(99999999, lastFrame));
for (int x = 0; x < count; x++) {
uint8_t buf[8];
uint32_t frame = m_file->m_frameOffsets[x].first;
write4ByteUInt(buf, frame);
uint64_t len64 = m_file->m_frameOffsets[x + 1].second;
len64 -= m_file->m_frameOffsets[x].second;
uint32_t len = len64;
write4ByteUInt(&buf[4], len);
write(buf, 8);
// printf("%d %d: %d\n", x, frame, len);
}
m_file->m_frameOffsets.pop_back();
seek(lastFrame, SEEK_SET);
V2Handler::finalize();
}
virtual void prepareRead(uint32_t frame) override {
// start reading the first couple blocks immediately
int block = 0;
while (frame >= m_file->m_frameOffsets[block + 1].first) {
block++;
}
LogDebug(VB_SEQUENCE, "Preparing to read starting frame: %d block: %d\n", frame, block);
m_blocksToRead.push_back(block);
m_blocksToRead.push_back(block + 1);