-
Notifications
You must be signed in to change notification settings - Fork 78
/
readsb.c
3177 lines (2723 loc) · 107 KB
/
readsb.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
// Part of readsb, a Mode-S/ADSB/TIS message decoder.
//
// readsb.c: main program & miscellany
//
// Copyright (c) 2019 Michael Wolf <[email protected]>
//
// This code is based on a detached fork of dump1090-fa.
//
// Copyright (c) 2014-2016 Oliver Jowett <[email protected]>
//
// This file is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This file is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// This file incorporates work covered by the following copyright and
// license:
//
// Copyright (C) 2012 by Salvatore Sanfilippo <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <sched.h>
#include "readsb.h"
#include "help.h"
#include <sys/time.h>
#include <sys/resource.h>
struct _Modes Modes;
struct _Threads Threads;
static void loadReplaceState();
static void checkReplaceState();
static void backgroundTasks(int64_t now);
static error_t parse_opt(int key, char *arg, struct argp_state *state);
//
// ============================= Utility functions ==========================
//
static void cleanup_and_exit(int code);
void setExit(int arg) {
// Signal to main loop that program is exiting soon, delay depends on cli arguments
// see main loop for details
Modes.exitSoon = arg;
uint64_t one = 1;
ssize_t res = write(Modes.exitSoonEventfd, &one, sizeof(one));
MODES_NOTUSED(res);
}
static void exitHandler(int sig) {
setExit(1);
char *sigX = NULL;
if (sig == SIGTERM) { sigX = "SIGTERM"; }
if (sig == SIGINT) { sigX = "SIGINT"; }
if (sig == SIGQUIT) { sigX = "SIGQUIT"; }
if (sig == SIGHUP) { sigX = "SIGHUP"; }
log_with_timestamp("Caught %s, shutting down...", sigX);
}
void receiverPositionChanged(float lat, float lon, float alt) {
log_with_timestamp("Autodetected receiver location: %.5f, %.5f at %.0fm AMSL", lat, lon, alt);
if (Modes.json_dir) {
free(writeJsonToFile(Modes.json_dir, "receiver.json", generateReceiverJson()).buffer); // location changed
}
}
//
// =============================== Initialization ===========================
//
static void configSetDefaults(void) {
// Default everything to zero/NULL
memset(&Modes, 0, sizeof (Modes));
for (int i = 0; i < 256; i++) {
Modes.threadNumber[i] = i;
}
// Now initialise things that should not be 0/NULL to their defaults
Modes.gain = MODES_MAX_GAIN;
Modes.freq = MODES_DEFAULT_FREQ;
Modes.check_crc = 1;
Modes.net_heartbeat_interval = MODES_NET_HEARTBEAT_INTERVAL;
//Modes.db_file = strdup("/usr/local/share/tar1090/git-db/aircraft.csv.gz");
Modes.db_file = NULL;
Modes.latString = strdup("");
Modes.lonString = strdup("");
Modes.net_input_raw_ports = strdup("0");
Modes.net_output_raw_ports = strdup("0");
Modes.net_output_uat_replay_ports = strdup("0");
Modes.net_input_uat_ports = strdup("0");
Modes.net_output_sbs_ports = strdup("0");
Modes.net_input_sbs_ports = strdup("0");
Modes.net_input_beast_ports = strdup("0");
Modes.net_input_planefinder_ports = strdup("0");
Modes.net_output_beast_ports = strdup("0");
Modes.net_output_beast_reduce_ports = strdup("0");
Modes.net_output_beast_reduce_interval = 250;
Modes.beast_reduce_filter_distance = -1;
Modes.beast_reduce_filter_altitude = -1;
Modes.net_output_vrs_ports = strdup("0");
Modes.net_output_vrs_interval = 5 * SECONDS;
Modes.net_output_json_ports = strdup("0");
Modes.net_output_api_ports = strdup("0");
Modes.net_input_jaero_ports = strdup("0");
Modes.net_output_jaero_ports = strdup("0");
Modes.net_connector_delay = 30 * 1000;
Modes.interactive_display_ttl = MODES_INTERACTIVE_DISPLAY_TTL;
Modes.json_interval = 1000;
Modes.json_location_accuracy = 2;
Modes.maxRange = 1852 * 450; // 450 nmi default max range
Modes.nfix_crc = 1;
Modes.biastee = 0;
Modes.position_persistence = 4;
Modes.net_sndbuf_size = 2; // Default to 256 kB SNDBUF / RCVBUF
Modes.net_output_flush_size = 1280; // Default to 1280 Bytes
Modes.net_output_flush_interval = 50; // Default to 50 ms
Modes.net_output_flush_interval_beast_reduce = -1; // default to net_output_flush_interval after config parse if not configured
Modes.netReceiverId = 0;
Modes.netIngest = 0;
Modes.json_trace_interval = 20 * 1000;
Modes.state_write_interval = 1 * HOURS;
Modes.heatmap_current_interval = -15;
Modes.heatmap_interval = 60 * SECONDS;
Modes.json_reliable = -13;
Modes.acasFD1 = -1; // set to -1 so it's clear we don't have that fd
Modes.acasFD2 = -1; // set to -1 so it's clear we don't have that fd
Modes.sbsOverrideSquawk = -1;
Modes.fUserAlt = -2e6;
Modes.enable_zstd = 1;
Modes.currentTask = "unset";
Modes.joinTimeout = 30 * SECONDS;
Modes.state_chunk_size = 12 * 1024 * 1024;
Modes.state_chunk_size_read = Modes.state_chunk_size;
Modes.decodeThreads = 1;
Modes.filterDF = 0;
Modes.filterDFbitset = 0;
Modes.cpr_focus = BADDR;
Modes.leg_focus = BADDR;
Modes.trace_focus = BADDR;
Modes.show_only = BADDR;
Modes.outline_json = 1; // enable by default
Modes.range_outline_duration = 24 * HOURS;
//Modes.receiver_focus = 0x123456;
//
Modes.trackExpireJaero = TRACK_EXPIRE_JAERO;
Modes.fixDF = 1;
sdrInitConfig();
reset_stats(&Modes.stats_current);
for (int i = 0; i < 90; ++i) {
reset_stats(&Modes.stats_10[i]);
}
//receiverTest();
struct rlimit limits;
int res = getrlimit(RLIMIT_NOFILE, &limits);
if (res != 0) {
fprintf(stderr, "WARNING: getrlimit(RLIMIT_NOFILE, &limits) returned the following error: \"%s\". Assuming bad limit query function, using up to 64 file descriptors \n",
strerror(errno));
Modes.max_fds = 64;
} else {
uint64_t limit = limits.rlim_cur;
// check limit for unreasonableness
if (limit < (uint64_t) 64) {
fprintf(stderr, "WARNING: getrlimit(RLIMIT_NOFILE, &limits) returned less than 64 fds for readsb to work with. Assuming bad limit query function, using up to 64 file descriptors. Fix RLIMIT!\n");
Modes.max_fds = 64;
} else if (limits.rlim_cur == RLIM_INFINITY) {
Modes.max_fds = INT32_MAX;
} else if (limit > (uint64_t) INT32_MAX) {
fprintf(stderr, "WARNING: getrlimit(RLIMIT_NOFILE, &limits) returned more than INT32_MAX ... This is just weird.\n");
Modes.max_fds = INT32_MAX;
} else {
Modes.max_fds = (int) limit;
}
}
Modes.max_fds -= 32; // reserve some fds for things we don't account for later like json writing.
// this is an high estimate ... if ppl run out of fds for other stuff they should up rlimit
Modes.sdr_buf_size = 16 * 16 * 1024;
// in seconds, default to 1 hour
Modes.dump_interval = 60 * 60;
Modes.ping_reduce = PING_REDUCE;
Modes.ping_reject = PING_REJECT;
Modes.binCraftVersion = 20240218;
Modes.messageRateMult = 1.0f;
Modes.apiShutdownDelay = 0 * SECONDS;
// default this on
Modes.enableAcasCsv = 1;
Modes.enableAcasJson = 1;
}
//
//=========================================================================
//
static void modesInit(void) {
int64_t now = mstime();
Modes.next_stats_update = roundSeconds(10, 5, now + 10 * SECONDS);
Modes.next_stats_display = now + Modes.stats_display_interval;
pthread_mutex_init(&Modes.traceDebugMutex, NULL);
pthread_mutex_init(&Modes.hungTimerMutex, NULL);
pthread_mutex_init(&Modes.sdrControlMutex, NULL);
threadInit(&Threads.reader, "reader");
threadInit(&Threads.upkeep, "upkeep");
threadInit(&Threads.decode, "decode");
threadInit(&Threads.json, "json");
threadInit(&Threads.globeJson, "globeJson");
threadInit(&Threads.globeBin, "globeBin");
threadInit(&Threads.misc, "misc");
threadInit(&Threads.apiUpdate, "apiUpdate");
if (Modes.json_globe_index || Modes.netReceiverId || AIRCRAFT_HASH_BITS > 16) {
// to keep decoding and the other threads working well, don't use all available processors
Modes.allPoolSize = imax(1, Modes.num_procs);
} else {
Modes.allPoolSize = 1;
}
Modes.allTasks = allocate_task_group(2 * Modes.allPoolSize);
Modes.allPool = threadpool_create(Modes.allPoolSize, 4);
for (int i = 0; i <= GLOBE_MAX_INDEX; i++) {
ca_init(&Modes.globeLists[i]);
}
ca_init(&Modes.aircraftActive);
geomag_init();
Modes.sample_rate = (double)2400000.0;
// Allocate the various buffers used by Modes
Modes.trailing_samples = (unsigned)((MODES_PREAMBLE_US + MODES_LONG_MSG_BITS + 16) * 1e-6 * Modes.sample_rate);
if (!Modes.net_only) {
for (int i = 0; i < MODES_MAG_BUFFERS; ++i) {
size_t alloc = (Modes.sdr_buf_samples + Modes.trailing_samples) * sizeof (uint16_t);
if ((Modes.mag_buffers[i].data = cmalloc(alloc)) == NULL) {
fprintf(stderr, "Out of memory allocating magnitude buffer.\n");
exit(1);
}
memset(Modes.mag_buffers[i].data, 0, alloc);
Modes.mag_buffers[i].length = 0;
Modes.mag_buffers[i].dropped = 0;
Modes.mag_buffers[i].sampleTimestamp = 0;
}
}
// Prepare error correction tables
modesChecksumInit(Modes.nfix_crc);
icaoFilterInit();
modeACInit();
icaoFilterAdd(Modes.show_only);
init_globe_index();
quickInit();
}
static void lockThreads() {
for (int i = 0; i < Modes.lockThreadsCount; i++) {
//fprintf(stderr, "locking %s\n", Modes.lockThreads[i]->name);
Modes.currentTask = Modes.lockThreads[i]->name;
pthread_mutex_lock(&Modes.lockThreads[i]->mutex);
}
}
static void unlockThreads() {
for (int i = Modes.lockThreadsCount - 1; i >= 0; i--) {
//fprintf(stderr, "unlocking %s\n", Modes.lockThreads[i]->name);
pthread_mutex_unlock(&Modes.lockThreads[i]->mutex);
}
}
static int64_t ms_until_priority() {
int64_t now = mstime();
int64_t mono = mono_milli_seconds();
int64_t ms_until_run = imin(
Modes.next_stats_update - now,
Modes.next_remove_stale - mono
);
if (Modes.replace_state_inhibit_traces_until) {
if (mono > Modes.replace_state_inhibit_traces_until) {
Modes.replace_state_inhibit_traces_until = 0;
} else if (ms_until_run > 100) {
ms_until_run = 80;
}
}
if (ms_until_run > 0 && Modes.replace_state_blob) {
ms_until_run = 0;
}
return ms_until_run;
}
// function to check if priorityTasksRun() needs to run
int priorityTasksPending() {
if (ms_until_priority() <= 0) {
return 1; // something to do
} else {
return 0; // nothing to do
}
}
//
// Entry point for periodic updates
//
void priorityTasksRun() {
if (0) {
int64_t now = mstime();
time_t nowTime = floor(now / 1000.0);
struct tm local;
gmtime_r(&nowTime, &local);
char timebuf[512];
strftime(timebuf, 128, "%T", &local);
printf("priorityTasksRun: utcTime: %s.%03lld epoch: %.3f\n", timebuf, (long long) now % 1000, now / 1000.0);
}
pthread_mutex_lock(&Modes.hungTimerMutex);
startWatch(&Modes.hungTimer1);
pthread_mutex_unlock(&Modes.hungTimerMutex);
Modes.currentTask = "priorityTasks_start";
// stop all threads so we can remove aircraft from the list.
// adding aircraft does not need to be done with locking:
// the worst case is that the newly added aircraft is skipped as it's not yet
// in the cache used by the json threads.
Modes.currentTask = "locking";
lockThreads();
Modes.currentTask = "locked";
int64_t now = mstime();
int64_t mono = mono_milli_seconds();
int removed_stale = 0;
static int64_t last_periodic_mono;
int64_t periodic_interval = mono - last_periodic_mono;
if (periodic_interval > 5 * SECONDS && periodic_interval < 9999 * HOURS && last_periodic_mono && !(Modes.syntethic_now_suppress_errors && Modes.synthetic_now)) {
fprintf(stderr, "<3> priorityTasksRun didn't run for %.1f seconds!\n", periodic_interval / 1000.0);
}
last_periodic_mono = mono;
struct timespec watch;
startWatch(&watch);
struct timespec start_time;
start_monotonic_timing(&start_time);
struct timespec before = threadpool_get_cumulative_thread_time(Modes.allPool);
if (Modes.replace_state_blob) {
loadReplaceState();
checkReplaceState();
}
// finish db update under lock
if (dbFinishUpdate()) {
// don't do trackRemoveStale at the same time as dbFinishUpdate
} else if (mono >= Modes.next_remove_stale) {
pthread_mutex_lock(&Modes.hungTimerMutex);
startWatch(&Modes.hungTimer2);
pthread_mutex_unlock(&Modes.hungTimerMutex);
Modes.currentTask = "trackRemoveStale";
trackRemoveStale(now);
traceDelete();
int64_t interval = mono - Modes.next_remove_stale;
if (interval > 5 * SECONDS && interval < 9999 * HOURS && Modes.next_remove_stale && !(Modes.syntethic_now_suppress_errors && Modes.synthetic_now)) {
fprintf(stderr, "<3> removeStale didn't run for %.1f seconds!\n", interval / 1000.0);
}
Modes.next_remove_stale = mono + REMOVE_STALE_INTERVAL;
removed_stale = 1;
}
int64_t elapsed1 = lapWatch(&watch);
if (now >= Modes.next_stats_update) {
Modes.updateStats = 1;
}
if (Modes.updateStats) {
Modes.currentTask = "statsUpdate";
statsUpdate(now); // needs to happen under lock
}
int64_t elapsed2 = lapWatch(&watch);
Modes.currentTask = "unlocking";
unlockThreads();
Modes.currentTask = "unlocked";
static int64_t antiSpam;
if (0 || (Modes.debug_removeStaleDuration) || ((elapsed1 > 150 || elapsed2 > 150) && mono > antiSpam + 30 * SECONDS)) {
fprintf(stderr, "<3>High load: removeStale took %"PRIi64"/%"PRIi64" ms! stats: %d (suppressing for 30 seconds)\n", elapsed1, elapsed2, Modes.updateStats);
antiSpam = mono;
}
//fprintf(stderr, "running for %ld ms\n", getUptime());
//fprintf(stderr, "removeStale took %"PRIu64" ms, running for %ld ms\n", elapsed, getUptime());
if (Modes.updateStats) {
Modes.currentTask = "statsReset";
statsResetCount();
int64_t now = mstime();
Modes.currentTask = "statsCount";
statsCountAircraft(now);
Modes.currentTask = "statsProcess";
statsProcess(now);
Modes.updateStats = 0;
if (Modes.json_dir) {
free(writeJsonToFile(Modes.json_dir, "status.json", generateStatusJson(now)).buffer);
free(writeJsonToFile(Modes.json_dir, "status.prom", generateStatusProm(now)).buffer);
}
}
end_monotonic_timing(&start_time, &Modes.stats_current.remove_stale_cpu);
if (removed_stale) {
struct timespec after = threadpool_get_cumulative_thread_time(Modes.allPool);
timespec_add_elapsed(&before, &after, &Modes.stats_current.remove_stale_cpu);
}
Modes.currentTask = "priorityTasks_end";
}
//
//=========================================================================
//
// We read data using a thread, so the main thread only handles decoding
// without caring about data acquisition
//
static void *readerEntryPoint(void *arg) {
MODES_NOTUSED(arg);
srandom(get_seed());
if (!sdrOpen()) {
Modes.sdrOpenFailed = 1;
setExit(2); // unexpected exit
log_with_timestamp("sdrOpen() failed, exiting!");
return NULL;
}
setPriorityPthread();
if (sdrHasRun()) {
sdrRun();
// Wake the main thread (if it's still waiting)
if (!Modes.exit)
setExit(2); // unexpected exit
} else {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
pthread_mutex_lock(&Threads.reader.mutex);
while (!Modes.exit) {
threadTimedWait(&Threads.reader, &ts, 15 * SECONDS);
}
pthread_mutex_unlock(&Threads.reader.mutex);
}
sdrClose();
return NULL;
}
static void *jsonEntryPoint(void *arg) {
MODES_NOTUSED(arg);
srandom(get_seed());
// set this thread low priority
setLowestPriorityPthread();
int64_t next_history = mstime();
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
pthread_mutex_lock(&Threads.json.mutex);
threadpool_buffer_t pass_buffer = { 0 };
threadpool_buffer_t zstd_buffer = { 0 };
ZSTD_CCtx* cctx = NULL;
if (Modes.enable_zstd) {
//if (Modes.debug_zstd) { fprintf(stderr, "calling ZSTD_createCCtx()\n"); }
cctx = ZSTD_createCCtx();
//if (Modes.debug_zstd) { fprintf(stderr, "ZSTD_createCCtx() returned %p\n", cctx); }
}
while (!Modes.exit) {
struct timespec start_time;
start_cpu_timing(&start_time);
int64_t now = mstime();
// old direct creation, slower when creating json for an aircraft more than once
//struct char_buffer cb = generateAircraftJson(0);
if (Modes.onlyBin < 2) {
// new way: use the apiBuffer of json fragments
struct char_buffer cb = apiGenerateAircraftJson(&pass_buffer);
if (Modes.json_gzip) {
writeJsonToGzip(Modes.json_dir, "aircraft.json.gz", cb, 2);
}
writeJsonToFile(Modes.json_dir, "aircraft.json", cb);
if ((Modes.legacy_history || ((ALL_JSON) && Modes.onlyBin < 2)) && now >= next_history) {
char filebuf[PATH_MAX];
snprintf(filebuf, PATH_MAX, "history_%d.json", Modes.json_aircraft_history_next);
writeJsonToFile(Modes.json_dir, filebuf, cb);
if (!Modes.json_aircraft_history_full) {
free(writeJsonToFile(Modes.json_dir, "receiver.json", generateReceiverJson()).buffer); // number of history entries changed
if (Modes.json_aircraft_history_next == HISTORY_SIZE - 1)
Modes.json_aircraft_history_full = 1;
}
Modes.json_aircraft_history_next = (Modes.json_aircraft_history_next + 1) % HISTORY_SIZE;
next_history = now + HISTORY_INTERVAL;
}
}
if (Modes.debug_recent) {
struct char_buffer cb = generateAircraftJson(1 * SECONDS);
writeJsonToFile(Modes.json_dir, "aircraft_recent.json", cb);
sfree(cb.buffer);
}
struct char_buffer cb3 = generateAircraftBin(&pass_buffer);
if (Modes.enableBinGz) {
writeJsonToGzip(Modes.json_dir, "aircraft.binCraft", cb3, 1);
}
//fprintf(stderr, "uncompressed size %ld\n", (long) cb3.len);
if (Modes.enable_zstd) {
writeJsonToFile(Modes.json_dir, "aircraft.binCraft.zst", generateZstd(cctx, &zstd_buffer, cb3, 1));
}
if (Modes.json_globe_index) {
struct char_buffer cb2 = generateGlobeBin(-1, 1, &pass_buffer);
if (Modes.enableBinGz) {
writeJsonToGzip(Modes.json_dir, "globeMil_42777.binCraft", cb2, 1);
}
if (Modes.enable_zstd) {
writeJsonToFile(Modes.json_dir, "globeMil_42777.binCraft.zst", ident(generateZstd(cctx, &zstd_buffer, cb2, 1)));
}
}
end_cpu_timing(&start_time, &Modes.stats_current.aircraft_json_cpu);
//fprintTimePrecise(stderr, mstime());
//fprintf(stderr, " wrote --write-json-every stuff to --write-json \n");
// we should exit this wait early due to a cond_signal from api.c
threadTimedWait(&Threads.json, &ts, Modes.json_interval * 3);
}
ZSTD_freeCCtx(cctx);
free_threadpool_buffer(&zstd_buffer);
free_threadpool_buffer(&pass_buffer);
pthread_mutex_unlock(&Threads.json.mutex);
return NULL;
}
static void *globeJsonEntryPoint(void *arg) {
MODES_NOTUSED(arg);
srandom(get_seed());
// set this thread low priority
setLowestPriorityPthread();
if (Modes.onlyBin > 0)
return NULL;
pthread_mutex_lock(&Threads.globeJson.mutex);
threadpool_buffer_t pass_buffer = { 0 };
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
while (!Modes.exit) {
struct timespec start_time;
start_cpu_timing(&start_time);
for (int j = 0; j <= Modes.json_globe_indexes_len; j++) {
int index = Modes.json_globe_indexes[j];
char filename[32];
snprintf(filename, 31, "globe_%04d.json", index);
struct char_buffer cb = apiGenerateGlobeJson(index, &pass_buffer);
writeJsonToGzip(Modes.json_dir, filename, cb, 1);
}
end_cpu_timing(&start_time, &Modes.stats_current.globe_json_cpu);
// we should exit this wait early due to a cond_signal from api.c
threadTimedWait(&Threads.globeJson, &ts, Modes.json_interval * 3);
}
free_threadpool_buffer(&pass_buffer);
pthread_mutex_unlock(&Threads.globeJson.mutex);
return NULL;
}
static void *globeBinEntryPoint(void *arg) {
MODES_NOTUSED(arg);
srandom(get_seed());
// set this thread low priority
setLowestPriorityPthread();
int part = 0;
int n_parts = 8; // power of 2
int64_t sleep_ms = Modes.json_interval / n_parts;
pthread_mutex_lock(&Threads.globeBin.mutex);
threadpool_buffer_t pass_buffer = { 0 };
threadpool_buffer_t zstd_buffer = { 0 };
ZSTD_CCtx* cctx = NULL;
if (Modes.enable_zstd) {
cctx = ZSTD_createCCtx();
}
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
while (!Modes.exit) {
char filename[32];
struct timespec start_time;
start_cpu_timing(&start_time);
for (int j = 0; j < Modes.json_globe_indexes_len; j++) {
if (j % n_parts != part)
continue;
int index = Modes.json_globe_indexes[j];
struct char_buffer cb2 = generateGlobeBin(index, 0, &pass_buffer);
if (Modes.enableBinGz) {
snprintf(filename, 31, "globe_%04d.binCraft", index);
writeJsonToGzip(Modes.json_dir, filename, cb2, 1);
}
if (Modes.enable_zstd) {
snprintf(filename, 31, "globe_%04d.binCraft.zst", index);
writeJsonToFile(Modes.json_dir, filename, ident(generateZstd(cctx, &zstd_buffer, cb2, 1)));
}
struct char_buffer cb3 = generateGlobeBin(index, 1, &pass_buffer);
if (Modes.enableBinGz) {
snprintf(filename, 31, "globeMil_%04d.binCraft", index);
writeJsonToGzip(Modes.json_dir, filename, cb3, 1);
}
if (Modes.enable_zstd) {
snprintf(filename, 31, "globeMil_%04d.binCraft.zst", index);
writeJsonToFile(Modes.json_dir, filename, ident(generateZstd(cctx, &zstd_buffer, cb3, 1)));
}
}
part++;
part %= n_parts;
end_cpu_timing(&start_time, &Modes.stats_current.bin_cpu);
threadTimedWait(&Threads.globeBin, &ts, sleep_ms);
}
ZSTD_freeCCtx(cctx);
free_threadpool_buffer(&zstd_buffer);
free_threadpool_buffer(&pass_buffer);
pthread_mutex_unlock(&Threads.globeBin.mutex);
return NULL;
}
static void gainStatistics(struct mag_buf *buf) {
static uint64_t loudEvents;
static uint64_t noiseLowSamples;
static uint64_t noiseHighSamples;
static uint64_t totalSamples;
static int slowRise;
static int64_t nextRaiseAgc;
loudEvents += buf->loudEvents;
noiseLowSamples += buf->noiseLowSamples;
noiseHighSamples += buf->noiseHighSamples;
totalSamples += buf->length;
double interval = 0.5;
double riseTime = 15;
if (totalSamples < interval * Modes.sample_rate) {
return;
}
double noiseLowPercent = noiseLowSamples / (double) totalSamples * 100.0;
double noiseHighPercent = noiseHighSamples / (double) totalSamples * 100.0;
if (!Modes.autoGain) {
goto reset;
}
// 29 gain values for typical rtl-sdr
// allow startup to sweep entire range quickly, almost half it for double steps
int noiseLow = noiseLowPercent > 5; // too many samples < noiseLowThreshold
int noiseHigh = noiseHighPercent < 1; // too few samples < noiseHighThreshold
int loud = loudEvents > 1;
int veryLoud = loudEvents > 5;
if (loud || noiseHigh) {
Modes.lowerGain = 1;
if (veryLoud && !Modes.gainStartup) {
Modes.lowerGain = 2;
}
} else if (noiseLow) {
if (Modes.gainStartup || slowRise > riseTime / interval) {
slowRise = 0;
Modes.increaseGain = 1;
} else {
slowRise++;
}
}
if (Modes.increaseGain && Modes.gain == 496 && buf->sysTimestamp < nextRaiseAgc) {
goto reset;
}
if (Modes.increaseGain || Modes.lowerGain) {
if (Modes.gainStartup) {
Modes.lowerGain *= Modes.gainStartup;
Modes.increaseGain *= Modes.gainStartup;
}
char *reason = "";
if (veryLoud) {
reason = "decreasing gain, many strong signals found: ";
} else if (loud) {
reason = "decreasing gain, strong signal found: ";
} else if (noiseHigh) {
reason = "decreasing gain, noise too high: ";
} else if (noiseLow) {
reason = "increasing gain, noise too low: ";
}
sdrSetGain(reason);
if (Modes.gain == MODES_RTL_AGC) {
// switching to AGC is only done every 5 minutes to avoid oscillations due to the large step
nextRaiseAgc = buf->sysTimestamp + 5 * MINUTES;
}
//fprintf(stderr, "%9s gain. noiseLow: %5.2f %% noiseHigh: %5.2f %% loudEvents: %4lld\n", action, noiseLowPercent, noiseHighPercent, (long long) loudEvents);
}
reset:
Modes.gainStartup /= 2;
loudEvents = 0;
noiseLowSamples = 0;
noiseHighSamples = 0;
totalSamples = 0;
}
static void timingStatistics(struct mag_buf *buf) {
static int64_t last_ts;
int64_t elapsed_ts = buf->sysMicroseconds - last_ts;
// nominal time in us between two SDR callbacks
int64_t nominal = Modes.sdr_buf_samples * 1000LL * 1000LL / Modes.sample_rate;
int64_t jitter = elapsed_ts - nominal;
if (last_ts && Modes.log_usb_jitter && fabs((double)jitter) > Modes.log_usb_jitter) {
fprintf(stderr, "libusb callback jitter: %6.0f us\n", (double) jitter);
}
static int64_t last_sys;
if (last_sys || buf->sampleTimestamp * (1 / 12e6) > 10) {
static int64_t last_sample;
static int64_t interval;
int64_t nominal_interval = 30 * SECONDS * 1000;
if (!last_sys) {
last_sys = buf->sysMicroseconds;
last_sample = buf->sampleTimestamp;
interval = nominal_interval;
}
double elapsed_sys = buf->sysMicroseconds - last_sys;
// every 30 seconds
if ((elapsed_sys > interval && fabs((double) jitter) < 100) || elapsed_sys > interval * 3 / 2) {
// adjust interval heuristically
interval += (nominal_interval - elapsed_sys) / 4;
double elapsed_sample = buf->sampleTimestamp - last_sample;
double freq_ratio = elapsed_sample / (elapsed_sys * 12.0);
double diff_us = elapsed_sample / 12.0 - elapsed_sys;
double ppm = (freq_ratio - 1) * 1e6;
Modes.estimated_ppm = ppm;
if (Modes.devel_log_ppm && fabs(ppm) > Modes.devel_log_ppm) {
fprintf(stderr, "SDR ppm: %8.1f elapsed: %6.0f ms diff: %6.0f us last jitter: %6.0f\n", ppm, elapsed_sys / 1000.0, diff_us, (double) jitter);
}
if (fabs(ppm) > 600) {
if (ppm < -1000) {
int packets_lost = (int) nearbyint(ppm / -1820);
Modes.stats_current.samples_lost += packets_lost * Modes.sdr_buf_samples;
fprintf(stderr, "Lost %d packets (%.1f us) on USB, MLAT could be UNSTABLE, check sync! (ppm: %.0f)"
"(or the system clock jumped for some reason)\n", packets_lost, diff_us, ppm);
} else {
fprintf(stderr, "SDR ppm out of specification (could cause MLAT issues) or local clock jumped / not syncing with ntp or chrony! ppm: %.0f\n", ppm);
}
}
last_sys = buf->sysMicroseconds;
last_sample = buf->sampleTimestamp;
}
}
last_ts = buf->sysMicroseconds;
}
static void *decodeEntryPoint(void *arg) {
MODES_NOTUSED(arg);
srandom(get_seed());
pthread_mutex_lock(&Threads.decode.mutex);
modesInitNet();
/* If the user specifies --net-only, just run in order to serve network
* clients without reading data from the RTL device.
* This rules also in case a local Mode-S Beast is connected via USB.
*/
//fprintf(stderr, "startup complete after %.3f seconds.\n", getUptime() / 1000.0);
interactiveInit();
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
int64_t now = mstime();
int64_t mono = mono_milli_seconds();
if (Modes.net_only) {
while (!Modes.exit) {
struct timespec start_time;
// in case we're not waiting in backgroundTasks and priorityTasks doesn't have a chance to schedule
mono = mono_milli_seconds();
if (mono > Modes.next_remove_stale + 5 * SECONDS) {
threadTimedWait(&Threads.decode, &ts, 1);
}
start_cpu_timing(&start_time);
// sleep via epoll_wait in net_periodic_work
now = mstime();
backgroundTasks(now);
end_cpu_timing(&start_time, &Modes.stats_current.background_cpu);
}
} else {
int watchdogCounter = 200; // roughly 20 seconds
while (!Modes.exit) {
struct timespec start_time;
lockReader();
// reader is locked, and possibly we have data.
// copy out reader CPU time and reset it
add_timespecs(&Modes.reader_cpu_accumulator, &Modes.stats_current.reader_cpu, &Modes.stats_current.reader_cpu);
Modes.reader_cpu_accumulator.tv_sec = 0;
Modes.reader_cpu_accumulator.tv_nsec = 0;
struct mag_buf *buf = NULL;
if (Modes.first_free_buffer != Modes.first_filled_buffer) {
// FIFO is not empty, process one buffer.
buf = &Modes.mag_buffers[Modes.first_filled_buffer];
} else {
buf = NULL;
}
unlockReader();
if (buf) {
start_cpu_timing(&start_time);
demodulate2400(buf);
if (Modes.mode_ac) {
demodulate2400AC(buf);
}
gainStatistics(buf);
timingStatistics(buf);
Modes.stats_current.samples_lost += Modes.sdr_buf_samples - buf->length;
Modes.stats_current.samples_processed += buf->length;
Modes.stats_current.samples_dropped += buf->dropped;
end_cpu_timing(&start_time, &Modes.stats_current.demod_cpu);
// Mark the buffer we just processed as completed.
lockReader();
Modes.first_filled_buffer = (Modes.first_filled_buffer + 1) % MODES_MAG_BUFFERS;
pthread_cond_signal(&Threads.reader.cond);
unlockReader();
watchdogCounter = 100; // roughly 10 seconds
} else {
// Nothing to process this time around.
if (--watchdogCounter <= 0) {
fprintf(stderr, "<3>SDR wedged, exiting! (check power supply / avoid using an USB extension / SDR might be defective)\n");
setExit(2);
break;
}
}
start_cpu_timing(&start_time);
now = mstime();
backgroundTasks(now);
end_cpu_timing(&start_time, &Modes.stats_current.background_cpu);
lockReader();
int newData = (Modes.first_free_buffer != Modes.first_filled_buffer);
unlockReader();
if (!newData) {
/* wait for more data.
* we should be getting data every 50-60ms. wait for max 80 before we give up and do some background work.
* this is fairly aggressive as all our network I/O runs out of the background work!
*/
threadTimedWait(&Threads.decode, &ts, 80);
}
mono = mono_milli_seconds();
if (mono > Modes.next_remove_stale + REMOVE_STALE_INTERVAL) {