-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathpack.c
More file actions
2632 lines (2236 loc) · 88.6 KB
/
Copy pathpack.c
File metadata and controls
2632 lines (2236 loc) · 88.6 KB
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 "extraheaders.h"
#include "internalstate.h"
#include "libmseed.h"
#include "mseedformat.h"
#include "packdata.h"
/* Internal from another source file */
extern double ms_nomsamprate (int factor, int multiplier);
/* Function(s) internal to this file */
static int msr3_pack_header2_offsets (const MS3Record *msr, char *record, uint32_t recbuflen,
uint16_t *blockette_1000_offset,
uint16_t *blockette_1001_offset, 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 nstime_t ms_timestr2btime (const char *timestr, uint8_t *btime, int8_t *usec_offset,
const char *sid, int8_t swapflag);
static nstime_t nstime2fsec_usec_offset (nstime_t nstime, uint16_t *fsec, int8_t *usec_offset);
/** ************************************************************************
* @brief Pack data into miniSEED records using a callback function to handle
* the 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 @p
* 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 (@p handlerdata).
* It is the responsibility of @p record_handler() to process the
* record, the memory will be re-used or freed when @p 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), Steim-1 compressed integers, expects type @c 'i'
* - ::DE_STEIM2 (11), Steim-2 compressed integers, expects type @c 'i'
*
* If @p 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 @p msr.reclen and @p msr.encoding
* are set to -1.
*
* To create a header-only record with no data payload (i.e., no samples), set
* @ref MS3Record.numsamples to 0.
*
* @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 @p 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
*
* @see msr3_pack_init()
* @see msr3_pack_next()
* @see msr3_pack_free()
***************************************************************************/
int
msr3_pack (const MS3Record *msr, void (*record_handler) (char *, int, void *), void *handlerdata,
int64_t *packedsamples, uint32_t flags, int8_t verbose)
{
MS3RecordPacker *packer = NULL;
char *record = NULL;
int32_t reclen = 0;
int result;
int recordcount = 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;
}
/* Initialize packer */
packer = msr3_pack_init (msr, flags, verbose);
if (!packer)
return -1;
/* Generate records using generator interface */
while ((result = msr3_pack_next (packer, &record, &reclen)) == 1)
{
record_handler (record, reclen, handlerdata);
recordcount++;
}
/* Free packer and get total packed samples */
msr3_pack_free (&packer, packedsamples);
/* Return record count on success, -1 on error */
return (result == 0) ? recordcount : -1;
} /* End of msr3_pack() */
/***************************************************************************
* Maximum samples that fit in maxdatabytes for a given encoding, the same
* formula used by lm_pack_state_init() to set packer->maxsamples.
***************************************************************************/
static uint32_t
lm_pack_maxsamples (uint32_t maxdatabytes, uint8_t encoding, uint8_t samplesize)
{
if (encoding == DE_STEIM1)
return (maxdatabytes / 64) * STEIM1_FRAME_MAX_SAMPLES;
else if (encoding == DE_STEIM2)
return (maxdatabytes / 64) * STEIM2_FRAME_MAX_SAMPLES;
else
return (samplesize) ? maxdatabytes / samplesize : 0;
} /* End of lm_pack_maxsamples() */
/***************************************************************************
* Test whether a record with the given geometry cannot hold numsamples,
* i.e. whether msr3_pack_next() would return 0 on a fresh packer with this
* geometry and without ::MSF_FLUSHDATA set. No allocation, no writing.
*
* Only miniSEED 3 geometry is pure arithmetic; miniSEED 2 depends on the
* blockette layout assembled by msr3_pack_header2_offsets(), so this
* always returns 0 (not determined) for miniSEED 2 and callers must fall
* back to a full msr3_pack_init() to find out.
*
* Returns non-zero if the record is short of a full record, and 0 if it
* may already be able to fill one or the geometry cannot be determined.
***************************************************************************/
int
lm_pack_short_of_record (int8_t formatversion, uint32_t maxreclen, size_t sidlength,
uint16_t extralength, uint8_t encoding, uint8_t samplesize,
int64_t numsamples)
{
uint32_t offset;
uint32_t maxdatabytes;
uint32_t maxsamples;
if (formatversion != 3 || !samplesize || numsamples <= 0 || maxreclen < MINRECLEN ||
maxreclen > MAXRECLEN)
return 0;
offset = MS3FSDH_LENGTH + (uint32_t)sidlength + extralength;
if (maxreclen < offset)
return 0;
maxdatabytes = maxreclen - offset;
maxsamples = lm_pack_maxsamples (maxdatabytes, encoding, samplesize);
return (uint64_t)numsamples < maxsamples;
} /* End of lm_pack_short_of_record() */
/** ************************************************************************
* @brief Initialize a packer for generator-style record creation
*
* Create and initialize an opaque ::MS3RecordPacker context for generating
* miniSEED records one at a time from an ::MS3Record.
*
* To create a header-only record with no data payload (i.e., no samples), set
* @ref MS3Record.numsamples to 0.
*
* The packer should be freed with msr3_pack_free() when done.
*
* @param[in] msr ::MS3Record containing data to pack
* @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 pointer to ::MS3RecordPacker on success and NULL on error,
*
* @ref MessageOnError - this function logs a message on error
*
* @see msr3_pack_next()
* @see msr3_pack_free()
***************************************************************************/
MS3RecordPacker *
msr3_pack_init (const MS3Record *msr, uint32_t flags, int8_t verbose)
{
MS3RecordPacker *packer = NULL;
if (!msr)
{
ms_log (2, "%s(): Required input not defined: 'msr'\n", __func__);
return NULL;
}
/* Allocate pack state context */
packer = (MS3RecordPacker *)libmseed_memory.malloc (sizeof (MS3RecordPacker));
if (!packer)
{
ms_log (2, "Cannot allocate memory for packer context\n");
return NULL;
}
memset (packer, 0, sizeof (MS3RecordPacker));
if (lm_pack_state_init (packer, msr, flags, verbose))
{
lm_pack_state_free (packer);
libmseed_memory.free (packer);
return NULL;
}
return packer;
} /* End of msr3_pack_init() */
/***************************************************************************
* Start (or restart) a packing session in a caller-allocated packer,
* reusing its rawrec/encoded buffers when they are already large enough.
*
* This is everything msr3_pack_init() does beyond allocating the
* ::MS3RecordPacker itself, factored out so a packer embedded in a
* longer-lived context (e.g. ::MS3TraceListPacker) can be re-initialized
* for each segment without a malloc/free cycle.
*
* Returns 0 on success and -1 on error.
***************************************************************************/
int
lm_pack_state_init (MS3RecordPacker *packer, const MS3Record *msr, uint32_t flags, int8_t verbose)
{
if (!packer || !msr)
{
ms_log (2, "%s(): Required input not defined: 'packer' or 'msr'\n", __func__);
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;
}
if (msr->starttime == NSTUNSET || msr->starttime == NSTERROR)
{
ms_log (2, "%s: Record start time is unset\n", msr->sid);
return -1;
}
/* Reset per-session state, retaining rawrec/encoded and their allocated
* sizes for reuse regardless of what else this struct grows to hold */
{
char *rawrec = packer->rawrec;
uint32_t rawrec_size = packer->rawrec_size;
char *encoded = packer->encoded;
uint32_t encoded_size = packer->encoded_size;
memset (packer, 0, sizeof (*packer));
packer->rawrec = rawrec;
packer->rawrec_size = rawrec_size;
packer->encoded = encoded;
packer->encoded_size = encoded_size;
}
packer->msr = msr;
packer->flags = flags;
packer->verbose = verbose;
/* Determine format version */
packer->formatversion = (msr->formatversion == 2 || flags & MSF_PACKVER2) ? 2 : 3;
/* Use default record length and encoding if needed */
packer->maxreclen = (msr->reclen < 0) ? MS_PACK_DEFAULT_RECLEN : msr->reclen;
packer->encoding = (msr->encoding < 0) ? MS_PACK_DEFAULT_ENCODING : msr->encoding;
/* Check to see if byte swapping is needed */
if (packer->formatversion == 3)
{
/* miniSEED 3 is little endian */
packer->swapflag = (ms_bigendianhost ()) ? 1 : 0;
}
else
{
/* miniSEED 2 is big endian */
packer->swapflag = (ms_bigendianhost ()) ? 0 : 1;
}
/* Validate record length vs header size */
if (packer->formatversion == 3)
{
if (packer->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, packer->maxreclen, MS3FSDH_LENGTH, strlen (msr->sid), msr->extralength);
return -1;
}
}
/* Allocate space for generated record, reusing the existing buffer if
* already large enough */
if (packer->rawrec_size < packer->maxreclen)
{
char *rawrec = (char *)libmseed_memory.realloc (packer->rawrec, packer->maxreclen);
if (!rawrec)
{
ms_log (2, "%s: Cannot allocate memory for record buffer\n", msr->sid);
return -1;
}
packer->rawrec = rawrec;
packer->rawrec_size = packer->maxreclen;
}
memset (packer->rawrec, 0, packer->maxreclen);
/* For records with samples, validate sample type before packing */
if (msr->numsamples > 0)
{
packer->samplesize = ms_samplesize (msr->sampletype);
if (!packer->samplesize)
{
ms_log (2, "%s: Unknown sample type '%c'\n", msr->sid, msr->sampletype);
return -1;
}
}
/* Pack header (required for header-only and data-containing records) */
if (packer->formatversion == 3)
{
packer->dataoffset = msr3_pack_header3 (msr, packer->rawrec, packer->maxreclen, verbose);
}
else
{
packer->dataoffset = msr3_pack_header2_offsets (msr, packer->rawrec, packer->maxreclen,
&packer->blockette_1000_offset,
&packer->blockette_1001_offset, verbose);
if (packer->dataoffset > 0 && msr->numsamples > 0)
{
/* For Steim encodings, align data offset to 64-byte boundary */
if (packer->encoding == DE_STEIM1 || packer->encoding == DE_STEIM2)
{
packer->dataoffset = ((packer->dataoffset + 63) / 64) * 64;
}
/* The (possibly aligned) data offset must still leave room for data
* within the record and fit the 16-bit v2 data-offset field. */
if ((uint32_t)packer->dataoffset >= packer->maxreclen || packer->dataoffset > UINT16_MAX)
{
ms_log (2, "%s: Data offset (%d) does not fit within record length (%u)\n", msr->sid,
packer->dataoffset, packer->maxreclen);
return -1;
}
/* Set data offset in header */
*pMS2FSDH_DATAOFFSET (packer->rawrec) = HO2u (packer->dataoffset, packer->swapflag);
}
}
if (packer->dataoffset < 0)
{
ms_log (2, "%s: Cannot pack miniSEED header\n", msr->sid);
return -1;
}
/* For records with samples, set up encoding buffers and parameters */
if (msr->numsamples > 0)
{
/* Determine the max data bytes and sample count */
packer->maxdatabytes = packer->maxreclen - packer->dataoffset;
packer->maxsamples =
lm_pack_maxsamples (packer->maxdatabytes, packer->encoding, packer->samplesize);
/* The miniSEED 2 FSDH sample count is a 16-bit field, so a single
* record cannot represent more than UINT16_MAX samples regardless of
* the record length. */
if (packer->formatversion == 2 && packer->maxsamples > UINT16_MAX)
{
packer->maxsamples = UINT16_MAX;
}
/* Allocate space for encoded data separately for alignment, reusing
* the existing buffer if already large enough */
if (packer->encoded_size < packer->maxdatabytes)
{
char *encoded = (char *)libmseed_memory.realloc (packer->encoded, packer->maxdatabytes);
if (!encoded)
{
ms_log (2, "%s: Cannot allocate memory for encoded data buffer\n", msr->sid);
return -1;
}
packer->encoded = encoded;
packer->encoded_size = packer->maxdatabytes;
}
}
packer->nextstarttime = msr->starttime;
if (verbose > 2)
ms_log (0, "%s: Initialized packing state for %s records\n", msr->sid,
(packer->formatversion == 3) ? "miniSEED 3" : "miniSEED 2");
return 0;
} /* End of lm_pack_state_init() */
/** ************************************************************************
* @brief Generate next miniSEED record.
*
* Pack the next miniSEED record from the packing context initialized with
* msr3_pack_init(). The record pointer and length are returned via the
* @p record and @p reclen parameters. The record memory is owned by the
* @p packer and will be reused or freed on subsequent calls.
*
* This function should be called repeatedly until it returns 0 (no more
* records) or -1 (error).
*
* @param[in] packer ::MS3RecordPacker context
* @param[out] record Pointer to record buffer (owned by packer)
* @param[out] reclen Length of record in bytes
*
* @return 1 when a record is available, 0 when finished, and -1 on error.
*
* @ref MessageOnError - this function logs a message on error
*
* @see msr3_pack_init()
* @see msr3_pack_free()
***************************************************************************/
int
msr3_pack_next (MS3RecordPacker *packer, char **record, int32_t *reclen)
{
int64_t samples_packed;
int64_t packoffset_bytes;
uint64_t remaining_samples;
uint32_t datalength;
uint32_t reclen_generated;
uint32_t crc;
uint16_t year;
uint16_t day;
uint8_t hour;
uint8_t min;
uint8_t sec;
uint32_t nsec;
uint16_t fsec;
int8_t usec_offset;
if (!packer || !record || !reclen)
{
ms_log (2, "%s(): Required input not defined\n", __func__);
return -1;
}
if (packer->finished)
return 0;
/* Handle header-only records (no data samples) */
if (packer->msr->numsamples <= 0)
{
if (packer->formatversion == 3)
{
/* Set encoding to text (value of 0) for consistency */
*pMS3FSDH_ENCODING (packer->rawrec) = DE_TEXT;
*pMS3FSDH_NUMSAMPLES (packer->rawrec) = HO4u (0, packer->swapflag);
*pMS3FSDH_DATALENGTH (packer->rawrec) = HO4u (0, packer->swapflag);
/* Calculate CRC and set */
memset (pMS3FSDH_CRC (packer->rawrec), 0, sizeof (uint32_t));
crc = ms_crc32c ((const uint8_t *)packer->rawrec, packer->dataoffset, 0);
*pMS3FSDH_CRC (packer->rawrec) = HO4u (crc, packer->swapflag);
if (packer->verbose >= 1)
ms_log (0, "%s: Packed %d byte record with no payload\n", packer->msr->sid,
packer->dataoffset);
*record = packer->rawrec;
*reclen = packer->dataoffset;
}
else /* version 2 */
{
/* Set encoding to text (value of 0) for consistency */
if (packer->blockette_1000_offset)
{
*pMS2B1000_ENCODING (packer->rawrec + packer->blockette_1000_offset) = DE_TEXT;
}
/* Data segment is not used; clear it */
if (packer->dataoffset > 0 && (uint32_t)packer->dataoffset < packer->maxreclen)
memset (packer->rawrec + packer->dataoffset, 0,
(size_t)(packer->maxreclen - (uint32_t)packer->dataoffset));
if (packer->verbose >= 1)
ms_log (0, "%s: Packed %u byte record with no payload\n", packer->msr->sid,
packer->maxreclen);
*record = packer->rawrec;
*reclen = packer->maxreclen;
}
packer->recordcount++;
packer->finished = 1;
return 1;
}
/* Calculate remaining samples */
remaining_samples = packer->msr->numsamples - packer->packed_samples;
/* Finished packing if all samples have been packed or less than max samples and not flushing */
if ((remaining_samples == 0) ||
(remaining_samples < packer->maxsamples && !(packer->flags & MSF_FLUSHDATA)))
{
packer->finished = 1;
return 0;
}
/* Pack data samples */
packoffset_bytes = packer->packed_samples * packer->samplesize;
/* miniSEED 2 FSDH sample count is 16-bit; cap so excess spills to next records */
uint64_t samples_to_pack = remaining_samples;
if (packer->formatversion == 2 && samples_to_pack > UINT16_MAX)
samples_to_pack = UINT16_MAX;
samples_packed = msr_pack_data (
packer->encoded, (uint8_t *)packer->msr->datasamples + packoffset_bytes, samples_to_pack,
packer->maxdatabytes, packer->msr->sampletype, packer->encoding, packer->swapflag,
&datalength, packer->msr->sid, packer->verbose);
if (samples_packed < 0)
{
ms_log (2, "%s: Error packing data samples\n", packer->msr->sid);
return -1;
}
/* Only proceed if samples were actually packed */
else if (samples_packed == 0)
{
packer->finished = 1;
return 0;
}
/* Copy encoded data into record */
memcpy (packer->rawrec + packer->dataoffset, packer->encoded, datalength);
/* Version 3 record */
if (packer->formatversion == 3)
{
/* Calculate record length */
reclen_generated = packer->dataoffset + datalength;
/* Update number of samples and data length */
*pMS3FSDH_NUMSAMPLES (packer->rawrec) = HO4u ((uint32_t)samples_packed, packer->swapflag);
*pMS3FSDH_DATALENGTH (packer->rawrec) = HO4u (datalength, packer->swapflag);
/* Update start time if not first record */
if (packer->recordcount > 0)
{
if (ms_nstime2time (packer->nextstarttime, &year, &day, &hour, &min, &sec, &nsec))
{
ms_log (2, "%s: Cannot convert record starttime: %" PRId64 "\n", packer->msr->sid,
packer->nextstarttime);
return -1;
}
*pMS3FSDH_NSEC (packer->rawrec) = HO4u (nsec, packer->swapflag);
*pMS3FSDH_YEAR (packer->rawrec) = HO2u (year, packer->swapflag);
*pMS3FSDH_DAY (packer->rawrec) = HO2u (day, packer->swapflag);
*pMS3FSDH_HOUR (packer->rawrec) = hour;
*pMS3FSDH_MIN (packer->rawrec) = min;
*pMS3FSDH_SEC (packer->rawrec) = sec;
}
/* Calculate CRC and set */
memset (pMS3FSDH_CRC (packer->rawrec), 0, sizeof (uint32_t));
crc = ms_crc32c ((const uint8_t *)packer->rawrec, reclen_generated, 0);
*pMS3FSDH_CRC (packer->rawrec) = HO4u (crc, packer->swapflag);
}
/* Version 2 record */
else
{
/* V2 records are always full length */
reclen_generated = packer->maxreclen;
/* Update number of samples */
*pMS2FSDH_NUMSAMPLES (packer->rawrec) = HO2u ((uint16_t)samples_packed, packer->swapflag);
/* Zero any space between encoded data and end of record */
uint32_t content = packer->dataoffset + datalength;
if (content < packer->maxreclen)
memset (packer->rawrec + content, 0, packer->maxreclen - content);
/* Update start time if not first record */
if (packer->recordcount > 0)
{
nstime_t second_nstime = nstime2fsec_usec_offset (packer->nextstarttime, &fsec, &usec_offset);
/* Use the (possibly carried) second-resolution time so Y/D/H/M/S stay
* consistent with fsec/usec_offset when rounding carries into the next second */
if (second_nstime == NSTERROR ||
ms_nstime2time (second_nstime, &year, &day, &hour, &min, &sec, NULL))
{
ms_log (2, "%s: Cannot convert record starttime: %" PRId64 "\n", packer->msr->sid,
packer->nextstarttime);
return -1;
}
*pMS2FSDH_YEAR (packer->rawrec) = HO2u (year, packer->swapflag);
*pMS2FSDH_DAY (packer->rawrec) = HO2u (day, packer->swapflag);
*pMS2FSDH_HOUR (packer->rawrec) = hour;
*pMS2FSDH_MIN (packer->rawrec) = min;
*pMS2FSDH_SEC (packer->rawrec) = sec;
*pMS2FSDH_FSEC (packer->rawrec) = HO2u (fsec, packer->swapflag);
if (packer->blockette_1001_offset)
{
*pMS2B1001_MICROSECOND (packer->rawrec + packer->blockette_1001_offset) = usec_offset;
}
}
}
if (packer->verbose >= 1)
ms_log (0, "%s: Packed %" PRId64 " samples into %u byte record\n", packer->msr->sid,
samples_packed, reclen_generated);
*record = packer->rawrec;
*reclen = reclen_generated;
packer->packed_samples += samples_packed;
packer->recordcount++;
/* Calculate start time for next record */
if (packer->packed_samples < packer->msr->numsamples)
{
packer->nextstarttime =
ms_sampletime (packer->msr->starttime, packer->packed_samples, packer->msr->samprate);
}
else
{
packer->finished = 1;
}
return 1;
} /* End of msr3_pack_next() */
/** ************************************************************************
* @brief Free packer and resources
*
* Free all memory associated with the ::MS3RecordPacker and set the
* pointer to NULL.
*
* @param[in] packer Pointer to ::MS3RecordPacker pointer
* @param[out] packedsamples Total number of samples packed, returned to caller
*
* @see msr3_pack_init()
* @see msr3_pack_next()
***************************************************************************/
void
msr3_pack_free (MS3RecordPacker **packer, int64_t *packedsamples)
{
if (!packer || !*packer)
return;
lm_pack_state_finish (*packer, packedsamples);
lm_pack_state_free (*packer);
libmseed_memory.free (*packer);
*packer = NULL;
} /* End of msr3_pack_free() */
/***************************************************************************
* Report the total samples packed by a session and end it. The packer's
* rawrec/encoded buffers are retained for reuse by a later
* lm_pack_state_init() call.
***************************************************************************/
void
lm_pack_state_finish (MS3RecordPacker *packer, int64_t *packedsamples)
{
if (!packer)
return;
if (packedsamples)
*packedsamples = packer->packed_samples;
packer->finished = 1;
packer->msr = NULL;
} /* End of lm_pack_state_finish() */
/***************************************************************************
* Release a packer's rawrec/encoded buffers.
***************************************************************************/
void
lm_pack_state_free (MS3RecordPacker *packer)
{
if (!packer)
return;
if (packer->rawrec)
libmseed_memory.free (packer->rawrec);
if (packer->encoded)
libmseed_memory.free (packer->encoded);
packer->rawrec = NULL;
packer->rawrec_size = 0;
packer->encoded = NULL;
packer->encoded_size = 0;
} /* End of lm_pack_state_free() */
/** ************************************************************************
* @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 buffer 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)dataoffset + origdatasize))
{
ms_log (2, "%s: Destination record buffer length (%u) is not large enough for record (%u)\n",
msr->sid, recbuflen, ((uint32_t)dataoffset + 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 @p msr.reclen and @p 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;
/* A NULL extra pointer means no extra headers regardless of extralength */
uint16_t extralength = (msr->extra) ? msr->extralength : 0;
/* 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 (extralength, swapflag);
memcpy (pMS3FSDH_SID (record), msr->sid, sidlength);
if (extralength > 0)
memcpy (record + extraoffset, msr->extra, extralength);
return (MS3FSDH_LENGTH + (int)sidlength + extralength);
} /* End of msr3_pack_header3() */
/** ************************************************************************
* @brief Repack a parsed miniSEED record into a version 2 record.
*
* Pack the parsed header into a version 2 header and copy the raw
* encoded data from the original record. The original record must be
* available at the ::MS3Record.record pointer.
*
* The new record will be the same length as the original record and an
* error will be returned if the repacked record would not fit.
* If the new record is shorter than the original record, the extra space
* will be zeroed.
*
* 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_mseed2 (const MS3Record *msr, char *record, uint32_t recbuflen, int8_t verbose)
{
int headerlen;
uint32_t dataoffset;
uint32_t origdataoffset;
uint32_t origdatasize;
uint32_t totalsize;
uint8_t swapflag;