Repository navigation
Expand file tree
/
Copy pathNetSim.cpp
More file actions
1370 lines (1184 loc) · 53.5 KB
/
Copy pathNetSim.cpp
File metadata and controls
1370 lines (1184 loc) · 53.5 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
// NetSim.cpp
// Network Simulator Implementation
// Based on empirical data from "Measurements and analysis of UDP transmissions
// over wireless networks" (Berglund, 2018)
#include "NetSim.h"
#include <algorithm>
#include <cmath>
#include <condition_variable>
#include <cstring>
#include <numeric>
#include <queue>
#include <stdexcept>
#include <thread>
// ============================================================================
// Network Profile Data - measured anchors plus model interpolations
// ============================================================================
namespace NetSimData {
// Helper to create delay profile based on thesis measurements
// All values in microseconds unless noted
DelayProfile makeDelayProfile(NetworkType aType, NetworkQuality aQuality, MobilityState aMobility) {
DelayProfile profile{};
switch (aType) {
case NetworkType::WIFI_5GHZ:
// From thesis Section 6.1.1: 5.0 GHz WLAN delay measurements
// Time before loss: 1-2 seconds for all cases
profile.mDelayBuildupSeconds = 1.5;
switch (aQuality) {
case NetworkQuality::EXCELLENT:
// High quality: max delay 48ms
profile.mBaseDelayUs = 1000; // 1ms base
profile.mMaxDelayUs = 48000; // 48ms max
profile.mJitterStdDevUs = 500; // Low jitter
break;
case NetworkQuality::GOOD:
profile.mBaseDelayUs = 2000;
profile.mMaxDelayUs = 100000; // 100ms
profile.mJitterStdDevUs = 1000;
break;
case NetworkQuality::FAIR:
// Medium quality: max delay 560ms (1472 bytes)
profile.mBaseDelayUs = 5000;
profile.mMaxDelayUs = 560000; // 560ms
profile.mJitterStdDevUs = 5000;
break;
case NetworkQuality::POOR:
// Low quality: max delay 878ms (1472 bytes)
profile.mBaseDelayUs = 10000;
profile.mMaxDelayUs = 878000; // 878ms
profile.mJitterStdDevUs = 10000;
break;
case NetworkQuality::TERRIBLE:
profile.mBaseDelayUs = 50000;
profile.mMaxDelayUs = 1200000; // 1.2s (upper bound from thesis)
profile.mJitterStdDevUs = 50000;
break;
}
break;
case NetworkType::WIFI_2_4GHZ:
// From thesis Section 6.1.2: 2.4 GHz WLAN delay measurements
// Generally higher delay than 5.0 GHz
profile.mDelayBuildupSeconds = 1.5;
switch (aQuality) {
case NetworkQuality::EXCELLENT:
// High quality: max delay 690ms (1472 bytes)
profile.mBaseDelayUs = 2000;
profile.mMaxDelayUs = 690000; // 690ms
profile.mJitterStdDevUs = 2000;
break;
case NetworkQuality::GOOD:
profile.mBaseDelayUs = 5000;
profile.mMaxDelayUs = 1000000; // 1s
profile.mJitterStdDevUs = 5000;
break;
case NetworkQuality::FAIR:
// Medium quality: max delay 2296ms
profile.mBaseDelayUs = 10000;
profile.mMaxDelayUs = 2296000; // 2.296s
profile.mJitterStdDevUs = 10000;
break;
case NetworkQuality::POOR:
// Low quality: max delay 24360ms (24.36s!)
profile.mBaseDelayUs = 50000;
profile.mMaxDelayUs = 10000000; // 10s (capped for usability)
profile.mJitterStdDevUs = 50000;
profile.mDelayBuildupSeconds = 3.0; // Longer in poor conditions
break;
case NetworkQuality::TERRIBLE:
profile.mBaseDelayUs = 100000;
profile.mMaxDelayUs = 25000000; // 25s (from thesis: 24.36s max)
profile.mJitterStdDevUs = 100000;
profile.mDelayBuildupSeconds = 5.0;
break;
}
break;
case NetworkType::CELLULAR_4G:
// From thesis Section 6.1.3: 4G delay measurements
// Much larger buffers = longer delay before loss (6-20 seconds)
if (aMobility == MobilityState::STATIONARY) {
// Stationary: max delay 5758ms (1472 bytes), 2914ms (740 bytes)
// Time before loss: 7-8 seconds (1472), 6-10 seconds (740)
profile.mDelayBuildupSeconds = 7.5; // midpoint of measured 7-8s at 1472 bytes
switch (aQuality) {
case NetworkQuality::EXCELLENT:
profile.mBaseDelayUs = 20000; // 20ms base (higher than WiFi)
profile.mMaxDelayUs = 500000; // 500ms
profile.mJitterStdDevUs = 5000;
break;
case NetworkQuality::GOOD:
profile.mBaseDelayUs = 30000;
profile.mMaxDelayUs = 2000000; // 2s
profile.mJitterStdDevUs = 10000;
break;
case NetworkQuality::FAIR:
profile.mBaseDelayUs = 50000;
profile.mMaxDelayUs = 5758000; // measured 1472-byte anchor: 5.758s
profile.mJitterStdDevUs = 20000;
break;
case NetworkQuality::POOR:
profile.mBaseDelayUs = 100000;
profile.mMaxDelayUs = 8000000; // model extrapolation
profile.mJitterStdDevUs = 50000;
break;
case NetworkQuality::TERRIBLE:
profile.mBaseDelayUs = 200000;
profile.mMaxDelayUs = 12000000; // model extrapolation
profile.mJitterStdDevUs = 100000;
break;
}
} else {
// Moving: max delay 6198ms (740 bytes), 3551ms (1472 bytes)
// Time before loss: 13-20 seconds (1472), 8-9 seconds (740)
// More variability due to handovers
profile.mDelayBuildupSeconds = 16.5; // midpoint of measured 13-20s at 1472 bytes
switch (aQuality) {
case NetworkQuality::EXCELLENT:
profile.mBaseDelayUs = 30000;
profile.mMaxDelayUs = 1000000; // 1s
profile.mJitterStdDevUs = 10000;
break;
case NetworkQuality::GOOD:
profile.mBaseDelayUs = 50000;
profile.mMaxDelayUs = 2500000; // 2.5s
profile.mJitterStdDevUs = 20000;
break;
case NetworkQuality::FAIR:
profile.mBaseDelayUs = 80000;
profile.mMaxDelayUs = 3551000; // measured 1472-byte anchor: 3.551s
profile.mJitterStdDevUs = 40000;
break;
case NetworkQuality::POOR:
profile.mBaseDelayUs = 150000;
profile.mMaxDelayUs = 6000000; // model extrapolation
profile.mJitterStdDevUs = 80000;
break;
case NetworkQuality::TERRIBLE:
profile.mBaseDelayUs = 300000;
profile.mMaxDelayUs = 10000000; // model extrapolation
profile.mJitterStdDevUs = 150000;
break;
}
}
break;
}
return profile;
}
// Helper to create loss profile based on thesis measurements
static LossProfile makeLossProfile(NetworkType aType, NetworkQuality aQuality, MobilityState aMobility) {
LossProfile profile{};
switch (aType) {
case NetworkType::WIFI_5GHZ:
// From thesis Table 3 and Table 6
// 5.0 GHz performs well even in poor conditions
profile.mCongestionThreshold = 0.85; // Loss starts at 85% utilization
switch (aQuality) {
case NetworkQuality::EXCELLENT:
// High quality: 2.86% loss (ramp), 0% (stream at 8 Mbps)
profile.mBaseLossPercent = 0.0;
profile.mCongestionLossPercent = 2.86;
profile.mSevereLossPercent = 10.0;
break;
case NetworkQuality::GOOD:
profile.mBaseLossPercent = 0.0;
profile.mCongestionLossPercent = 5.0;
profile.mSevereLossPercent = 15.0;
break;
case NetworkQuality::FAIR:
// Medium quality: 11.80% loss
profile.mBaseLossPercent = 0.01;
profile.mCongestionLossPercent = 11.80;
profile.mSevereLossPercent = 25.0;
break;
case NetworkQuality::POOR:
// Low quality: 29.09% loss
profile.mBaseLossPercent = 0.02;
profile.mCongestionLossPercent = 29.09;
profile.mSevereLossPercent = 50.0;
break;
case NetworkQuality::TERRIBLE:
profile.mBaseLossPercent = 0.1;
profile.mCongestionLossPercent = 40.0;
profile.mSevereLossPercent = 70.0;
break;
}
break;
case NetworkType::WIFI_2_4GHZ:
// From thesis Table 4 and Table 7
// 2.4 GHz has significantly more loss than 5.0 GHz
profile.mCongestionThreshold = 0.70; // Earlier congestion
switch (aQuality) {
case NetworkQuality::EXCELLENT:
// High quality: 40.18% loss in ramp, 0.015% in stream
profile.mBaseLossPercent = 0.0;
profile.mCongestionLossPercent = 40.18;
profile.mSevereLossPercent = 60.0;
break;
case NetworkQuality::GOOD:
profile.mBaseLossPercent = 0.01;
profile.mCongestionLossPercent = 50.0;
profile.mSevereLossPercent = 70.0;
break;
case NetworkQuality::FAIR:
// Medium quality: 77.25% loss in ramp, 1.17% in stream at 8 Mbps
profile.mBaseLossPercent = 0.1;
profile.mCongestionLossPercent = 77.25;
profile.mSevereLossPercent = 85.0;
break;
case NetworkQuality::POOR:
// Low quality: 93.44% loss in ramp, 57.44% in stream at 8 Mbps
profile.mBaseLossPercent = 1.0;
profile.mCongestionLossPercent = 93.44;
profile.mSevereLossPercent = 98.0;
break;
case NetworkQuality::TERRIBLE:
profile.mBaseLossPercent = 5.0;
profile.mCongestionLossPercent = 95.0;
profile.mSevereLossPercent = 99.0;
break;
}
break;
case NetworkType::CELLULAR_4G:
// From thesis Table 5 and Table 8
// Performance varies with mobility
profile.mCongestionThreshold = 0.75;
if (aMobility == MobilityState::STATIONARY) {
// Stationary: 13.43% loss (1472 bytes), 22.42% (740 bytes)
switch (aQuality) {
case NetworkQuality::EXCELLENT:
profile.mBaseLossPercent = 0.0;
profile.mCongestionLossPercent = 5.0;
profile.mSevereLossPercent = 15.0;
break;
case NetworkQuality::GOOD:
profile.mBaseLossPercent = 0.0;
profile.mCongestionLossPercent = 10.0;
profile.mSevereLossPercent = 25.0;
break;
case NetworkQuality::FAIR:
profile.mBaseLossPercent = 0.01;
profile.mCongestionLossPercent = 13.43;
profile.mSevereLossPercent = 30.0;
break;
case NetworkQuality::POOR:
profile.mBaseLossPercent = 0.1;
profile.mCongestionLossPercent = 22.42;
profile.mSevereLossPercent = 45.0;
break;
case NetworkQuality::TERRIBLE:
profile.mBaseLossPercent = 1.0;
profile.mCongestionLossPercent = 35.0;
profile.mSevereLossPercent = 60.0;
break;
}
} else {
// Moving: 9.29% (1472 bytes), 27.22% (740 bytes)
// Higher variability
switch (aQuality) {
case NetworkQuality::EXCELLENT:
profile.mBaseLossPercent = 0.0;
profile.mCongestionLossPercent = 8.0;
profile.mSevereLossPercent = 20.0;
break;
case NetworkQuality::GOOD:
profile.mBaseLossPercent = 0.01;
profile.mCongestionLossPercent = 12.0;
profile.mSevereLossPercent = 28.0;
break;
case NetworkQuality::FAIR:
profile.mBaseLossPercent = 0.1;
profile.mCongestionLossPercent = 9.29; // measured 1472-byte anchor
profile.mSevereLossPercent = 30.0;
break;
case NetworkQuality::POOR:
profile.mBaseLossPercent = 0.5;
profile.mCongestionLossPercent = 18.0; // model extrapolation
profile.mSevereLossPercent = 50.0;
break;
case NetworkQuality::TERRIBLE:
profile.mBaseLossPercent = 2.0;
profile.mCongestionLossPercent = 40.0;
profile.mSevereLossPercent = 70.0;
break;
}
}
break;
}
return profile;
}
// Helper to create reorder profile
// Informed by thesis Section 6.4.2 and Tables 9-10. Runtime probability uses
// the measured bandwidth/packet-size anchors; quality controls the modeled
// maximum reorder distance.
static ReorderProfile makeReorderProfile(NetworkType aType, NetworkQuality aQuality, MobilityState aMobility) {
ReorderProfile profile{};
// WiFi networks do NOT produce reordering according to thesis
if (aType != NetworkType::CELLULAR_4G) {
profile.mReorderPercent = 0.0;
profile.mMaxReorderDistance = 0;
profile.mGaussianDistribution = false;
return profile;
}
// 4G 1472-byte ramp anchors from Table 10. Runtime probability also
// accounts for offered bandwidth and packet size.
profile.mGaussianDistribution = true; // Thesis notes Gaussian-like distribution
if (aMobility == MobilityState::STATIONARY) {
profile.mReorderPercent = 0.28;
switch (aQuality) {
case NetworkQuality::EXCELLENT:
case NetworkQuality::GOOD:
profile.mMaxReorderDistance = 5;
break;
case NetworkQuality::FAIR:
profile.mMaxReorderDistance = 10;
break;
case NetworkQuality::POOR:
case NetworkQuality::TERRIBLE:
profile.mMaxReorderDistance = 20;
break;
}
} else {
profile.mReorderPercent = 1.60;
switch (aQuality) {
case NetworkQuality::EXCELLENT:
case NetworkQuality::GOOD:
profile.mMaxReorderDistance = 15;
break;
case NetworkQuality::FAIR:
profile.mMaxReorderDistance = 25;
break;
case NetworkQuality::POOR:
case NetworkQuality::TERRIBLE:
profile.mMaxReorderDistance = 40;
break;
}
}
return profile;
}
// Helper to create duplicate profile
// From thesis Section 6.4.1 - duplicates occur only in 4G and are rare
static DuplicateProfile makeDuplicateProfile(NetworkType aType, NetworkQuality aQuality, MobilityState aMobility) {
static_cast<void>(aQuality);
DuplicateProfile profile{};
// WiFi networks do NOT produce duplicates according to thesis
if (aType != NetworkType::CELLULAR_4G) {
profile.mDuplicatePercent = 0.0;
profile.mDuplicateDelayUs = 0;
return profile;
}
// The thesis observed one duplicate in one of four moving 740-byte ramp
// repetitions and none while stationary. 0.00035% is the approximate
// mean rate across those repetitions; runtime packet-size scaling makes
// the probability zero at 1472 bytes and reaches this value at 740 bytes.
profile.mDuplicateDelayUs = 50000; // Modeled 50ms duplicate delay
if (aMobility == MobilityState::STATIONARY) {
profile.mDuplicatePercent = 0.0;
} else {
profile.mDuplicatePercent = 0.00035;
}
return profile;
}
// Get maximum bandwidth based on network type and quality
double getMaxBandwidth(NetworkType aType, NetworkQuality aQuality) {
// From thesis: WLAN tests up to 100 Mbps, 4G tests up to 50 Mbps
// Actual achievable bandwidth depends on quality
switch (aType) {
case NetworkType::WIFI_5GHZ:
// 802.11n can theoretically do 600 Mbps, but thesis used 100 Mbps max
switch (aQuality) {
case NetworkQuality::EXCELLENT: return 100'000'000.0; // 100 Mbps
case NetworkQuality::GOOD: return 80'000'000.0; // 80 Mbps
case NetworkQuality::FAIR: return 50'000'000.0; // 50 Mbps
case NetworkQuality::POOR: return 30'000'000.0; // 30 Mbps
case NetworkQuality::TERRIBLE: return 10'000'000.0; // 10 Mbps
}
break;
case NetworkType::WIFI_2_4GHZ:
// 2.4 GHz typically slower than 5.0 GHz
switch (aQuality) {
case NetworkQuality::EXCELLENT: return 50'000'000.0; // 50 Mbps
case NetworkQuality::GOOD: return 40'000'000.0; // 40 Mbps
case NetworkQuality::FAIR: return 25'000'000.0; // 25 Mbps
case NetworkQuality::POOR: return 10'000'000.0; // 10 Mbps
case NetworkQuality::TERRIBLE: return 4'000'000.0; // 4 Mbps
}
break;
case NetworkType::CELLULAR_4G:
// LTE theoretical 100 Mbps down, but shared among users
switch (aQuality) {
case NetworkQuality::EXCELLENT: return 50'000'000.0; // 50 Mbps
case NetworkQuality::GOOD: return 30'000'000.0; // 30 Mbps
case NetworkQuality::FAIR: return 15'000'000.0; // 15 Mbps
case NetworkQuality::POOR: return 5'000'000.0; // 5 Mbps
case NetworkQuality::TERRIBLE: return 1'000'000.0; // 1 Mbps
}
break;
}
return 10'000'000.0; // Default 10 Mbps
}
NetworkProfile getProfile(NetworkType aType, NetworkQuality aQuality, MobilityState aMobility) {
NetworkProfile profile{};
profile.mDelay = makeDelayProfile(aType, aQuality, aMobility);
profile.mLoss = makeLossProfile(aType, aQuality, aMobility);
profile.mReorder = makeReorderProfile(aType, aQuality, aMobility);
profile.mDuplicate = makeDuplicateProfile(aType, aQuality, aMobility);
profile.mMaxBandwidthBps = getMaxBandwidth(aType, aQuality);
return profile;
}
} // namespace NetSimData
// ============================================================================
// NetSim Implementation
// ============================================================================
class NetSim::Impl {
public:
Impl() : Impl(NetSimConfig{}) {}
explicit Impl(const NetSimConfig& aConfig) {
configure(aConfig);
}
~Impl() {
mStopped = true;
stopWorker();
}
void configure(const NetSimConfig& aConfig) {
std::lock_guard<std::mutex> lock(mMutex);
mConfig = aConfig;
mProfile = NetSimData::getProfile(aConfig.mNetworkType, aConfig.mQuality, aConfig.mMobility);
// Override max bandwidth if specified in config
if (aConfig.mMaxBandwidthBps > 0) {
mProfile.mMaxBandwidthBps = aConfig.mMaxBandwidthBps;
}
// Initialize RNG
if (aConfig.mRandomSeed == 0) {
std::random_device rd;
mRng.seed(rd());
} else {
mRng.seed(aConfig.mRandomSeed);
}
// Reset state
mCongestionState = CongestionState::IDLE;
mCongestionBuildupStart = std::chrono::steady_clock::time_point{};
mLastPacketDeliveryTime = std::chrono::steady_clock::time_point{};
mCurrentUtilization = mManualOfferedBandwidth
? *mManualOfferedBandwidth / mProfile.mMaxBandwidthBps
: 0.0;
mStats.mCongestionState = mCongestionState;
}
NetSimConfig getConfig() const {
std::lock_guard<std::mutex> lock(mMutex);
return mConfig;
}
void setOnPacketDelivered(OnPacketDeliveredCallback aCallback) {
std::lock_guard<std::mutex> lock(mMutex);
mOnPacketDelivered = std::move(aCallback);
}
void setOnStateChange(OnStateChangeCallback aCallback) {
std::lock_guard<std::mutex> lock(mMutex);
mOnStateChange = std::move(aCallback);
}
void reset() {
// Stop worker first if running
stopWorker();
std::lock_guard<std::mutex> lock(mMutex);
mPendingPackets.clear();
mDeliveryQueue.clear();
mStats = NetSimStatistics{};
mCongestionState = CongestionState::IDLE;
mCongestionBuildupStart = std::chrono::steady_clock::time_point{};
mLastDelay = 0;
mLastPacketDeliveryTime = std::chrono::steady_clock::time_point{};
mLastScheduledDeliveryTime = std::chrono::steady_clock::time_point{};
mCurrentUtilization = 0.0;
mLastPacketSize = 1472;
mBandwidthHistory.clear();
mHighestDeliveredSeq = 0;
mHasDeliveredSequence = false;
mAutoSequence = 0;
mQueueBytes = 0;
mManualOfferedBandwidth.reset();
mStopped = false;
}
void stop() {
mStopped = true;
stopWorker();
// Also drain packets submitted in synchronous mode, or accepted just
// before a concurrent stop request.
processTimeStepInternal(true);
}
void start() {
bool expected = false;
if (!mRunning.compare_exchange_strong(expected, true)) {
return; // Already running
}
mStopped = false;
mWorker = std::thread([this] { workerLoop(); });
}
bool isRunning() const {
return mRunning.load();
}
void push(const uint8_t* aData, size_t aLen) {
if (!aData || aLen == 0) return;
if (mStopped) return;
std::vector<std::pair<CongestionState, CongestionState>> stateChanges;
OnStateChangeCallback stateCallback;
std::unique_lock<std::mutex> lock(mMutex);
if (mStopped) return;
const size_t mtu = mConfig.mMtuBytes > 0 ? mConfig.mMtuBytes : aLen;
size_t offset = 0;
while (offset < aLen) {
const size_t chunk = std::min(mtu, aLen - offset);
const uint64_t seq = mAutoSequence++;
// Tail-drop if queue is full
if (mQueueBytes + chunk > mConfig.mMaxQueueBytes) {
mStats.mPacketsDroppedQueueFull++;
mStats.mPacketsSent++;
updateStatistics();
offset += chunk;
continue;
}
// Create payload for this chunk
std::vector<uint8_t> payload(aData + offset, aData + offset + chunk);
auto stateChange = submitPacketLocked(seq, payload);
if (stateChange) stateChanges.push_back(*stateChange);
offset += chunk;
}
stateCallback = mOnStateChange;
lock.unlock();
if (stateCallback) {
for (const auto& change : stateChanges) {
stateCallback(change.first, change.second);
}
}
// Notify worker thread
mCv.notify_all();
}
void push(const std::vector<uint8_t>& aData) {
push(aData.data(), aData.size());
}
void submitPacket(uint64_t aSequenceNumber, const std::vector<uint8_t>& aPayload) {
if (mStopped) return;
OnStateChangeCallback stateCallback;
std::optional<std::pair<CongestionState, CongestionState>> stateChange;
{
std::lock_guard<std::mutex> lock(mMutex);
if (mStopped) return;
stateChange = submitPacketLocked(aSequenceNumber, aPayload);
stateCallback = mOnStateChange;
}
if (stateChange && stateCallback) {
stateCallback(stateChange->first, stateChange->second);
}
mCv.notify_all();
}
void submitPacket(uint64_t aSequenceNumber, const uint8_t* aData, size_t aSize) {
if (!aData && aSize > 0) return;
if (aSize == 0) {
submitPacket(aSequenceNumber, std::vector<uint8_t>{});
return;
}
submitPacket(aSequenceNumber, std::vector<uint8_t>(aData, aData + aSize));
}
std::optional<NetSimResult> pollDelivered() {
std::lock_guard<std::mutex> lock(mMutex);
if (mDeliveryQueue.empty()) {
return std::nullopt;
}
NetSimResult result = std::move(mDeliveryQueue.front());
mDeliveryQueue.pop_front();
return result;
}
std::vector<NetSimResult> pollAllDelivered() {
std::lock_guard<std::mutex> lock(mMutex);
std::vector<NetSimResult> results;
results.reserve(mDeliveryQueue.size());
while (!mDeliveryQueue.empty()) {
results.push_back(std::move(mDeliveryQueue.front()));
mDeliveryQueue.pop_front();
}
return results;
}
size_t processTimeStep() {
if (mStopped) return 0;
return processTimeStepInternal(false);
}
NetSimStatistics getStatistics() const {
std::lock_guard<std::mutex> lock(mMutex);
return mStats;
}
void resetStatistics() {
std::lock_guard<std::mutex> lock(mMutex);
mStats = NetSimStatistics{};
mStats.mCongestionState = mCongestionState;
mLastDelay = 0;
mHighestDeliveredSeq = 0;
mHasDeliveredSequence = false;
if (mManualOfferedBandwidth) {
mStats.mTargetBandwidthBps = *mManualOfferedBandwidth;
}
}
CongestionState getCongestionState() const {
std::lock_guard<std::mutex> lock(mMutex);
return mCongestionState;
}
void setOfferedBandwidth(double aBandwidthBps) {
OnStateChangeCallback stateCallback;
std::optional<std::pair<CongestionState, CongestionState>> stateChange;
{
std::lock_guard<std::mutex> lock(mMutex);
if (aBandwidthBps > 0) {
mManualOfferedBandwidth = aBandwidthBps;
mStats.mTargetBandwidthBps = aBandwidthBps;
mCurrentUtilization = aBandwidthBps / mProfile.mMaxBandwidthBps;
} else {
mManualOfferedBandwidth.reset();
mStats.mTargetBandwidthBps = 0.0;
mCurrentUtilization = mStats.mCurrentBandwidthBps / mProfile.mMaxBandwidthBps;
}
stateChange = updateCongestionState(std::chrono::steady_clock::now());
stateCallback = mOnStateChange;
}
if (stateChange && stateCallback) {
stateCallback(stateChange->first, stateChange->second);
}
}
double getEstimatedCapacity() const {
std::lock_guard<std::mutex> lock(mMutex);
return mProfile.mMaxBandwidthBps;
}
private:
std::optional<std::pair<CongestionState, CongestionState>> submitPacketLocked(
uint64_t aSequenceNumber, const std::vector<uint8_t>& aPayload) {
auto now = std::chrono::steady_clock::now();
mLastPacketSize = aPayload.size();
// Update bandwidth tracking
updateBandwidthTracking(aPayload.size(), now);
// Update congestion state
auto stateChange = updateCongestionState(now);
// Create packet
SimPacket packet;
packet.mSequenceNumber = aSequenceNumber;
packet.mPayload = aPayload;
packet.mEnqueueTime = now;
// Determine if packet will be dropped (pass packet size for 4G size-dependent loss)
packet.mIsDropped = shouldDropPacket(aPayload.size());
if (!packet.mIsDropped) {
// Calculate delivery time with delay
int64_t delayUs = calculateDelay(now, aPayload.size());
// Store the scheduled delay for reproducibility
packet.mScheduledDelayUs = delayUs;
auto delayDuration = std::chrono::microseconds(delayUs);
// Apply time scaling
if (mConfig.mTimeScale != 1.0 && mConfig.mTimeScale > 0) {
delayDuration = std::chrono::microseconds(
static_cast<int64_t>(delayUs / mConfig.mTimeScale));
}
packet.mDeliveryTime = now + delayDuration;
// Delay jitter alone must not create reordering. Keep the base
// schedule monotonic; the explicit 4G reorder offset below is the
// only mechanism allowed to change packet order.
if (mLastScheduledDeliveryTime != std::chrono::steady_clock::time_point{} &&
packet.mDeliveryTime <= mLastScheduledDeliveryTime) {
packet.mDeliveryTime = mLastScheduledDeliveryTime + std::chrono::microseconds(1);
}
mLastScheduledDeliveryTime = packet.mDeliveryTime;
// Determine reordering (4G only)
if (mConfig.mEnableReordering && mProfile.mReorder.mReorderPercent > 0) {
packet.mReorderOffset = calculateReorderOffset(aPayload.size());
}
mPendingPackets.push_back(packet);
mQueueBytes += packet.mPayload.size();
// Generate duplicate if applicable (4G only)
if (mConfig.mEnableDuplicates && shouldGenerateDuplicate(aPayload.size())) {
SimPacket duplicate = packet;
duplicate.mIsDuplicate = true;
auto dupDelay = std::chrono::microseconds(mProfile.mDuplicate.mDuplicateDelayUs);
duplicate.mDeliveryTime = packet.mDeliveryTime + dupDelay;
// Duplicate's scheduled delay includes the extra duplicate delay
duplicate.mScheduledDelayUs = packet.mScheduledDelayUs + mProfile.mDuplicate.mDuplicateDelayUs;
mPendingPackets.push_back(duplicate);
mQueueBytes += duplicate.mPayload.size();
mStats.mPacketsDuplicated++;
}
} else {
mStats.mPacketsDropped++;
}
mStats.mPacketsSent++;
updateStatistics();
return stateChange;
}
void updateBandwidthTracking(size_t aPacketSize, std::chrono::steady_clock::time_point aTime) {
// Track bandwidth over a sliding window
double bitsReceived = aPacketSize * 8.0;
mBandwidthHistory.push_back({aTime, bitsReceived});
// Remove old entries (older than 1 second)
auto cutoff = aTime - std::chrono::seconds(1);
while (!mBandwidthHistory.empty() && mBandwidthHistory.front().first < cutoff) {
mBandwidthHistory.pop_front();
}
// Calculate current bandwidth
double totalBits = 0;
for (const auto& entry : mBandwidthHistory) {
totalBits += entry.second;
}
mStats.mCurrentBandwidthBps = totalBits; // bits per second (1 second window)
// Update utilization
const double offeredBandwidth = mManualOfferedBandwidth.value_or(mStats.mCurrentBandwidthBps);
mCurrentUtilization = offeredBandwidth / mProfile.mMaxBandwidthBps;
}
double scaledBuildupSeconds() const {
double buildupSeconds = mProfile.mDelay.mDelayBuildupSeconds;
if (mConfig.mNetworkType == NetworkType::CELLULAR_4G &&
mLastPacketSize > 0 && mLastPacketSize < 1472) {
// Figure 32 midpoint anchors: stationary 740-byte ramps build for
// about 8s; moving 740-byte ramps build for about 8.5s.
const double target740 =
mConfig.mMobility == MobilityState::STATIONARY ? 8.0 : 8.5;
const double interpolation = std::clamp(
static_cast<double>(1472 - mLastPacketSize) / (1472.0 - 740.0), 0.0, 1.0);
buildupSeconds += (target740 - buildupSeconds) * interpolation;
}
const double bufferScale = std::clamp(
static_cast<double>(mConfig.mBufferSizePackets) / 1000.0, 0.01, 10.0);
const double timeScale = mConfig.mTimeScale > 0 ? mConfig.mTimeScale : 1.0;
return buildupSeconds * bufferScale / timeScale;
}
std::optional<std::pair<CongestionState, CongestionState>> updateCongestionState(
std::chrono::steady_clock::time_point aTime) {
CongestionState oldState = mCongestionState;
// State machine based on utilization
if (mCurrentUtilization < 0.3) {
mCongestionState = CongestionState::IDLE;
mCongestionBuildupStart = std::chrono::steady_clock::time_point{};
} else if (mCurrentUtilization < mProfile.mLoss.mCongestionThreshold) {
mCongestionState = CongestionState::NORMAL;
mCongestionBuildupStart = std::chrono::steady_clock::time_point{};
} else {
// Delay builds before significant loss even when offered traffic
// greatly exceeds capacity. Once the measured buildup interval
// elapses, select congested or severe loss from utilization.
if (mCongestionState < CongestionState::BUILDING ||
mCongestionBuildupStart == std::chrono::steady_clock::time_point{}) {
mCongestionBuildupStart = aTime;
}
const auto buildupDuration = std::chrono::duration_cast<std::chrono::duration<double>>(
aTime - mCongestionBuildupStart);
if (buildupDuration.count() < scaledBuildupSeconds()) {
mCongestionState = CongestionState::BUILDING;
} else {
mCongestionState = mCurrentUtilization < 0.95
? CongestionState::CONGESTED
: CongestionState::SEVERELY_CONGESTED;
}
}
mStats.mCongestionState = mCongestionState;
if (oldState != mCongestionState) {
return std::make_pair(oldState, mCongestionState);
}
return std::nullopt;
}
bool shouldDropPacket(size_t packetSize) {
double lossPercent = 0.0;
switch (mCongestionState) {
case CongestionState::IDLE:
case CongestionState::NORMAL:
lossPercent = mProfile.mLoss.mBaseLossPercent;
break;
case CongestionState::BUILDING:
// The measured warning phase is rising delay before significant
// loss, so retain only the profile's baseline loss here.
lossPercent = mProfile.mLoss.mBaseLossPercent;
break;
case CongestionState::CONGESTED:
lossPercent = mProfile.mLoss.mCongestionLossPercent;
break;
case CongestionState::SEVERELY_CONGESTED:
lossPercent = mProfile.mLoss.mSevereLossPercent;
break;
}
// Apply packet-size-dependent loss multiplier for 4G networks.
// Reference ratios at 740 bytes versus 1472 bytes:
// stationary 22.42 / 13.43 = 1.67; moving 27.22 / 9.29 = 2.93.
if (mConfig.mNetworkType == NetworkType::CELLULAR_4G && packetSize > 0 && packetSize < 1472) {
const double referenceMultiplier =
mConfig.mMobility == MobilityState::STATIONARY ? (22.42 / 13.43)
: (27.22 / 9.29);
const double interpolation = std::clamp(
static_cast<double>(1472 - packetSize) / (1472.0 - 740.0), 0.0, 1.0);
const double sizeFactor = 1.0 + (referenceMultiplier - 1.0) * interpolation;
lossPercent *= sizeFactor;
}
std::uniform_real_distribution<double> dist(0.0, 100.0);
return dist(mRng) < lossPercent;
}
int64_t calculateDelay(std::chrono::steady_clock::time_point aTime, size_t aPacketSize) {
// Base delay
int64_t delay = mProfile.mDelay.mBaseDelayUs;
int64_t maxDelayUs = mProfile.mDelay.mMaxDelayUs;
// Table 5 / Figure 32 show opposite packet-size delay effects for
// stationary and moving 4G. Interpolate between the measured 1472-
// and 740-byte anchors, then cap the factor for smaller packets.
if (mConfig.mNetworkType == NetworkType::CELLULAR_4G &&
aPacketSize > 0 && aPacketSize < 1472) {
const double measuredRatio =
mConfig.mMobility == MobilityState::STATIONARY
? (2914.0 / 5758.0)
: (6198.0 / 3551.0);
const double interpolation = std::clamp(
static_cast<double>(1472 - aPacketSize) / (1472.0 - 740.0), 0.0, 1.0);
const double factor = 1.0 + (measuredRatio - 1.0) * interpolation;
maxDelayUs = static_cast<int64_t>(maxDelayUs * factor);
maxDelayUs = std::max(maxDelayUs, mProfile.mDelay.mBaseDelayUs);
}
// Add congestion-based delay
switch (mCongestionState) {
case CongestionState::IDLE:
// Just base delay with small jitter
break;
case CongestionState::NORMAL:
// Slight increase
delay += static_cast<int64_t>(
(maxDelayUs - mProfile.mDelay.mBaseDelayUs) * 0.1);
break;
case CongestionState::BUILDING: {
// Delay increases over time (thesis observation: delay ramps up before loss)
double buildupProgress = 0.0;
if (mCongestionBuildupStart != std::chrono::steady_clock::time_point{}) {
auto duration = std::chrono::duration_cast<std::chrono::duration<double>>(
aTime - mCongestionBuildupStart);
buildupProgress = std::min(1.0, duration.count() / scaledBuildupSeconds());
}
delay += static_cast<int64_t>(
(maxDelayUs - mProfile.mDelay.mBaseDelayUs) * buildupProgress * 0.7);
break;
}
case CongestionState::CONGESTED:
delay += static_cast<int64_t>(
(maxDelayUs - mProfile.mDelay.mBaseDelayUs) * 0.8);
break;
case CongestionState::SEVERELY_CONGESTED:
delay = maxDelayUs;
break;
}
// Add jitter
std::normal_distribution<double> jitterDist(0.0, mProfile.mDelay.mJitterStdDevUs);
int64_t jitter = static_cast<int64_t>(jitterDist(mRng));
// Thesis observation: jitter shifts positive before loss
if (mCongestionState == CongestionState::BUILDING && mConfig.mEnableJitterWarning &&
mCongestionBuildupStart != std::chrono::steady_clock::time_point{}) {
const auto elapsed = std::chrono::duration_cast<std::chrono::duration<double>>(
aTime - mCongestionBuildupStart).count();
const double timeScale = mConfig.mTimeScale > 0 ? mConfig.mTimeScale : 1.0;
const double warningWindow = 0.6 / timeScale;
if (scaledBuildupSeconds() - elapsed <= warningWindow) {
jitter = std::abs(jitter);
}
}
delay += jitter;
// Ensure delay is positive
return std::max(delay, mProfile.mDelay.mBaseDelayUs);
}
int32_t calculateReorderOffset(size_t aPacketSize) {
if (mProfile.mReorder.mReorderPercent <= 0) {