-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathtracelist.c
More file actions
4154 lines (3597 loc) · 138 KB
/
Copy pathtracelist.c
File metadata and controls
4154 lines (3597 loc) · 138 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
/***************************************************************************
* Routines to handle TraceList and related structures.
*
* 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 <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "internalstate.h"
#include "libmseed.h"
static MS3TraceID *lm_findID_atleast (MS3TraceList *mstl, const char *sid, uint8_t pubversion);
static MS3TraceID *lm_addID (MS3TraceList *mstl, MS3TraceID *id, MS3TraceID **prev);
static MS3TraceSeg *lm_msr2seg (const MS3Record *msr, nstime_t endtime);
static MS3TraceSeg *lm_addmsrtoseg (MS3TraceSeg *seg, const MS3Record *msr, nstime_t endtime,
int8_t whence);
static MS3TraceSeg *lm_addsegtoseg (MS3TraceSeg *seg1, MS3TraceSeg *seg2);
static MS3RecordPtr *lm_add_recordptr (MS3TraceSeg *seg, const MS3Record *msr, nstime_t endtime,
int8_t whence, uint32_t flags);
static void lm_recentseg_touch (LMTraceIDNode *idnode, MS3TraceSeg *seg);
static void lm_recentseg_remove (LMTraceIDNode *idnode, MS3TraceSeg *seg);
static void lm_endbound_fold (LMTraceIDNode *idnode, nstime_t endtime);
static int lm_seg_listorder (const MS3TraceSeg *a, const MS3TraceSeg *b, int *order);
static int lm_scan_recent (LMTraceIDNode *idnode, const MS3Record *msr, nstime_t endtime,
nstime_t nsperiod, nstime_t nstimetol, nstime_t nnstimetol,
double sampratehz, double sampratetol, int8_t autoheal,
MS3TraceSeg **psegbefore, MS3TraceSeg **psegafter,
MS3TraceSeg **pfollowseg);
static void lm_free_segment_memory (MS3TraceSeg *seg, int8_t freeprvtptr);
static int lm_remove_segment (MS3TraceList *mstl, MS3TraceID *id, MS3TraceSeg *seg,
int8_t freeprvtptr);
static void lm_update_id_extent (MS3TraceID *id);
static uint32_t lm_lcg_r (uint64_t *state);
static uint8_t lm_random_height (uint8_t maximum, uint64_t *state);
static nstime_t lm_packed_starttime (const MS3TraceSeg *seg, int64_t packedsamples);
static uint8_t lm_segment_encoding (char sampletype, int8_t encoding);
static int lm_segment_short_of_record (const char *sid, const MS3TraceSeg *seg, int reclen,
int8_t encoding, const char *extra, size_t extralength,
uint32_t flags);
static int lm_pack_scan_range (MS3TraceListPacker *packer, uint32_t flags, size_t extralength,
nstime_t *now, MS3TraceID *start, MS3TraceID *end,
MS3TraceSeg *first_resume_seg, char **record, int32_t *reclen);
/* Test if two sample rates are similar using either specified tolerance (if non-negative) or
* default tolerance */
#define IS_SAMPRATE_SIMILAR(SR1, SR2, SRT) \
((SR1) == (SR2) || ((SRT >= 0.0) ? fabs (SR1 - SR2) <= SRT : MS_ISRATETOLERABLE (SR1, SR2)))
/* Test if a MS3TraceSeg represents time coverage */
#define SEGMENT_HAS_TIME_COVERAGE(seg) ((seg)->samplecnt > 0 && (seg)->samprate != 0.0)
/** ************************************************************************
* @brief Initialize a ::MS3TraceList container
*
* A new ::MS3TraceList is allocated if needed. If the supplied
* ::MS3TraceList is not NULL it will be re-initialized and any
* associated memory will be freed including data at @p prvtptr pointers.
*
* @param[in] mstl ::MS3TraceList to reinitialize or NULL
*
* @returns a pointer to a MS3TraceList struct on success or NULL on error.
*
* @ref MessageOnError - this function logs a message on error
*
* @see mstl3_free()
***************************************************************************/
MS3TraceList *
mstl3_init (MS3TraceList *mstl)
{
if (mstl)
{
mstl3_free (&mstl, 1);
}
mstl = (MS3TraceList *)libmseed_memory.malloc (sizeof (LMTraceListNode));
if (mstl == NULL)
{
ms_log (2, "Cannot allocate memory\n");
return NULL;
}
memset (mstl, 0, sizeof (LMTraceListNode));
/* Seed PRNG with 1, we only need random distribution */
mstl->prngstate = 1;
mstl->traces.height = MSTRACEID_SKIPLIST_HEIGHT;
return mstl;
} /* End of mstl3_init() */
/** ************************************************************************
* @brief Free all memory associated with a ::MS3TraceList
*
* The pointer to the target ::MS3TraceList will be set to NULL.
*
* @param[in] ppmstl Pointer-to-pointer to the target ::MS3TraceList to free
* @param[in] freeprvtptr If true, also free any data at the @p
* prvtptr members of ::MS3TraceID.prvtptr, ::MS3TraceSeg.prvtptr, and
* ::MS3RecordPtr.prvtptr (in ::MS3TraceSeg.recordlist)
***************************************************************************/
void
mstl3_free (MS3TraceList **ppmstl, int8_t freeprvtptr)
{
MS3TraceID *id = NULL;
MS3TraceID *nextid = NULL;
MS3TraceSeg *seg = NULL;
MS3TraceSeg *nextseg = NULL;
if (!ppmstl || !*ppmstl)
return;
/* Free any associated traces */
id = (*ppmstl)->traces.next[0];
while (id)
{
nextid = id->next[0];
/* Free any associated trace segments */
seg = id->first;
while (seg)
{
nextseg = seg->next;
/* Free all memory associated with the segment */
lm_free_segment_memory (seg, freeprvtptr);
seg = nextseg;
}
/* Free private pointer data if present and requested */
if (freeprvtptr && id->prvtptr)
libmseed_memory.free (id->prvtptr);
libmseed_memory.free (id);
id = nextid;
}
libmseed_memory.free (*ppmstl);
*ppmstl = NULL;
return;
} /* End of mstl3_free() */
/** ************************************************************************
* @brief Find matching ::MS3TraceID in a ::MS3TraceList
*
* Return the ::MS3TraceID matching the @p sid in the specified ::MS3TraceList.
*
* If @p prev is not NULL, set pointers to previous entries for the
* expected location of the trace ID. Useful for adding a new ID
* with mstl3_addID(), and should be set to @p NULL otherwise.
*
* @param[in] mstl Pointer to the ::MS3TraceList to search
* @param[in] sid Source ID to search for in the list
* @param[in] pubversion If non-zero, find the entry with this version
* @param[out] prev Pointers to previous entries in expected location or NULL
*
* @returns a pointer to the matching ::MS3TraceID or NULL if not found or error.
***************************************************************************/
MS3TraceID *
mstl3_findID (MS3TraceList *mstl, const char *sid, uint8_t pubversion, MS3TraceID **prev)
{
MS3TraceID *id = NULL;
int level;
int cmp;
if (!mstl || !sid)
{
ms_log (2, "%s(): Required input not defined: 'mstl' or 'sid'\n", __func__);
return NULL;
}
level = MSTRACEID_SKIPLIST_HEIGHT - 1;
/* Search trace ID skip list, starting from the head/sentinel node */
id = &(mstl->traces);
while (id != NULL && level >= 0)
{
if (prev != NULL) /* Track previous entries at each level */
{
prev[level] = id;
}
if (id->next[level] == NULL)
{
level -= 1;
}
else
{
cmp = strcmp (id->next[level]->sid, sid);
/* If source IDs match, check publication if matching requested */
if (!cmp && pubversion && id->next[level]->pubversion != pubversion)
{
cmp = (id->next[level]->pubversion < pubversion) ? -1 : 1;
}
if (cmp == 0) /* Found matching trace ID */
{
return id->next[level];
}
else if (cmp > 0) /* Drop a level */
{
level -= 1;
}
else /* Continue at this level */
{
id = id->next[level];
}
}
}
return NULL;
} /* End of mstl3_findID() */
/***************************************************************************
* Find the first ::MS3TraceID at or after a given (sid, pubversion) key.
*
* Descends the trace ID skip list with the same logic as mstl3_findID(),
* but without an early return on an exact match, so the result is always
* the first entry whose key is greater than or equal to the one requested
* -- even when no entry with that exact key exists, e.g. because it was
* since removed from the list. This resolves a stale resume hint in
* O(log N) without ever dereferencing a freed ::MS3TraceID.
*
* @returns a pointer to the first qualifying ::MS3TraceID or NULL if none do.
***************************************************************************/
static MS3TraceID *
lm_findID_atleast (MS3TraceList *mstl, const char *sid, uint8_t pubversion)
{
MS3TraceID *id;
int level;
int cmp;
id = &(mstl->traces);
level = MSTRACEID_SKIPLIST_HEIGHT - 1;
while (level >= 0)
{
if (id->next[level] == NULL)
{
level -= 1;
continue;
}
cmp = strcmp (id->next[level]->sid, sid);
if (!cmp)
{
if (id->next[level]->pubversion < pubversion)
cmp = -1;
else if (id->next[level]->pubversion > pubversion)
cmp = 1;
}
if (cmp < 0)
id = id->next[level];
else
level -= 1;
}
return id->next[0];
} /* End of lm_findID_atleast() */
/** ************************************************************************
* @brief Add ::MS3TraceID to a ::MS3TraceList
*
* The @p prev array is the list of pointers to previous entries at different
* levels of the skip list. It is common to first search the list using
* mstl3_findID() which returns this list of pointers for use here.
* If this value is NULL mstl3_findID() will be run to find the pointers.
*
* @param[in] mstl Add ID to this ::MS3TraceList
* @param[in] id The ::MS3TraceID to add
* @param[in] prev Pointers to previous entries in expected location, can be NULL
*
* @returns a pointer to the added ::MS3TraceID or NULL on error.
*
* @see mstl3_findID()
***************************************************************************/
MS3TraceID *
mstl3_addID (MS3TraceList *mstl, MS3TraceID *id, MS3TraceID **prev)
{
/* An ID added through this public entry point may not carry the private
* tail this library allocates internally, so disable the state that
* relies on it for the containing list. */
if (mstl)
((LMTraceListNode *)mstl)->foreignid = 1;
return lm_addID (mstl, id, prev);
} /* End of mstl3_addID() */
/* Add a MS3TraceID to a MS3TraceList, see mstl3_addID() for the public entry point. */
static MS3TraceID *
lm_addID (MS3TraceList *mstl, MS3TraceID *id, MS3TraceID **prev)
{
MS3TraceID *local_prev[MSTRACEID_SKIPLIST_HEIGHT] = {NULL};
int level;
if (!mstl || !id)
{
ms_log (2, "%s(): Required input not defined: 'mstl' or 'id'\n", __func__);
return NULL;
}
/* If previous list pointers not supplied, find them */
if (!prev)
{
mstl3_findID (mstl, id->sid, 0, local_prev);
prev = local_prev;
}
/* Set level of new entry to a random level within head height */
id->height = lm_random_height (MSTRACEID_SKIPLIST_HEIGHT, &(mstl->prngstate));
/* Set all pointers above new entry level to NULL */
for (level = MSTRACEID_SKIPLIST_HEIGHT - 1; level > id->height; level--)
{
id->next[level] = NULL;
}
/* Verify all required previous pointers exist before linking anything */
for (level = id->height - 1; level >= 0; level--)
{
if (!prev[level])
{
ms_log (2, "No previous pointer at level %d for adding SID %s\n", level, id->sid);
return NULL;
}
}
/* Connect previous and new ID pointers */
for (level = id->height - 1; level >= 0; level--)
{
id->next[level] = prev[level]->next[level];
prev[level]->next[level] = id;
}
mstl->numtraceids++;
return id;
} /* End of lm_addID() */
/***************************************************************************
* Move a segment into the most-recently-used slot of a trace ID's recent
* set, evicting the least-recently-used entry if the segment was not
* already tracked. An evicted segment's current end time is folded into
* the non-recent end-time bound before it is dropped.
***************************************************************************/
static void
lm_recentseg_touch (LMTraceIDNode *idnode, MS3TraceSeg *seg)
{
MS3TraceSeg *evicted;
int found = -1;
int i;
if (!seg)
return;
for (i = 0; i < LM_RECENTSEGS; i++)
{
if (idnode->recentseg[i] == seg)
{
found = i;
break;
}
}
/* Only the least-recently-used slot is evicted, and only when the
* segment being touched was not already present */
evicted = (found < 0) ? idnode->recentseg[LM_RECENTSEGS - 1] : NULL;
/* Shift entries from the found (or last) slot down to make room at the front */
for (i = (found < 0) ? LM_RECENTSEGS - 1 : found; i > 0; i--)
{
idnode->recentseg[i] = idnode->recentseg[i - 1];
}
idnode->recentseg[0] = seg;
if (evicted)
lm_endbound_fold (idnode, evicted->endtime);
} /* End of lm_recentseg_touch() */
/***************************************************************************
* Remove a segment from a trace ID's recent set, if present, compacting the
* array. The end-time bound is not lowered; it may now overestimate for
* this segment, which only costs search performance.
***************************************************************************/
static void
lm_recentseg_remove (LMTraceIDNode *idnode, MS3TraceSeg *seg)
{
int i, j;
for (i = 0; i < LM_RECENTSEGS; i++)
{
if (idnode->recentseg[i] == seg)
{
for (j = i; j < LM_RECENTSEGS - 1; j++)
idnode->recentseg[j] = idnode->recentseg[j + 1];
idnode->recentseg[LM_RECENTSEGS - 1] = NULL;
break;
}
}
} /* End of lm_recentseg_remove() */
/***************************************************************************
* Raise a trace ID's non-recent end-time bound to cover a known end time.
* The bound only ever grows.
***************************************************************************/
static void
lm_endbound_fold (LMTraceIDNode *idnode, nstime_t endtime)
{
if (endtime > idnode->nonrecentendbound)
idnode->nonrecentendbound = endtime;
} /* End of lm_endbound_fold() */
/***************************************************************************
* Determine the list order of two segments: starttime ascending, endtime
* descending. Segments with fully equal keys are adjacent in the list;
* such ties are resolved by walking a bounded number of hops from 'a' in
* each direction looking for 'b'.
*
* On success returns 1 and sets *order to -1 (a before b), 0 (a is b), or
* 1 (a after b). Returns 0 if the order could not be resolved within the
* walk bound.
***************************************************************************/
static int
lm_seg_listorder (const MS3TraceSeg *a, const MS3TraceSeg *b, int *order)
{
const MS3TraceSeg *walk;
int hops;
if (a == b)
{
*order = 0;
return 1;
}
if (a->starttime != b->starttime)
{
*order = (a->starttime < b->starttime) ? -1 : 1;
return 1;
}
if (a->endtime != b->endtime)
{
*order = (a->endtime > b->endtime) ? -1 : 1;
return 1;
}
for (walk = a->next, hops = 0; walk && hops < LM_RECENTSEGS_MAXWALK; walk = walk->next, hops++)
{
if (walk == b)
{
*order = -1;
return 1;
}
}
for (walk = a->prev, hops = 0; walk && hops < LM_RECENTSEGS_MAXWALK; walk = walk->prev, hops++)
{
if (walk == b)
{
*order = 1;
return 1;
}
}
return 0;
} /* End of lm_seg_listorder() */
/***************************************************************************
* Reproduce the segment-list search of _mstl3_addmsr_impl() using only
* the recent segments of a trace ID. Callable only when every segment not
* in the recent set is provably out of range for segbefore, segafter, and
* the autoheal exact match, and necessarily sorts before the record (see
* the guard at the call site); under that condition the outcome of the
* recent segments alone matches a full scan.
*
* This loop body mirrors the general search in _mstl3_addmsr_impl() and
* must be kept in lockstep with it.
*
* Returns 1 with *psegbefore, *psegafter and *pfollowseg set (any may be
* NULL) when the shortcut applies. Returns 0, with the outputs untouched,
* when the search cannot be resolved from the recent set and the caller
* must fall back to a full scan.
***************************************************************************/
static int
lm_scan_recent (LMTraceIDNode *idnode, const MS3Record *msr, nstime_t endtime, nstime_t nsperiod,
nstime_t nstimetol, nstime_t nnstimetol, double sampratehz, double sampratetol,
int8_t autoheal, MS3TraceSeg **psegbefore, MS3TraceSeg **psegafter,
MS3TraceSeg **pfollowseg)
{
MS3TraceSeg *recent[LM_RECENTSEGS];
MS3TraceSeg *searchseg;
MS3TraceSeg *segbefore = NULL;
MS3TraceSeg *segafter = NULL;
MS3TraceSeg *followseg = NULL;
nstime_t postgap;
nstime_t pregap;
int order;
int count = 0;
int i, j;
/* Collect the tracked recent segments */
for (i = 0; i < LM_RECENTSEGS; i++)
{
if (idnode->recentseg[i])
recent[count++] = idnode->recentseg[i];
}
/* Sort the collected segments into list order; a small insertion sort
* is sufficient for this fixed, small-size array */
for (i = 1; i < count; i++)
{
for (j = i; j > 0; j--)
{
if (!lm_seg_listorder (recent[j - 1], recent[j], &order))
return 0;
if (order <= 0)
break;
searchseg = recent[j - 1];
recent[j - 1] = recent[j];
recent[j] = searchseg;
}
}
/* Identical loop body to the general search in _mstl3_addmsr_impl(),
* run over the recent segments only, in list order */
for (i = 0; i < count; i++)
{
searchseg = recent[i];
/* Done searching when segment starts beyond the record end plus tolerance */
if (searchseg->starttime > endtime + nsperiod + nstimetol)
break;
/* Skip segments with no time coverage, these cannot be extended */
if (!SEGMENT_HAS_TIME_COVERAGE (searchseg))
continue;
/* Done searching if autohealing and record exactly matches a segment */
if (autoheal && msr->starttime == searchseg->starttime && endtime == searchseg->endtime)
{
followseg = searchseg;
break;
}
if (msr->starttime > searchseg->starttime)
followseg = searchseg;
if (!segbefore)
{
postgap = msr->starttime - searchseg->endtime - nsperiod;
if (postgap <= nstimetol && postgap >= nnstimetol &&
IS_SAMPRATE_SIMILAR (sampratehz, searchseg->samprate, sampratetol))
segbefore = searchseg;
}
if (!segafter)
{
pregap = searchseg->starttime - endtime - nsperiod;
if (pregap <= nstimetol && pregap >= nnstimetol &&
IS_SAMPRATE_SIMILAR (sampratehz, searchseg->samprate, sampratetol))
segafter = searchseg;
}
/* Done searching if both before and after segments are found */
if (segbefore && segafter)
break;
/* Done searching if not autohealing and one match found */
else if (!autoheal && (segbefore || segafter))
break;
}
/* If nothing matched, followseg must be the globally latest-starting
* coverage segment before the record, which may be outside the recent
* set: walk backward from the list end, skipping segments that start
* at/after the record (necessarily recent, already considered above) or
* that lack coverage. */
if (!segbefore && !segafter && !followseg)
{
int hops;
searchseg = idnode->id.last;
for (hops = 0; searchseg && hops < LM_RECENTSEGS_MAXWALK; hops++)
{
if (SEGMENT_HAS_TIME_COVERAGE (searchseg) && searchseg->starttime < msr->starttime)
{
followseg = searchseg;
break;
}
searchseg = searchseg->prev;
}
/* Walk bound exceeded without resolving followseg, refuse the shortcut */
if (!followseg && searchseg)
return 0;
}
*psegbefore = segbefore;
*psegafter = segafter;
*pfollowseg = followseg;
return 1;
} /* End of lm_scan_recent() */
/***************************************************************************
* Implementation of MS3TraceList addition functions
*
* @see mstl3_addmsr()
* @see mstl3_addmsr_recordptr()
***************************************************************************/
MS3TraceSeg *
_mstl3_addmsr_impl (MS3TraceList *mstl, const MS3Record *msr, MS3RecordPtr **pprecptr,
int8_t splitversion, int8_t autoheal, uint32_t flags,
const MS3Tolerance *tolerance)
{
MS3TraceID *id = NULL;
MS3TraceID *previd[MSTRACEID_SKIPLIST_HEIGHT] = {NULL};
MS3TraceSeg *seg = NULL;
MS3TraceSeg *searchseg = NULL;
MS3TraceSeg *segbefore = NULL;
MS3TraceSeg *segafter = NULL;
MS3TraceSeg *followseg = NULL;
nstime_t endtime;
nstime_t pregap;
nstime_t postgap;
nstime_t lastgap;
nstime_t firstgap;
nstime_t nsperiod;
nstime_t nstimetol = 0;
nstime_t nnstimetol = 0;
double sampratehz;
double sampratetol = -1.0;
if (!mstl || !msr)
{
ms_log (2, "%s(): Required input not defined: 'mstl' or 'msr'\n", __func__);
return NULL;
}
/* Calculate end time for MS3Record */
if ((endtime = msr3_endtime (msr)) == NSTERROR)
{
ms_log (2, "Error calculating record end time\n");
return NULL;
}
/* If splitversion is true and MSF_SPLITISVERSION is set in flags, use splitversion
* as the version, otherwise use msr->pubversion */
uint8_t pubversion = (flags & MSF_SPLITISVERSION) ? splitversion : msr->pubversion;
/* Search for matching trace ID */
id = mstl3_findID (mstl, msr->sid, (splitversion) ? pubversion : 0, previd);
/* If no matching ID was found create new MS3TraceID and MS3TraceSeg entries */
if (!id)
{
if (!(id = (MS3TraceID *)libmseed_memory.malloc (sizeof (LMTraceIDNode))))
{
ms_log (2, "Error allocating memory\n");
return NULL;
}
memset (id, 0, sizeof (LMTraceIDNode));
/* Populate MS3TraceID */
memcpy (id->sid, msr->sid, sizeof (id->sid));
id->pubversion = pubversion;
id->earliest = msr->starttime;
id->latest = endtime;
id->numsegments = 1;
/* End-time bound starts below any possible end time, recent set starts empty */
((LMTraceIDNode *)id)->nonrecentendbound = INT64_MIN;
if (!(seg = lm_msr2seg (msr, endtime)))
{
libmseed_memory.free (id);
return NULL;
}
id->first = id->last = seg;
/* Add MS3RecordPtr if requested */
if (pprecptr && !(*pprecptr = lm_add_recordptr (seg, msr, endtime, 1, flags)))
{
lm_free_segment_memory (seg, 0);
libmseed_memory.free (id);
return NULL;
}
/* Add new MS3TraceID to MS3TraceList */
if (lm_addID (mstl, id, previd) == NULL)
{
ms_log (2, "Error adding new ID to trace list\n");
lm_free_segment_memory (seg, 0);
libmseed_memory.free (id);
return NULL;
}
}
/* Add data coverage to the matching MS3TraceID */
else
{
/* Calculate nanosecond sample period */
nsperiod = msr3_nsperiod (msr);
/* Calculate high-precision time tolerance */
if (tolerance && tolerance->time)
{
double timetol = tolerance->time (msr);
if (timetol < 0.0)
{
ms_log (1, "%s: Ignoring negative time tolerance (%g), using default\n", msr->sid, timetol);
nstimetol = (nstime_t)(0.5 * nsperiod);
}
else
nstimetol = (nstime_t)(NSTMODULUS * timetol);
}
else
nstimetol = (nstime_t)(0.5 * nsperiod); /* Default time tolerance is 1/2 sample period */
nnstimetol = (nstimetol) ? -nstimetol : 0;
/* Calculate sample rate tolerance */
if (tolerance && tolerance->samprate)
{
sampratetol = tolerance->samprate (msr);
if (sampratetol < 0.0)
{
ms_log (1, "%s: Ignoring negative sample rate tolerance (%g), using default\n", msr->sid,
sampratetol);
sampratetol = -1.0; /* Restore default sentinel */
}
}
sampratehz = msr3_sampratehz (msr);
/* last/firstgap are negative when the record overlaps the trace
* segment and positive when there is a time gap. */
/* Gap relative to the last segment */
lastgap = msr->starttime - id->last->endtime - nsperiod;
/* Gap relative to the first segment */
firstgap = id->first->starttime - endtime - nsperiod;
/* Search first for the simple scenarios in order of likelihood:
* - Record fits at end of last segment
* - Record fits after all coverage
* - Record fits before all coverage
* - Record fits at beginning of first segment
*
* If none of those scenarios are true search the complete segment list.
*/
/* Record coverage fits at end of last segment */
if (lastgap <= nstimetol && lastgap >= nnstimetol &&
IS_SAMPRATE_SIMILAR (sampratehz, id->last->samprate, sampratetol) &&
SEGMENT_HAS_TIME_COVERAGE (id->last))
{
if (!lm_addmsrtoseg (id->last, msr, endtime, 1))
return NULL;
seg = id->last;
if (endtime > id->latest)
id->latest = endtime;
/* Add MS3RecordPtr if requested */
if (pprecptr && !(*pprecptr = lm_add_recordptr (seg, msr, endtime, 1, flags)))
{
/* seg's end time was already extended above; keep the end-time bound valid */
if (!((LMTraceListNode *)mstl)->foreignid)
lm_endbound_fold ((LMTraceIDNode *)id, seg->endtime);
return NULL;
}
}
/* Record coverage is after all other coverage */
else if ((msr->starttime - nsperiod - nstimetol) > id->latest)
{
if (!(seg = lm_msr2seg (msr, endtime)))
return NULL;
/* Add to end of list */
id->last->next = seg;
seg->prev = id->last;
id->last = seg;
id->numsegments++;
if (endtime > id->latest)
id->latest = endtime;
/* Add MS3RecordPtr if requested */
if (pprecptr && !(*pprecptr = lm_add_recordptr (seg, msr, endtime, 0, flags)))
{
/* seg is already linked into the list; keep the end-time bound valid */
if (!((LMTraceListNode *)mstl)->foreignid)
lm_endbound_fold ((LMTraceIDNode *)id, seg->endtime);
return NULL;
}
}
/* Record coverage is before all other coverage */
else if ((endtime + nsperiod + nstimetol) < id->earliest)
{
if (!(seg = lm_msr2seg (msr, endtime)))
return NULL;
/* Add to beginning of list */
id->first->prev = seg;
seg->next = id->first;
id->first = seg;
id->numsegments++;
if (msr->starttime < id->earliest)
id->earliest = msr->starttime;
/* Add MS3RecordPtr if requested */
if (pprecptr && !(*pprecptr = lm_add_recordptr (seg, msr, endtime, 0, flags)))
{
/* seg is already linked into the list; keep the end-time bound valid */
if (!((LMTraceListNode *)mstl)->foreignid)
lm_endbound_fold ((LMTraceIDNode *)id, seg->endtime);
return NULL;
}
}
/* Record coverage fits at beginning of first segment */
else if (firstgap <= nstimetol && firstgap >= nnstimetol &&
IS_SAMPRATE_SIMILAR (sampratehz, id->first->samprate, sampratetol) &&
SEGMENT_HAS_TIME_COVERAGE (id->first))
{
if (!lm_addmsrtoseg (id->first, msr, endtime, 2))
return NULL;
seg = id->first;
if (msr->starttime < id->earliest)
id->earliest = msr->starttime;
/* Add MS3RecordPtr if requested */
if (pprecptr && !(*pprecptr = lm_add_recordptr (seg, msr, endtime, 2, flags)))
return NULL;
}
/* Search complete segment list for matches */
else
{
/* This search finds the following values if they exist: */
segbefore = NULL; /* The first segment end that matches the record start (within tolerance) */
segafter = NULL; /* The first segment start that matches the record end (within tolerance) */
followseg = NULL; /* The segment with latest start time before the record start */
/* A zero rate record cannot match segbefore/segafter without an explicit
* tolerance, so only followseg is needed: search backward from the last segment. */
if (sampratehz == 0.0 && sampratetol < 0.0)
{
searchseg = id->last;
while (searchseg)
{
/* Skip segments with no time coverage, these cannot be extended */
if (!SEGMENT_HAS_TIME_COVERAGE (searchseg))
{
searchseg = searchseg->prev;
continue;
}
/* Done searching if autohealing and record exactly matches a segment.
*
* Rationale: autohealing would have combined this segment
* with another if that were possible, so this record will
* also not fit with any other segment. */
if (autoheal && msr->starttime == searchseg->starttime && endtime == searchseg->endtime)
{
followseg = searchseg;
break;
}
/* Done searching at the first (i.e. latest) segment starting before the record */
if (searchseg->starttime < msr->starttime)
{
followseg = searchseg;
break;
}
searchseg = searchseg->prev;
}
}
/* If every segment outside the recent set is provably too old to match,
* the recent set alone determines the result of the search below. */
else if (!((LMTraceListNode *)mstl)->foreignid &&
(msr->starttime - nsperiod - nstimetol) > ((LMTraceIDNode *)id)->nonrecentendbound &&
lm_scan_recent ((LMTraceIDNode *)id, msr, endtime, nsperiod, nstimetol, nnstimetol,
sampratehz, sampratetol, autoheal, &segbefore, &segafter,
&followseg))
{
/* segbefore, segafter and followseg set by lm_scan_recent() */
}
else
{
searchseg = id->first;
while (searchseg)
{
/* Done searching when segment starts beyond the record end plus tolerance */
if (searchseg->starttime > endtime + nsperiod + nstimetol)
break;
/* Skip segments with no time coverage, these cannot be extended */
if (!SEGMENT_HAS_TIME_COVERAGE (searchseg))
{
searchseg = searchseg->next;
continue;
}
/* Done searching if autohealing and record exactly matches a segment.
*
* Rationale: autohealing would have combined this segment
* with another if that were possible, so this record will
* also not fit with any other segment. */
if (autoheal && msr->starttime == searchseg->starttime && endtime == searchseg->endtime)
{
followseg = searchseg;
break;
}
if (msr->starttime > searchseg->starttime)
followseg = searchseg;
if (!segbefore)
{
postgap = msr->starttime - searchseg->endtime - nsperiod;
if (postgap <= nstimetol && postgap >= nnstimetol &&
IS_SAMPRATE_SIMILAR (sampratehz, searchseg->samprate, sampratetol))
segbefore = searchseg;
}
if (!segafter)
{
pregap = searchseg->starttime - endtime - nsperiod;
if (pregap <= nstimetol && pregap >= nnstimetol &&
IS_SAMPRATE_SIMILAR (sampratehz, searchseg->samprate, sampratetol))
segafter = searchseg;
}
/* Done searching if both before and after segments are found */
if (segbefore && segafter)
break;
/* Done searching if not autohealing and one match found */
else if (!autoheal && (segbefore || segafter))
break;
searchseg = searchseg->next;
} /* Done looping through segments */
}
/* Add MS3Record coverage to end of segment before */
if (segbefore)
{
if (!lm_addmsrtoseg (segbefore, msr, endtime, 1))
{
return NULL;
}
/* Add MS3RecordPtr if requested */
if (pprecptr && !(*pprecptr = lm_add_recordptr (segbefore, msr, endtime, 1, flags)))