-
Notifications
You must be signed in to change notification settings - Fork 34
/
pack.c
2143 lines (1785 loc) · 70.1 KB
/
pack.c
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
/***************************************************************************
* Generic routines to pack miniSEED records using an MS3Record as a
* header template and data source.
*
* This file is part of the miniSEED Library.
*
* Copyright (c) 2024 Chad Trabant, EarthScope Data Services
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "libmseed.h"
#include "mseedformat.h"
#include "packdata.h"
#include "extraheaders.h"
/* Internal from another source file */
extern double ms_nomsamprate (int factor, int multiplier);
/* Function(s) internal to this file */
static int msr3_pack_mseed3 (const MS3Record *msr, void (*record_handler) (char *, int, void *),
void *handlerdata, int64_t *packedsamples,
uint32_t flags, int8_t verbose);
static int msr3_pack_mseed2 (const MS3Record *msr, void (*record_handler) (char *, int, void *),
void *handlerdata, int64_t *packedsamples,
uint32_t flags, int8_t verbose);
static int64_t msr_pack_data (void *dest, void *src, uint64_t maxsamples, uint64_t maxdatabytes,
char sampletype, int8_t encoding, int8_t swapflag,
uint32_t *byteswritten, const char *sid, int8_t verbose);
static int ms_genfactmult (double samprate, int16_t *factor, int16_t *multiplier);
static int64_t ms_timestr2btime (const char *timestr, uint8_t *btime, const char *sid, int8_t swapflag);
/**********************************************************************/ /**
* @brief Pack data into miniSEED records.
*
* Packing is performed according to the version at
* @ref MS3Record.formatversion.
*
* The @ref MS3Record.datasamples array and @ref MS3Record.numsamples
* value will __not__ be changed by this routine. It is the
* responsibility of the calling routine to adjust the data buffer if
* desired.
*
* As each record is filled and finished they are passed to \a
* record_handler() which should expect 1) a \c char* to the record,
* 2) the length of the record and 3) a pointer supplied by the
* original caller containing optional private data (\a handlerdata).
* It is the responsibility of \a record_handler() to process the
* record, the memory will be re-used or freed when \a
* record_handler() returns.
*
* The following data encodings and expected @ref MS3Record.sampletype
* are supported:
* - ::DE_TEXT (0), Text, expects type \c 't'
* - ::DE_INT16 (1), 16-bit integer, expects type \c 'i'
* - ::DE_INT32 (3), 32-bit integer, expects type \c 'i'
* - ::DE_FLOAT32 (4), 32-bit float (IEEE), expects type \c 'f'
* - ::DE_FLOAT64 (5), 64-bit float (IEEE), expects type \c 'd'
* - ::DE_STEIM1 (10), Stiem-1 compressed integers, expects type \c 'i'
* - ::DE_STEIM2 (11), Stiem-2 compressed integers, expects type \c 'i'
*
* If \a flags has ::MSF_FLUSHDATA set, all of the data will be packed
* into data records even though the last one will probably be smaller
* than requested or, in the case of miniSEED 2, unfilled.
*
* Default values are: record length = 4096, encoding = 11 (Steim2).
* The defaults are triggered when \a msr.reclen and \a msr.encoding
* are set to -1.
*
* @param[in] msr ::MS3Record containing data to pack
* @param[in] record_handler() Callback function called for each record
* @param[in] handlerdata A pointer that will be provided to the \a record_handler()
* @param[out] packedsamples The number of samples packed, returned to caller
* @param[in] flags Bit flags used to control the packing process:
* @parblock
* - \c ::MSF_FLUSHDATA : Pack all data in the buffer
* - \c ::MSF_PACKVER2 : Pack miniSEED version 2 regardless of ::MS3Record.formatversion
* @endparblock
* @param[in] verbose Controls logging verbosity, 0 is no diagnostic output
*
* @returns the number of records created on success and -1 on error.
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
msr3_pack (const MS3Record *msr, void (*record_handler) (char *, int, void *),
void *handlerdata, int64_t *packedsamples, uint32_t flags, int8_t verbose)
{
int packedrecs = 0;
if (!msr)
{
ms_log (2, "%s(): Required input not defined: 'msr'\n", __func__);
return -1;
}
if (!record_handler)
{
ms_log (2, "callback record_handler() function pointer not set!\n");
return -1;
}
if ((msr->reclen != -1) && (msr->reclen < MINRECLEN || msr->reclen > MAXRECLEN))
{
ms_log (2, "%s: Record length is out of range: %d\n", msr->sid, msr->reclen);
return -1;
}
/* Pack version 2 if requested */
if (msr->formatversion == 2 || flags & MSF_PACKVER2)
{
packedrecs = msr3_pack_mseed2 (msr, record_handler, handlerdata, packedsamples,
flags, verbose);
}
/* Pack version 3 otherwise */
else
{
packedrecs = msr3_pack_mseed3 (msr, record_handler, handlerdata, packedsamples,
flags, verbose);
}
return packedrecs;
} /* End of msr3_pack() */
/***************************************************************************
* msr3_pack_mseed3:
*
* Pack data into miniSEED version 3 record(s).
*
* Returns the number of records created on success and -1 on error.
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
msr3_pack_mseed3 (const MS3Record *msr, void (*record_handler) (char *, int, void *),
void *handlerdata, int64_t *packedsamples,
uint32_t flags, int8_t verbose)
{
char *rawrec = NULL;
char *encoded = NULL; /* Separate encoded data buffer for alignment */
int8_t swapflag;
int dataoffset = 0;
int samplesize;
uint32_t maxdatabytes;
uint32_t maxsamples;
int recordcnt = 0;
int64_t packsamples;
int64_t packoffset;
int64_t totalpackedsamples;
uint32_t reclen;
uint32_t maxreclen;
uint8_t encoding;
uint32_t crc;
uint32_t datalength;
nstime_t nextstarttime;
uint16_t year;
uint16_t day;
uint8_t hour;
uint8_t min;
uint8_t sec;
uint32_t nsec;
if (!msr)
{
ms_log (2, "%s(): Required input not defined: 'msr'\n", __func__);
return -1;
}
if (!record_handler)
{
ms_log (2, "callback record_handler() function pointer not set!\n");
return -1;
}
/* Use default record length and encoding if needed */
maxreclen = (msr->reclen < 0) ? MS_PACK_DEFAULT_RECLEN : msr->reclen;
encoding = (msr->encoding < 0) ? MS_PACK_DEFAULT_ENCODING : msr->encoding;
if (maxreclen < (MS3FSDH_LENGTH + strlen(msr->sid) + msr->extralength))
{
ms_log (2, "%s: Record length (%u) is not large enough for header (%u), SID (%"PRIsize_t"), and extra (%d)\n",
msr->sid, maxreclen, MS3FSDH_LENGTH, strlen(msr->sid), msr->extralength);
return -1;
}
/* Check to see if byte swapping is needed, miniSEED 3 is little endian */
swapflag = (ms_bigendianhost ()) ? 1 : 0;
/* Allocate space for data record */
rawrec = (char *)libmseed_memory.malloc (maxreclen);
if (rawrec == NULL)
{
ms_log (2, "%s: Cannot allocate memory\n", msr->sid);
return -1;
}
memset (rawrec, 0, MS3FSDH_LENGTH);
/* Pack fixed header and extra headers, returned size is data offset */
dataoffset = msr3_pack_header3 (msr, rawrec, maxreclen, verbose);
if (dataoffset < 0)
{
ms_log (2, "%s: Cannot pack miniSEED version 3 header\n", msr->sid);
return -1;
}
/* Short cut: if there are no samples, record packing is complete */
if (msr->numsamples <= 0)
{
/* Set encoding to text for consistency and to reduce expectations */
*pMS3FSDH_ENCODING(rawrec) = DE_TEXT;
/* Calculate CRC (with CRC field set to 0) and set */
memset (pMS3FSDH_CRC(rawrec), 0, sizeof(uint32_t));
crc = ms_crc32c ((const uint8_t*)rawrec, dataoffset, 0);
*pMS3FSDH_CRC(rawrec) = HO4u (crc, swapflag);
if (verbose >= 1)
ms_log (0, "%s: Packed %d byte record with no payload\n", msr->sid, dataoffset);
/* Send record to handler */
record_handler (rawrec, dataoffset, handlerdata);
libmseed_memory.free (rawrec);
if (packedsamples)
*packedsamples = 0;
return 1;
}
samplesize = ms_samplesize (msr->sampletype);
if (!samplesize)
{
ms_log (2, "%s: Unknown sample type '%c'\n", msr->sid, msr->sampletype);
return -1;
}
/* Determine the max data bytes and sample count */
maxdatabytes = maxreclen - dataoffset;
if (encoding == DE_STEIM1)
{
maxsamples = (uint32_t)(maxdatabytes / 64) * STEIM1_FRAME_MAX_SAMPLES;
}
else if (encoding == DE_STEIM2)
{
maxsamples = (uint32_t)(maxdatabytes / 64) * STEIM2_FRAME_MAX_SAMPLES;
}
else
{
maxsamples = maxdatabytes / samplesize;
}
/* Allocate space for encoded data separately for alignment */
if (msr->numsamples > 0)
{
encoded = (char *)libmseed_memory.malloc (maxdatabytes);
if (encoded == NULL)
{
ms_log (2, "%s: Cannot allocate memory\n", msr->sid);
libmseed_memory.free (rawrec);
return -1;
}
}
/* Pack samples into records */
totalpackedsamples = 0;
packoffset = 0;
if (packedsamples)
*packedsamples = 0;
while ((msr->numsamples - totalpackedsamples) > maxsamples || flags & MSF_FLUSHDATA)
{
packsamples = msr_pack_data (encoded,
(char *)msr->datasamples + packoffset,
(int)(msr->numsamples - totalpackedsamples), maxdatabytes,
msr->sampletype, encoding, swapflag,
&datalength, msr->sid, verbose);
if (packsamples < 0)
{
ms_log (2, "%s: Error packing data samples\n", msr->sid);
libmseed_memory.free (encoded);
libmseed_memory.free (rawrec);
return -1;
}
packoffset += packsamples * samplesize;
reclen = dataoffset + datalength;
/* Copy encoded data into record */
memcpy (rawrec + dataoffset, encoded, datalength);
/* Update number of samples and data length */
*pMS3FSDH_NUMSAMPLES(rawrec) = HO4u ((uint32_t)packsamples, swapflag);
*pMS3FSDH_DATALENGTH(rawrec) = HO4u (datalength, swapflag);
/* Calculate CRC (with CRC field set to 0) and set */
memset (pMS3FSDH_CRC(rawrec), 0, sizeof(uint32_t));
crc = ms_crc32c ((const uint8_t*)rawrec, reclen, 0);
*pMS3FSDH_CRC(rawrec) = HO4u (crc, swapflag);
if (verbose >= 1)
ms_log (0, "%s: Packed %" PRId64 " samples into %u byte record\n", msr->sid, packsamples, reclen);
/* Send record to handler */
record_handler (rawrec, reclen, handlerdata);
totalpackedsamples += packsamples;
if (packedsamples)
*packedsamples = totalpackedsamples;
recordcnt++;
if (totalpackedsamples >= msr->numsamples)
break;
/* Update record start time for next record */
nextstarttime = ms_sampletime (msr->starttime, totalpackedsamples, msr->samprate);
if (ms_nstime2time (nextstarttime, &year, &day, &hour, &min, &sec, &nsec))
{
ms_log (2, "%s: Cannot convert next record starttime: %" PRId64 "\n", msr->sid, nextstarttime);
libmseed_memory.free (rawrec);
return -1;
}
*pMS3FSDH_NSEC (rawrec) = HO4u (nsec, swapflag);
*pMS3FSDH_YEAR (rawrec) = HO2u (year, swapflag);
*pMS3FSDH_DAY (rawrec) = HO2u (day, swapflag);
*pMS3FSDH_HOUR (rawrec) = hour;
*pMS3FSDH_MIN (rawrec) = min;
*pMS3FSDH_SEC (rawrec) = sec;
}
if (verbose >= 2)
ms_log (0, "%s: Packed %" PRId64 " total samples\n", msr->sid, totalpackedsamples);
if (encoded)
libmseed_memory.free (encoded);
libmseed_memory.free (rawrec);
return recordcnt;
} /* End of msr3_pack_mseed3() */
/**********************************************************************/ /**
* @brief Repack a parsed miniSEED record into a version 3 record.
*
* Pack the parsed header into a version 3 header and copy the raw
* encoded data from the original record. The original record must be
* available at the ::MS3Record.record pointer.
*
* This can be used to efficiently convert format versions or modify
* header values without unpacking the data samples.
*
* @param[in] msr ::MS3Record containing record to repack
* @param[out] record Destination buffer for repacked record
* @param[in] recbuflen Length of destination buffer
* @param[in] verbose Controls logging verbosity, 0 is no diagnostic output
*
* @returns record length on success and -1 on error.
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
msr3_repack_mseed3 (const MS3Record *msr, char *record, uint32_t recbuflen,
int8_t verbose)
{
int dataoffset;
uint32_t origdataoffset;
uint32_t origdatasize;
uint32_t crc;
uint32_t reclen;
int8_t swapflag;
if (!msr || !msr->record || ! record)
{
ms_log (2, "%s(): Required input not defined: 'msr', 'msr->record', or 'record'\n",
__func__);
return -1;
}
if (recbuflen < (MS3FSDH_LENGTH + strlen(msr->sid) + msr->extralength))
{
ms_log (2, "%s: Record length (%u) is not large enough for header (%u), SID (%"PRIsize_t"), and extra (%d)\n",
msr->sid, recbuflen, MS3FSDH_LENGTH, strlen(msr->sid), msr->extralength);
return -1;
}
if (msr->samplecnt > UINT32_MAX)
{
ms_log (2, "%s: Too many samples in input record (%" PRId64 " for a single record)\n",
msr->sid, msr->samplecnt);
return -1;
}
/* Pack fixed header and extra headers, returned size is data offset */
dataoffset = msr3_pack_header3 (msr, record, recbuflen, verbose);
if (dataoffset < 0)
{
ms_log (2, "%s: Cannot pack miniSEED version 3 header\n", msr->sid);
return -1;
}
/* Determine encoded data size */
if (msr3_data_bounds (msr, &origdataoffset, &origdatasize))
{
ms_log (2, "%s: Cannot determine original data bounds\n", msr->sid);
return -1;
}
if (recbuflen < (uint32_t)(MS3FSDH_LENGTH + msr->extralength + origdatasize))
{
ms_log (2, "%s: Destination record buffer length (%u) is not large enough for record (%d)\n",
msr->sid, recbuflen, (MS3FSDH_LENGTH + msr->extralength + origdatasize));
return -1;
}
reclen = dataoffset + origdatasize;
/* Copy encoded data into record */
memcpy (record + dataoffset, msr->record + origdataoffset, origdatasize);
/* Check to see if byte swapping is needed, miniSEED 3 is little endian */
swapflag = (ms_bigendianhost ()) ? 1 : 0;
/* Update number of samples and data length */
*pMS3FSDH_NUMSAMPLES(record) = HO4u ((uint32_t)msr->samplecnt, swapflag);
*pMS3FSDH_DATALENGTH(record) = HO4u (origdatasize, swapflag);
/* Calculate CRC (with CRC field set to 0) and set */
memset (pMS3FSDH_CRC(record), 0, sizeof(uint32_t));
crc = ms_crc32c ((const uint8_t*)record, reclen, 0);
*pMS3FSDH_CRC(record) = HO4u (crc, swapflag);
if (verbose >= 1)
ms_log (0, "%s: Repacked %" PRId64 " samples into a %u byte record\n",
msr->sid, msr->samplecnt, reclen);
return reclen;
} /* End of msr3_repack_mseed3() */
/**********************************************************************/ /**
* @brief Pack a miniSEED version 3 header into the specified buffer.
*
* Default values are: record length = 4096, encoding = 11 (Steim2).
* The defaults are triggered when \a msr.reclen and \a msr.encoding
* are set to -1.
*
* @param[in] msr ::MS3Record to pack
* @param[out] record Destination for packed header
* @param[in] recbuflen Length of destination buffer
* @param[in] verbose Controls logging verbosity, 0 is no diagnostic output
*
* @returns the size of the header (fixed and extra) on success, otherwise -1.
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
msr3_pack_header3 (const MS3Record *msr, char *record, uint32_t recbuflen, int8_t verbose)
{
int extraoffset = 0;
size_t sidlength;
uint32_t maxreclen;
uint8_t encoding;
int8_t swapflag;
uint16_t year;
uint16_t day;
uint8_t hour;
uint8_t min;
uint8_t sec;
uint32_t nsec;
if (!msr || !record)
{
ms_log (2, "%s(): Required input not defined: 'msr' or 'record'\n", __func__);
return -1;
}
/* Use default record length and encoding if needed */
maxreclen = (msr->reclen < 0) ? MS_PACK_DEFAULT_RECLEN : msr->reclen;
encoding = (msr->encoding < 0) ? MS_PACK_DEFAULT_ENCODING : msr->encoding;
if (maxreclen < MINRECLEN || maxreclen > MAXRECLEN)
{
ms_log (2, "%s: Record length is out of range: %d\n", msr->sid, maxreclen);
return -1;
}
sidlength = strlen (msr->sid);
if (recbuflen < (uint32_t)(MS3FSDH_LENGTH + sidlength + msr->extralength))
{
ms_log (2, "%s: Buffer length (%d) is not large enough for fixed header (%d), SID (%"PRIsize_t"), and extra (%d)\n",
msr->sid, recbuflen, MS3FSDH_LENGTH, sidlength, msr->extralength);
return -1;
}
/* Check to see if byte swapping is needed, miniSEED 3 is little endian */
swapflag = (ms_bigendianhost ()) ? 1 : 0;
if (verbose > 2 && swapflag)
ms_log (0, "%s: Byte swapping needed for packing of header\n", msr->sid);
/* Break down start time into individual components */
if (ms_nstime2time (msr->starttime, &year, &day, &hour, &min, &sec, &nsec))
{
ms_log (2, "%s: Cannot convert starttime: %" PRId64 "\n", msr->sid, msr->starttime);
return -1;
}
/* Ensure that SID length fits in format, which uses data type uint8_t */
if (sidlength > 255)
{
ms_log (2, "%s: Source ID too long: %"PRIsize_t" bytes\n", msr->sid, sidlength);
return -1;
}
extraoffset = MS3FSDH_LENGTH + (int)sidlength;
/* Build fixed header */
record[0] = 'M';
record[1] = 'S';
*pMS3FSDH_FORMATVERSION (record) = 3;
*pMS3FSDH_FLAGS (record) = msr->flags;
*pMS3FSDH_NSEC (record) = HO4u (nsec, swapflag);
*pMS3FSDH_YEAR (record) = HO2u (year, swapflag);
*pMS3FSDH_DAY (record) = HO2u (day, swapflag);
*pMS3FSDH_HOUR (record) = hour;
*pMS3FSDH_MIN (record) = min;
*pMS3FSDH_SEC (record) = sec;
*pMS3FSDH_ENCODING (record) = encoding;
/* If rate positive and less than one, convert to period notation */
if (msr->samprate != 0.0 && msr->samprate > 0 && msr->samprate < 1.0)
*pMS3FSDH_SAMPLERATE(record) = HO8f((-1.0 / msr->samprate), swapflag);
else
*pMS3FSDH_SAMPLERATE(record) = HO8f(msr->samprate, swapflag);
*pMS3FSDH_PUBVERSION(record) = msr->pubversion;
*pMS3FSDH_SIDLENGTH(record) = (uint8_t)sidlength;
*pMS3FSDH_EXTRALENGTH(record) = HO2u(msr->extralength, swapflag);
memcpy (pMS3FSDH_SID(record), msr->sid, sidlength);
if (msr->extralength > 0)
memcpy (record + extraoffset, msr->extra, msr->extralength);
return (MS3FSDH_LENGTH + (int)sidlength + msr->extralength);
} /* End of msr3_pack_header3() */
/***************************************************************************
* msr3_pack_mseed2:
*
* Pack data into miniSEED version 2 record(s).
*
* Returns the number of records created on success and -1 on error.
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
msr3_pack_mseed2 (const MS3Record *msr, void (*record_handler) (char *, int, void *),
void *handlerdata, int64_t *packedsamples,
uint32_t flags, int8_t verbose)
{
char *rawrec = NULL;
char *encoded = NULL; /* Separate encoded data buffer for alignment */
int8_t swapflag;
uint32_t reclen;
uint8_t encoding;
int dataoffset = 0;
int headerlen;
uint32_t content;
int samplesize;
uint32_t maxdatabytes;
uint32_t maxsamples;
int recordcnt = 0;
int64_t packsamples;
int64_t packoffset;
int64_t totalpackedsamples;
uint32_t datalength;
nstime_t nextstarttime;
uint16_t year;
uint16_t day;
uint8_t hour;
uint8_t min;
uint8_t sec;
uint32_t nsec;
if (!msr)
{
ms_log (2, "%s(): Required input not defined: 'msr'\n", __func__);
return -1;
}
if (!record_handler)
{
ms_log (2, "callback record_handler() function pointer not set!\n");
return -1;
}
/* Use default record length and encoding if needed */
reclen = (msr->reclen < 0) ? MS_PACK_DEFAULT_RECLEN : msr->reclen;
encoding = (msr->encoding < 0) ? MS_PACK_DEFAULT_ENCODING : msr->encoding;
if (reclen < 128 || reclen > MAXRECLENv2)
{
ms_log (2, "%s: Record length (%u) is out of allowed range: 128 to %u bytes\n",
msr->sid, reclen, MAXRECLENv2);
return -1;
}
/* Check that record length is a power of 2.
* Power of two if (X & (X - 1)) == 0 */
if ((reclen & (reclen - 1)) != 0)
{
ms_log (2, "%s: Cannot create miniSEED 2, record length (%u) is not a power of 2\n",
msr->sid, reclen);
return -1;
}
/* Check to see if byte swapping is needed, miniSEED 2 is written big endian */
swapflag = (ms_bigendianhost ()) ? 0 : 1;
/* Allocate space for data record */
rawrec = (char *)libmseed_memory.malloc (reclen);
if (rawrec == NULL)
{
ms_log (2, "%s: Cannot allocate memory\n", msr->sid);
return -1;
}
memset (rawrec, 0, MS2FSDH_LENGTH);
/* Pack fixed header and extra headers, returned size is data offset */
headerlen = msr3_pack_header2 (msr, rawrec, reclen, verbose);
if (headerlen < 0)
return -1;
/* Short cut: if there are no samples, record packing is complete */
if (msr->numsamples <= 0)
{
/* Set encoding to text for consistency and to reduce expectations */
*pMS2B1000_ENCODING (rawrec + 48) = DE_TEXT;
/* Set empty part of record to zeros */
memset (rawrec + headerlen, 0, reclen - headerlen);
if (verbose >= 1)
ms_log (0, "%s: Packed %u byte record with no payload\n", msr->sid, reclen);
/* Send record to handler */
record_handler (rawrec, reclen, handlerdata);
libmseed_memory.free (rawrec);
if (packedsamples)
*packedsamples = 0;
return 1;
}
samplesize = ms_samplesize (msr->sampletype);
if (!samplesize)
{
ms_log (2, "%s: Unknown sample type '%c'\n", msr->sid, msr->sampletype);
return -1;
}
/* Determine offset to encoded data */
if (encoding == DE_STEIM1 || encoding == DE_STEIM2)
{
dataoffset = 64;
while (dataoffset < headerlen)
dataoffset += 64;
/* Zero memory between blockettes and data if any */
memset (rawrec + headerlen, 0, dataoffset - headerlen);
}
else
{
dataoffset = headerlen;
}
/* Set data offset in header */
*pMS2FSDH_DATAOFFSET(rawrec) = HO2u (dataoffset, swapflag);
/* Determine the max data bytes and sample count */
maxdatabytes = reclen - dataoffset;
if (encoding == DE_STEIM1)
{
maxsamples = (int)(maxdatabytes / 64) * STEIM1_FRAME_MAX_SAMPLES;
}
else if (encoding == DE_STEIM2)
{
maxsamples = (int)(maxdatabytes / 64) * STEIM2_FRAME_MAX_SAMPLES;
}
else
{
maxsamples = maxdatabytes / samplesize;
}
/* Allocate space for encoded data separately for alignment */
if (msr->numsamples > 0)
{
encoded = (char *)libmseed_memory.malloc (maxdatabytes);
if (encoded == NULL)
{
ms_log (2, "%s: Cannot allocate memory\n", msr->sid);
libmseed_memory.free (rawrec);
return -1;
}
}
/* Pack samples into records */
totalpackedsamples = 0;
packoffset = 0;
if (packedsamples)
*packedsamples = 0;
while ((msr->numsamples - totalpackedsamples) > maxsamples || flags & MSF_FLUSHDATA)
{
packsamples = msr_pack_data (encoded,
(char *)msr->datasamples + packoffset,
(int)(msr->numsamples - totalpackedsamples), maxdatabytes,
msr->sampletype, encoding, swapflag,
&datalength, msr->sid, verbose);
if (packsamples < 0)
{
ms_log (2, "%s: Error packing data samples\n", msr->sid);
libmseed_memory.free (encoded);
libmseed_memory.free (rawrec);
return -1;
}
if (packsamples > UINT16_MAX)
{
ms_log (2, "%s: Too many samples packed (%" PRId64 ") for a single v2 record)\n",
msr->sid, packsamples);
libmseed_memory.free (encoded);
libmseed_memory.free (rawrec);
return -1;
}
packoffset += packsamples * samplesize;
/* Copy encoded data into record */
memcpy (rawrec + dataoffset, encoded, datalength);
/* Update number of samples */
*pMS2FSDH_NUMSAMPLES(rawrec) = HO2u ((uint16_t)packsamples, swapflag);
/* Zero any space between encoded data and end of record */
content = dataoffset + datalength;
if (content < reclen)
memset (rawrec + content, 0, reclen - content);
if (verbose >= 1)
ms_log (0, "%s: Packed %" PRId64 " samples into %u byte record\n", msr->sid, packsamples, reclen);
/* Send record to handler */
record_handler (rawrec, reclen, handlerdata);
totalpackedsamples += packsamples;
if (packedsamples)
*packedsamples = totalpackedsamples;
recordcnt++;
if (totalpackedsamples >= msr->numsamples)
break;
/* Update record start time for next record */
nextstarttime = ms_sampletime (msr->starttime, totalpackedsamples, msr->samprate);
if (ms_nstime2time (nextstarttime, &year, &day, &hour, &min, &sec, &nsec))
{
ms_log (2, "%s: Cannot convert next record starttime: %" PRId64 "\n",
msr->sid, nextstarttime);
libmseed_memory.free (encoded);
libmseed_memory.free (rawrec);
return -1;
}
*pMS2FSDH_YEAR (rawrec) = HO2u (year, swapflag);
*pMS2FSDH_DAY (rawrec) = HO2u (day, swapflag);
*pMS2FSDH_HOUR (rawrec) = hour;
*pMS2FSDH_MIN (rawrec) = min;
*pMS2FSDH_SEC (rawrec) = sec;
*pMS2FSDH_FSEC (rawrec) = HO2u ((nsec / 100000), swapflag);
}
if (verbose >= 2)
ms_log (0, "%s: Packed %" PRId64 " total samples\n", msr->sid, totalpackedsamples);
if (encoded)
libmseed_memory.free (encoded);
libmseed_memory.free (rawrec);
return recordcnt;
} /* End of msr3_pack_mseed2() */
/**********************************************************************/ /**
* @brief Pack a miniSEED version 2 header into the specified buffer.
*
* Default values are: record length = 4096, encoding = 11 (Steim2).
* The defaults are triggered when \a msr.reclen and \a msr.encoding
* are set to -1.
*
* @param[in] msr ::MS3Record to pack
* @param[out] record Destination for packed header
* @param[in] recbuflen Length of destination buffer
* @param[in] verbose Controls logging verbosity, 0 is no diagnostic output
*
* @returns the size of the header (fixed and blockettes) on success, otherwise -1.
*
* \ref MessageOnError - this function logs a message on error
***************************************************************************/
int
msr3_pack_header2 (const MS3Record *msr, char *record, uint32_t recbuflen, int8_t verbose)
{
int written = 0;
int8_t swapflag;
uint32_t reclen;
uint8_t encoding;
char network[64];
char station[64];
char location[64];
char channel[64];
uint16_t year;
uint16_t day;
uint8_t hour;
uint8_t min;
uint8_t sec;
uint32_t nsec;
uint16_t fsec;
int8_t msec_offset;
uint32_t reclenexp = 0;
uint32_t reclenfind;
int16_t factor;
int16_t multiplier;
uint16_t *next_blockette = NULL;
yyjson_doc *ehdoc = NULL;
yyjson_val *ehroot = NULL;
yyjson_read_flag flg = YYJSON_READ_NOFLAG;
yyjson_alc alc = {_priv_malloc, _priv_realloc, _priv_free, NULL};
yyjson_read_err err;
yyjson_val *eharr;
yyjson_arr_iter ehiter;
yyjson_val *ehiterval;
const char *header_string;
double header_number;
uint64_t header_uint;
bool header_boolean;
uint16_t blockette_type;
uint16_t blockette_length;
if (!msr || !record)
{
ms_log (2, "%s(): Required input not defined: 'msr' or 'record'\n", __func__);
return -1;
}
/* Use default record length and encoding if needed */
reclen = (msr->reclen < 0) ? MS_PACK_DEFAULT_RECLEN : msr->reclen;
encoding = (msr->encoding < 0) ? MS_PACK_DEFAULT_ENCODING : msr->encoding;
if (reclen < 128 || reclen > MAXRECLEN)
{
ms_log (2, "%s: Record length is out of range: %u\n", msr->sid, reclen);
return -1;
}
/* Check that record length is a power of 2.
* Power of two if (X & (X - 1)) == 0 */
if ((reclen & (reclen - 1)) != 0)
{
ms_log (2, "%s: Cannot pack miniSEED 2, record length (%u) is not a power of 2\n",
msr->sid, reclen);
return -1;
}
/* Calculate the record length as an exponent of 2 */
for (reclenfind = 1, reclenexp = 1; reclenfind <= MAXRECLEN; reclenexp++)
{
reclenfind *= 2;
if (reclenfind == reclen)
break;
}
/* Parse identifier codes from full identifier */
if (ms_sid2nslc (msr->sid, network, station, location, channel))
{
ms_log (2, "%s: Cannot parse SEED identifier codes from full identifier\n", msr->sid);
return -1;
}
/* Verify that identifier codes will fit into and are appropriate for miniSEED 2 */
if (strlen (network) > 2 || strlen (station) > 5 || strlen (location) > 2 || strlen (channel) != 3)
{
ms_log (2, "%s: Cannot create miniSEED 2 for N,S,L,C codes: %s, %s, %s, %s\n",
msr->sid, network, station, location, channel);
return -1;
}
/* Check to see if byte swapping is needed, miniSEED 2 is written big endian */
swapflag = (ms_bigendianhost ()) ? 0 : 1;
if (verbose > 2 && swapflag)
ms_log (0, "%s: Byte swapping needed for packing of header\n", msr->sid);
/* Break down start time into individual components */
if (ms_nstime2time (msr->starttime, &year, &day, &hour, &min, &sec, &nsec))
{
ms_log (2, "%s: Cannot convert starttime: %" PRId64 "\n", msr->sid, msr->starttime);
return -1;
}
/* Calculate time at fractional 100usec resolution and microsecond offset */
fsec = nsec / 100000;
msec_offset = ((nsec / 1000) - (fsec * 100));
/* Generate factor & multipler representation of sample rate */
if (ms_genfactmult (msr3_sampratehz(msr), &factor, &multiplier))
{
ms_log (2, "%s: Cannot convert sample rate (%g) to factor and multiplier\n", msr->sid, msr->samprate);
return -1;
}
/* Parse extra headers if present */
if (msr->extra && msr->extralength > 0)
{
ehdoc = yyjson_read_opts (msr->extra, msr->extralength, flg, &alc, &err);
if (!ehdoc)
{
ms_log (2, "%s() Cannot parse extra header JSON: %s\n",
__func__, (err.msg) ? err.msg : "Unknown error");
return -1;
}
ehroot = yyjson_doc_get_root (ehdoc);
}
/* Build fixed header */
/* Use sequence number from extra headers if present */
if (yyjson_ptr_get_uint (ehroot, "/FDSN/Sequence", &header_uint))
{
if (header_uint <= 999999)
{
char seqnum[7];
snprintf (seqnum, sizeof (seqnum), "%06" PRIu64, header_uint);
memcpy (pMS2FSDH_SEQNUM (record), seqnum, 6);
}
else
{