File: normStreamer.cpp

package info (click to toggle)
norm 1.5.9%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,680 kB
  • sloc: cpp: 123,494; xml: 7,536; tcl: 5,460; makefile: 3,442; python: 1,898; java: 1,750; ansic: 642; sh: 21; csh: 8
file content (2354 lines) | stat: -rw-r--r-- 89,336 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354

#include "normApi.h"
#include "protoSocket.h"

#include <stdio.h>       // for printf(), etc
#include <stdlib.h>      // for srand()
#include <string.h>      // for strrchr(), memset(), etc
#include <sys/time.h>    // for gettimeofday()
#include <arpa/inet.h>   // for htons()
#include <fcntl.h>       // for, well, fnctl()
#include <errno.h>       // obvious child
#include <assert.h>      // embarrassingly obvious
#include <sys/mman.h>    // Memory Lock.
#include <sched.h>       // Adjust scheduler (linux)
#include <sys/resource.h> // for setpriority() stuff
#ifdef LINUX
#include <sys/timerfd.h>
#endif // LINUX

const unsigned int LOOP_MAX = 100;

// Setting SHOOT_FIRST to non-zero means that an ACK request
// will be used to advance the acking "watermark" point
// with each message fully written to the transmit stream.
// The alternative "ack later" behavior waits to send a new
// ACK request until any pending flow control ACK requeset
// has completed.  This latter approach favors throughput
// over timeliness of message delivery.  I.e., lower data
// rate applications that are concerned with low-latency message
// delivery can potentially benefit from the "shoot first" 
// behavior while very high throughput applications that want
// to "keep the pipe full as possible" can benefit from the
// "ack later" behavior.  The difference between these behaviors,
// since ACK requests are cued for all messages when flow
// control is _not_ pending, is somewhat subtle and developers
// may want to assess both behaviors for their application.  
// Additionally, limiting ACK request to flow control only is
// another possible approach as well as dynamically updating
// something like the "tx_stream_buffer_count" with each 
// message ACK request initiated could be possible.  The caution
// with the SHOOT_FIRST type strategies and high throughput is
// the application may end up "chasing" the ACK request until
// flow control buffer limits are reached and end up with 
// "dead air" time.  There are always tradeoffs!

//#define SHOOT_FIRST 0

class NormStreamer
{
    public:
        NormStreamer();
        ~NormStreamer();
        
        // some day build these directly into NORM API
        enum CCMode {NORM_FIXED, NORM_CC, NORM_CCE, NORM_CCL};
        
        enum 
        {
            MSG_HEADER_SIZE = 2,    // Big Endian message length header size
            MSG_SIZE_MAX = 65535    // (including length header)  
        };  
            
        void SetOutputFile(FILE* filePtr)
        {
            output_file = filePtr;
            output_fd = fileno(filePtr);
        }
        
        void SetLoopback(bool state)
        {
            loopback = state;
            if (NORM_SESSION_INVALID != norm_session)
                NormSetMulticastLoopback(norm_session, state);
        }  
        void SetFtiInfo(bool state)
        {
            fti_info = state;
            if (NORM_SESSION_INVALID != norm_session)
                NormLimitObjectInfo(norm_session, state);
        }     
        
       void SetAckEx(bool state)
           {ack_ex = state;}
        
        bool EnableUdpRelay(const char* relayAddr, unsigned short relayPort);
        bool EnableUdpListener(unsigned short thePort, const char* groupAddr, const char * interfaceName);
        bool UdpListenerEnabled() const
            {return input_socket.IsOpen();}
        bool UdpRelayEnabled() const
            {return output_socket.IsOpen();}
        
        int GetInputDescriptor() const
            {return (input_socket.IsOpen() ? input_socket.GetHandle() : fileno(input_file));}
        int GetOutputDescriptor() const
            {return (output_socket.IsOpen() ? output_socket.GetHandle() : fileno(output_file));} 
            
        bool OpenNormSession(NormInstanceHandle instance, 
                             const char*        addr,
                             unsigned short     port,
                             NormNodeId         nodeId);
        void CloseNormSession();
        
        void SetNormCongestionControl(CCMode ccMode);
        void SetFlushMode(NormFlushMode flushMode)
            {flush_mode = flushMode;}
        void SetNormTxRate(double bitsPerSecond)
        {
            assert(NORM_SESSION_INVALID != norm_session);
            NormSetTxRate(norm_session, bitsPerSecond);
        }
        void SetNormMulticastInterface(const char* ifaceName)
        {
            assert(NORM_SESSION_INVALID != norm_session);
            NormSetMulticastInterface(norm_session, ifaceName);
        } 
        void SetNormMessageTrace(bool state)
        {
            assert(NORM_SESSION_INVALID != norm_session);
            NormSetMessageTrace(norm_session, state);
        } 
        void AddAckingNode(NormNodeId ackId)
        {
            assert(NORM_SESSION_INVALID != norm_session);
            NormAddAckingNode(norm_session, ackId);
            acking_node_count++;
            norm_acking = true;  // invoke ack-based flow control
        }
        void SetAutoAck(bool enable)
        {
            auto_ack = enable;
            norm_acking = enable;
        }
        
        bool Start(bool sender, bool receiver);
        void Stop()
            {is_running = false;}
        bool IsRunning() const
            {return is_running;}
        void HandleNormEvent(const NormEvent& event);
        
        // Sender methods
        int GetInputFile() const
            {return input_fd;}
        void SetInputReady() 
            {input_ready = true;}
        bool InputReady() const
            {return input_ready;}
        bool InputNeeded() const
            {return input_needed;}
        void ReadInput();
        void ReadInputSocket();
        bool TxPending() const
            {return (!input_needed && (input_index < input_msg_length));}
        bool TxReady() const
            {return (tx_ready && (!norm_acking || (tx_stream_buffer_count < tx_stream_buffer_max)));}
        void SendData();
        unsigned int WriteToStream(const char* buffer, unsigned int numBytes);
        void FlushStream(bool eom, NormFlushMode flushMode);
        
        // Receiver methods
        bool RxNeeded() const
            {return rx_needed;}
        bool RxReady() const
            {return rx_ready;}
        void RecvData();
        int GetOutputFile() const
            {return output_fd;}
        void SetOutputReady()
            {output_ready = true;}
        bool OutputReady() const
            {return output_ready;}
        bool OutputPending() const
            {return (!rx_needed && (output_index < output_msg_length));}
        
        
        void SetOutputBucketRate(double bitsPerSecond) 
        {
            output_bucket_rate = bitsPerSecond / 8.0;  // convert to bytes per second
            output_bucket_interval = 1.0 / output_bucket_rate;
        }
        
        void SetOutputBucketDepth(unsigned int numBytes)
            {output_bucket_depth = numBytes;}
        unsigned int GetOutputBucketDepth() const
            {return output_bucket_depth;}
        
        double GetOutputBucketTimeout() const
        {
            if (0 != output_bucket_depth)
            {
                if (OutputPending())
                {
                    unsigned int pendingBytes = output_msg_length - output_index;
                    if (pendingBytes > output_bucket_count)
                    {
                        return ((double)(pendingBytes - output_bucket_count)) * output_bucket_interval; 
                    }
                    else
                    {
                        return 0.0;
                    }
                }
                else
                {
                    return -1.0;
                }
            }
            else
            {
                return 0.0;
            }   
        }
        
        double GetOutputBucketFillTime() const
        {
            return (output_bucket_count < output_bucket_depth) ?
                ((double)(output_bucket_depth - output_bucket_count)) * output_bucket_interval :
                0.0;     
        }
        
        bool OutputBucketReady() const
        {
            if (0 != output_bucket_depth)
            {
                unsigned int pendingBytes = output_msg_length - output_index;
                return (output_bucket_count >= pendingBytes);
            }
            else
            {
                return true;
            }
        }
        void CreditOutputBucket(double interval)
        {
            if (0 != output_bucket_depth)
            {
                output_bucket_count += interval * output_bucket_rate;
                if (output_bucket_count > output_bucket_depth)
                    output_bucket_count = output_bucket_depth;
            }
        }
        
        void WriteOutput();
        void WriteOutputSocket();
        
        void OmitHeader(bool state) 
            {omit_header = state;}
        
        unsigned long GetInputByteCount() const
            {return input_byte_count;}
        unsigned long GetTxByteCount() const
            {return tx_byte_count;}
        
        // These can only be called post-OpenNormSession()
        void SetSilentReceiver(bool state)
            {NormSetSilentReceiver(norm_session, state);}
        void SetTxLoss(double txloss)
            {NormSetTxLoss(norm_session, txloss);}
        // Set the scheduler for running the app and norm threads.
        static bool BoostPriority();
        
        void SetSegmentSize(unsigned short segmentSize)
            {segment_size = segmentSize;}
        void SetBlockSize(unsigned short blockSize)
            {block_size = blockSize;}
        void SetNumParity(unsigned short numParity)
            {num_parity = numParity;}
        void SetAutoParity(unsigned short autoParity)
            {auto_parity = autoParity;}
        
        void SetStreamBufferSize(unsigned int value)
            {stream_buffer_size = value;}
        void SetTxSocketBufferSize(unsigned int value)
            {tx_socket_buffer_size = value;}
        void SetRxSocketBufferSize(unsigned int value)
            {rx_socket_buffer_size = value;}
        
        void SetInputSocketBufferSize(unsigned int value)
            {input_socket_buffer_size = value;}
        void SetOutputSocketBufferSize(unsigned int value)
            {output_socket_buffer_size = value;}
        
        void SetProbeTOS(UINT8 value)
            {probe_tos = value;}
        
        // Check that sequence numbers increase by one each time.
        // Assumes that sequence number is 8- or 4-byte network-order first 8 bytes of buffer.
        void CheckSequenceNumber(const char* buffer, const char* source);
        void CheckSequenceNumber64(const char* buffer, const char* source);
        void CheckSequenceNumber32(const char* buffer, const char* source);
        void SetCheckSequence(unsigned int value)  // 64 or 32
            {check_sequence = value;}
        
    private:
        NormSessionHandle   norm_session;
        bool                is_multicast;
        UINT8               probe_tos;
        bool                loopback;
        bool                is_running;     
                                                     
        // State variables for reading input messages for transmission
        ProtoSocket         input_socket;    // optional UDP socket to "listen"
        FILE*               input_file;
        int                 input_fd;      // stdin by default  
        bool                input_ready;                       
        bool                input_needed;    
        char                input_buffer[MSG_SIZE_MAX]; 
        unsigned int        input_msg_length;
        unsigned int        input_index;
                                                
        NormObjectHandle    tx_stream;
        bool                tx_ready;
        unsigned int        tx_stream_buffer_max;
        unsigned int        tx_stream_buffer_threshold; // flow control threshold
        unsigned int        tx_stream_buffer_count;
        unsigned int        tx_stream_bytes_remain;
        bool                tx_watermark_pending;
        bool                norm_acking;
        bool                auto_ack;
        unsigned int        acking_node_count;
        bool                tx_ack_pending;
        NormFlushMode       flush_mode;  // TBD - allow for "none", "passive", "active" options
        bool                fti_info;
        bool                ack_ex;
        
        // Receive stream and state variables for writing received messages to output
        NormObjectHandle    rx_stream;
        bool                rx_ready;
        bool                rx_needed;
        bool                msg_sync;
        double              output_bucket_rate;     // bytes per second
        double              output_bucket_interval; // seconds per byte
        unsigned int        output_bucket_depth;    // bytes
        unsigned int        output_bucket_count;    // bytes
        ProtoSocket         output_socket;  // optional UDP socket for recv msg output
        ProtoAddress        relay_addr;     // dest addr for recv msg relay
        FILE*               output_file;
        int                 output_fd;    // stdout by default
        bool                output_ready;
        char                output_buffer[MSG_SIZE_MAX];
        unsigned int        output_msg_length;
        unsigned int        output_index;
        
        
        // These are some options mainly for testing purposes
        bool                omit_header;  // if "true", receive message length header is _not_ written to output
        bool                rx_silent;
        //double              tx_loss;
        unsigned long       input_byte_count;
        unsigned long       tx_byte_count;
        
        unsigned short      segment_size;
        unsigned short      block_size;
        unsigned short      num_parity;
        unsigned short      auto_parity;
        
        unsigned long       stream_buffer_size;
        unsigned int        tx_socket_buffer_size;
        unsigned int        rx_socket_buffer_size;
        unsigned int        input_socket_buffer_size;
        unsigned int        output_socket_buffer_size;
        
        unsigned int        check_sequence;
        uint64_t            sequence_prev;
};  // end class NormStreamer

NormStreamer::NormStreamer()
 : norm_session(NORM_SESSION_INVALID), is_multicast(false), probe_tos(0), loopback(false), is_running(false),
   input_socket(ProtoSocket::UDP), input_file(stdin), input_fd(fileno(stdin)), input_ready(true), 
   input_needed(false), input_msg_length(0), input_index(0),
   tx_stream (NORM_OBJECT_INVALID), tx_ready(true),
   tx_stream_buffer_max(0), tx_stream_buffer_count(0), tx_stream_bytes_remain(0), tx_watermark_pending(false), 
   norm_acking(false), auto_ack(false), acking_node_count(0), tx_ack_pending(false), flush_mode(NORM_FLUSH_ACTIVE),
   fti_info(false), ack_ex(false), rx_stream(NORM_OBJECT_INVALID), rx_ready(false), rx_needed(false), msg_sync(false),
   output_bucket_rate(0.0), output_bucket_interval(0.0), output_bucket_depth(0), output_bucket_count(0),
   output_socket(ProtoSocket::UDP), output_file(stdout), output_fd(fileno(stdout)), output_ready(true), 
   output_msg_length(0), output_index(0), 
   omit_header(false), rx_silent(false), input_byte_count(0), tx_byte_count(0),
   segment_size(1398), block_size(64), num_parity(0), auto_parity(0),
   stream_buffer_size(2*1024*1024),
   tx_socket_buffer_size(0), rx_socket_buffer_size(0),
   input_socket_buffer_size(0), output_socket_buffer_size(0),
   check_sequence(0), sequence_prev(0)
{
}

NormStreamer::~NormStreamer()
{
}

bool NormStreamer::BoostPriority()
{
#ifdef LINUX
    pid_t this_process = getpid() ;
    int policy = SCHED_FIFO ;
    int max_priority = sched_get_priority_max(policy) ;
    struct sched_param schedule_parameters ;
    memset((void*)&schedule_parameters, 0, sizeof(schedule_parameters)) ;
    schedule_parameters.sched_priority = max_priority ;
    int status = sched_setscheduler(this_process, policy, &schedule_parameters) ;
    if (0 != status)
    {
        fprintf(stderr, "%s:=>sched_setscheduler failed (%d), %s\n", __PRETTY_FUNCTION__, errno, strerror(errno) ) ;
        return false ;
    }
    else
    {
        fprintf(stderr, "%s:=>sched_setscheduler set priority to %d for process %u \n", __PRETTY_FUNCTION__, max_priority, this_process ) ;
    }
#else
    // (TBD) Do something differently if "pthread sched param"?
    if (0 != setpriority(PRIO_PROCESS, getpid(), -20))
    {
        PLOG(PL_ERROR, "NormStreamer::BoostPriority() error: setpriority() error: %s\n", GetErrorString());
        return false;
    }
#endif // if/else LINUX
    return true;
}

#ifndef ntohll
//Convert net-order to host-order.
uint64_t ntohll(uint64_t value)
{
    static const int betest = 1 ;
    union MyUnion
    {
        uint64_t i64;
        uint32_t i32[2];
    };

    uint64_t rval = value;
    bool host_is_little_endian =  ( 1 == (int)(*(char*)&betest) ) ;
    if ( host_is_little_endian )
    {

        MyUnion u;
        u.i64 = value;
        uint32_t temp = u.i32[0];
        u.i32[0] = ntohl(u.i32[1]);
        u.i32[1] = ntohl(temp);
        rval = u.i64;
    }
    return rval ;
}
#endif // !nothll

void NormStreamer::CheckSequenceNumber64(const char* buffer, const char* source)
{
    uint64_t temp;
    memcpy((void*)&temp, (void*)buffer, sizeof(temp));
    uint64_t sequence = ntohll(temp);
    if (0 != sequence_prev)
    {
        int64_t delta = (int64_t)(sequence - sequence_prev);
        if (1 != delta)
        {
            fprintf(stderr, "normStreamer: %s dropped %lu packets seq:%lu seq_prev:%lu\n",
                            source, (unsigned long)delta, (unsigned long)sequence,
                            (unsigned long)sequence_prev);
        }
    }
    sequence_prev = sequence;
}  // end NormStreamer::CheckSequenceNumber64()

void NormStreamer::CheckSequenceNumber32(const char* buffer, const char* source)
{
    uint32_t temp;
    memcpy((void*)&temp, (void*)buffer, sizeof(temp));
    uint32_t sequence = ntohll(temp);
    if (0 != sequence_prev)
    {
        int32_t delta = (int32_t)(sequence - sequence_prev);
        if (1 != delta)
        {
            fprintf(stderr, "normStreamer: %s dropped %lu packets seq:%lu seq_prev:%lu\n",
                            source, (unsigned long)delta, (unsigned long)sequence,
                            (unsigned long)sequence_prev);
        }
    }
    sequence_prev = sequence;
}  // end NormStreamer::CheckSequenceNumber32()

void NormStreamer::CheckSequenceNumber(const char* buffer, const char* source)
{
    switch (check_sequence)
    {
        case 32:
            CheckSequenceNumber32(buffer, source);
            break;
        case 64:
            CheckSequenceNumber64(buffer, source) ;
            break;
        default:
            break;
    }
}  // end NormStreamer::CheckSequenceNumber()

bool NormStreamer::EnableUdpRelay(const char* relayAddr, unsigned short relayPort)
{
    if (!output_socket.Open())
    {
        fprintf(stderr, "normStreamer error: unable to open 'relay' socket\n");
        return false ;
    }
    if (!output_socket.SetTxBufferSize(output_socket_buffer_size))
    {
        fprintf(stderr, "normStreamer warning: unable to set desired 'relay' socket buffer size (retrieved value:%u)\n", 
                        output_socket.GetTxBufferSize());
    }
    if (!relay_addr.ResolveFromString(relayAddr))
    {
        fprintf(stderr, "normStreamer error: invalid relay address\n");
        output_socket.Close();
        return false;
    }
    relay_addr.SetPort(relayPort);  // TBD - validate port number??
    return true;
}  // end bool EnableUdpRelay()

bool NormStreamer::EnableUdpListener(unsigned short thePort, const char* groupAddr, const char * interfaceName)
{
    if (!input_socket.Open(thePort))
    {
        fprintf(stderr, "normStreamer error: unable to open 'listen' socket on port %hu\n", thePort);
        return false;
    }
    if (!input_socket.SetRxBufferSize(input_socket_buffer_size))
    {
        fprintf(stderr, "normStreamer error: unable to set desired 'listen' socket buffer size\n");
        return false;
    }
    if (NULL != groupAddr)
    {
        ProtoAddress addr;
        if (!addr.ResolveFromString(groupAddr) || (!addr.IsMulticast()))
        {
            fprintf(stderr, "normStreamer error: invalid 'listen' group address\n");
            input_socket.Close();
            return false ;
        }
        if (!input_socket.JoinGroup(addr, interfaceName))
        {
            fprintf(stderr, "normStreamer error: unable to join 'listen' group address\n");
            input_socket.Close();
            return false;
        }
    }
    return true;
}  // end NormStreamer::EnableUdpListener()

bool NormStreamer::OpenNormSession(NormInstanceHandle instance, const char* addr, unsigned short port, NormNodeId nodeId)
{
    if (NormIsUnicastAddress(addr))
        is_multicast = false;
    else
        is_multicast = true;
    norm_session = NormCreateSession(instance, addr, port, nodeId);
    if (NORM_SESSION_INVALID == norm_session)
    {
        fprintf(stderr, "normStreamer error: unable to create NORM session\n");
        return false;
    }
    if (is_multicast)
    {
        NormSetRxPortReuse(norm_session, true);
        if (loopback)
            NormSetMulticastLoopback(norm_session, true);
    }
    
    // Set some default parameters (maybe we should put parameter setting in Start())
    NormSetDefaultSyncPolicy(norm_session, NORM_SYNC_STREAM);
    
    if (!is_multicast)
        NormSetDefaultUnicastNack(norm_session, true);
    
    NormSetTxRobustFactor(norm_session, 20);
    
    NormSetGrttProbingTOS(norm_session, probe_tos);
    
    NormSetFragmentation(norm_session, true);  // so that IP ID gets set for SMF DPD
    
    return true;
}  // end NormStreamer::OpenNormSession()

void NormStreamer::CloseNormSession()
{
    if (NORM_SESSION_INVALID == norm_session) return;
    NormDestroySession(norm_session);
    norm_session = NORM_SESSION_INVALID;
}  // end NormStreamer::CloseNormSession()

void NormStreamer::SetNormCongestionControl(CCMode ccMode)
{
    assert(NORM_SESSION_INVALID != norm_session);
    switch (ccMode)
    {
        case NORM_CC:  // default TCP-friendly congestion control
            NormSetEcnSupport(norm_session, false, false, false);
            break;
        case NORM_CCE: // "wireless-ready" ECN-only congestion control
            NormSetEcnSupport(norm_session, true, true);
            break;
        case NORM_CCL: // "loss tolerant", non-ECN congestion control
            NormSetEcnSupport(norm_session, false, false, true);
            break;
        case NORM_FIXED: // "fixed" constant data rate
            NormSetEcnSupport(norm_session, false, false, false);
            break;
    }
    if (NORM_FIXED != ccMode)
        NormSetCongestionControl(norm_session, true);
    else
        NormSetCongestionControl(norm_session, false);
}  // end NormStreamer::SetNormCongestionControl()

bool NormStreamer::Start(bool sender, bool receiver)
{
    // Note the session NORM buffer size is set the same s stream_buffer_size
    unsigned int bufferSize = stream_buffer_size;
    if (receiver)
    {
        if (!NormPreallocateRemoteSender(norm_session, bufferSize, segment_size, block_size, num_parity, stream_buffer_size))
            fprintf(stderr, "normStreamer warning: unable to preallocate remote sender\n");
        fprintf(stderr, "normStreamer: receiver ready.\n");
        if (!NormStartReceiver(norm_session, bufferSize))
        {
            fprintf(stderr, "normStreamer error: unable to start NORM receiver\n");
            return false;
        }
        if (0 != mlockall(MCL_CURRENT | MCL_FUTURE))
            fprintf(stderr, "normStreamer error: failed to lock memory for receiver.\n");
        if (0 != rx_socket_buffer_size)
            NormSetRxSocketBuffer(norm_session, rx_socket_buffer_size);
        rx_needed = true;
        rx_ready = false;
    }
    if (sender)
    {
        NormSetGrttEstimate(norm_session, 0.001);
        //NormSetGrttMax(norm_session, 0.100);
        NormSetBackoffFactor(norm_session, 0);
        if (norm_acking)
        {   
            // ack-based flow control enabled on command-line, 
            // so disable timer-based flow control
            NormSetFlowControl(norm_session, 0.0);
            NormTrackingStatus trackingMode = auto_ack? NORM_TRACK_RECEIVERS : NORM_TRACK_NONE;
            NormSetAutoAckingNodes(norm_session, trackingMode);
            if (auto_ack && (0 == acking_node_count))
            {
                // This allows for the receivrer(s) to start after the sender
                // as the sender will persistently send ack requests until
                // a receiver responds.
                NormAddAckingNode(norm_session, NORM_NODE_NONE);
            }
        }
        // Pick a random instance id for now
        struct timeval currentTime;
        gettimeofday(&currentTime, NULL);
        srand(currentTime.tv_usec);  // seed random number generator
        NormSessionId instanceId = (NormSessionId)rand();
        if (fti_info)
            NormLimitObjectInfo(norm_session, true);
        if (!NormStartSender(norm_session, instanceId, bufferSize, segment_size, block_size, num_parity))
        {
            fprintf(stderr, "normStreamer error: unable to start NORM sender\n");
            if (receiver) NormStopReceiver(norm_session);
            return false;
        }
        if (auto_parity > 0)
            NormSetAutoParity(norm_session, auto_parity < num_parity ? auto_parity : num_parity);
        if (0 != tx_socket_buffer_size)
            NormSetTxSocketBuffer(norm_session, tx_socket_buffer_size);
        if (NORM_OBJECT_INVALID == (tx_stream = NormStreamOpen(norm_session, stream_buffer_size)))
        {
            fprintf(stderr, "normStreamer error: unable to open NORM tx stream\n");
            NormStopSender(norm_session);
            if (receiver) NormStopReceiver(norm_session);
            return false;
        }
        else
        {
            if (0 != mlockall(MCL_CURRENT|MCL_FUTURE))
                fprintf(stderr, "normStreamer warning: failed to lock memory for sender.\n");
        }
        tx_stream_buffer_max = NormGetStreamBufferSegmentCount(bufferSize, segment_size, block_size);
        tx_stream_buffer_max -= block_size;  // a little safety margin (perhaps not necessary)
        tx_stream_buffer_threshold = tx_stream_buffer_max / 8;
        tx_stream_buffer_count = 0;
        tx_stream_bytes_remain = 0;
        tx_watermark_pending = false;
        tx_ack_pending = false;
        tx_ready = true;
        input_index = input_msg_length = 0;
        input_needed = true;
        input_ready = true;
    }
    is_running = true;
    return true;
}  // end NormStreamer::Start();

void NormStreamer::ReadInputSocket()
{
    unsigned int loopCount = 0;
    NormSuspendInstance(NormGetInstance(norm_session));
    while (input_needed && input_ready && (loopCount < LOOP_MAX))
    {
        loopCount++;
        unsigned int numBytes = MSG_SIZE_MAX - MSG_HEADER_SIZE;
        ProtoAddress srcAddr;
        if (input_socket.RecvFrom(input_buffer+MSG_HEADER_SIZE, numBytes, srcAddr))
        {
            if (0 == numBytes)
            {
                input_ready = false;
                break;
            }
            input_index = 0;
            input_msg_length = numBytes + MSG_HEADER_SIZE;
            input_byte_count += input_msg_length;
            unsigned short msgSize = input_msg_length;;
            msgSize = htons(msgSize);
            memcpy(input_buffer, &msgSize, MSG_HEADER_SIZE);
            input_needed = false;
            if (TxReady()) SendData();
        }
        else
        {
            // TBD - handle error?
            input_ready = false;
        }
    }
    NormResumeInstance(NormGetInstance(norm_session));
}  // end NormStreamer::ReadInputSocket()

void NormStreamer::ReadInput()
{
    if (UdpListenerEnabled()) return ReadInputSocket();
    // The loop count makes sure we don't spend too much time here
    // before going back to the main loop to handle NORM events, etc
    unsigned int loopCount = 0;
    NormSuspendInstance(NormGetInstance(norm_session));
    while (input_needed && input_ready && (loopCount < LOOP_MAX))
    {
        loopCount++;
        //if (100 == loopCount)
        //    fprintf(stderr, "normStreamer ReadInput() loop count max reached\n");
        unsigned int numBytes;
        if (input_index < MSG_HEADER_SIZE)
        {
            // Reading message length header for next message to send
            numBytes = MSG_HEADER_SIZE - input_index;
        }
        else
        {
            // Reading message body
            assert(input_index < input_msg_length);
            numBytes = input_msg_length - input_index;
        }
        ssize_t result = read(input_fd, input_buffer + input_index, numBytes);
        if (result > 0)
        {
            input_index += result;
            input_byte_count += result;
            if (MSG_HEADER_SIZE == input_index)
            {
                // We have now read the message size header
                // TBD - support other message header formats?
                // (for now, assume 2-byte message length header)
                uint16_t msgSize ;
                memcpy(&msgSize, input_buffer, MSG_HEADER_SIZE);
                msgSize = ntohs(msgSize);
                input_msg_length = msgSize;
            }
            else if (input_index == input_msg_length)
            {
                // Message input complete
                input_index = 0;  // reset index for transmission phase
                input_needed = false;
                if (TxReady()) SendData();
            }   
            else
            {
                // Still need more input
                // (wait for next input notification to read more)
                input_ready = false;
            }
        }
        else if (0 == result)
        {
            // end-of-file reached, TBD - trigger final flushing and wrap-up
            fprintf(stderr, "normStreamer: input end-of-file detected ...\n");
            NormStreamClose(tx_stream, true);
            if (norm_acking)
            {
                if (ack_ex)
                {
                    const char* req = "Hello, acker";
                    NormSetWatermarkEx(norm_session, tx_stream, req, strlen(req) + 1, true);
                }
                else
                {
                    NormSetWatermark(norm_session, tx_stream, true);
                }
                tx_ack_pending = false;
            }
            input_needed = false;
        }
        else
        {
            switch (errno)
            {
                case EINTR:
                    continue;  // interrupted, try again
                case EAGAIN:
                    // input starved, wait for next notification
                    input_ready = false;
                    break;
                default:
                    // TBD - handle this better
                    perror("normStreamer error reading input");
                    break;
            }
            break;
        }
    }  // end while (input_needed && input_ready)
    NormResumeInstance(NormGetInstance(norm_session));
}  // end NormStreamer::ReadInput()

void NormStreamer::SendData()
{
    while (TxReady() && !input_needed)
    {
        // Note WriteToStream() or FlushStream() will set "tx_ready" to 
        // false upon flow control thus negating TxReady() status
        assert(input_index < input_msg_length);
        assert(input_msg_length);
        if ((0 != check_sequence) && (0 == input_index))
            CheckSequenceNumber(input_buffer+MSG_HEADER_SIZE, __func__);
        input_index += WriteToStream(input_buffer + input_index, input_msg_length - input_index);
        if (input_index == input_msg_length)
        {
            // Complete message was sent, so set eom and optionally flush
            if (NORM_FLUSH_NONE != flush_mode)
                FlushStream(true, flush_mode); 
            else
                NormStreamMarkEom(tx_stream);
            input_index = input_msg_length = 0;
            input_needed = true;
        }
        else
        {
            //fprintf(stderr, "SendData() impeded by flow control\n");
        }
    }  // end while (TxReady() && !input_needed)
}  // end NormStreamer::SendData()

unsigned int NormStreamer::WriteToStream(const char* buffer, unsigned int numBytes)
{
    unsigned int bytesWritten;
    if (norm_acking)
    {
        // This method uses NormStreamWrite(), but limits writes by explicit ACK-based flow control status
        if (tx_stream_buffer_count < tx_stream_buffer_max)
        {
            // 1) How many buffer bytes are available?
            unsigned int bytesAvailable = segment_size * (tx_stream_buffer_max - tx_stream_buffer_count);
            bytesAvailable -= tx_stream_bytes_remain;  // unflushed segment portion
            if (bytesAvailable < numBytes) numBytes = bytesAvailable;
            assert(numBytes);
            // 2) Write to the stream
            bytesWritten = NormStreamWrite(tx_stream, buffer, numBytes);
            tx_byte_count += bytesWritten;
            // 3) Update "tx_stream_buffer_count" accordingly
            unsigned int totalBytes = bytesWritten + tx_stream_bytes_remain;
            unsigned int numSegments = totalBytes / segment_size;
            tx_stream_bytes_remain = totalBytes % segment_size;
            tx_stream_buffer_count += numSegments;
            
            //assert(bytesWritten == numBytes);  // this could fail if timer-based flow control is left enabled
            // 3) Check if we need to issue a watermark ACK request?
            if (!tx_watermark_pending && (tx_stream_buffer_count >= tx_stream_buffer_threshold))
            {
                // Initiate flow control ACK request
                //fprintf(stderr, "write-initiated flow control ACK REQUEST\n");
                if (ack_ex)
                {
                    const char* req = "Hello, acker";
                    NormSetWatermarkEx(norm_session, tx_stream, req, strlen(req) + 1);
                }
                else
                {
                    NormSetWatermark(norm_session, tx_stream);
                }
                
                tx_watermark_pending = true;
                tx_ack_pending = false;
            }
        }
        else
        {
            fprintf(stderr, "normStreamer: sender flow control limited\n");
            return 0;
        }
    }
    else
    {
        bytesWritten = NormStreamWrite(tx_stream, buffer, numBytes);
        tx_byte_count += bytesWritten;
    }
    if (bytesWritten != numBytes) //NormStreamWrite() was (at least partially) blocked
    {
        //fprintf(stderr, "NormStreamWrite() blocked by flow control ...\n");
        tx_ready = false;
    }
    return bytesWritten;
}  // end NormStreamer::WriteToStream()

void NormStreamer::FlushStream(bool eom, NormFlushMode flushMode)
{ 
    if (norm_acking)
    {
        bool setWatermark = false;
        if (0 != tx_stream_bytes_remain)
        {
            // The flush will force the runt segment out, so we increment our buffer usage count
            // (and initiate flow control watermark ack request if buffer mid-point threshold exceeded
            tx_stream_buffer_count++;
            tx_stream_bytes_remain = 0;
            if (!tx_watermark_pending && (tx_stream_buffer_count >= tx_stream_buffer_threshold))
            {
                setWatermark = true;
                tx_watermark_pending = true;
                //fprintf(stderr, "flush-initiated flow control ACK REQUEST\n");
            }
        }
        // The check for "tx_watermark_pending" here prevents a new watermark
        // ack request from being set until the pending flow control ack is 
        // received. This favors avoiding dead air time over saving "chattiness"
        if (setWatermark)
        {
            // Flush passive since watermark will invoke active request
            // (TBD - do non-acking nodes NACK to watermark when not ack target?)
            NormStreamFlush(tx_stream, eom, NORM_FLUSH_PASSIVE);
        }
        else if (tx_watermark_pending)
        {
            // Pre-existing pending flow control watermark ack request
#if SHOOT_FIRST
            // Go ahead and set a fresh watermark
            // TBD - not sure this mode works properly ... may need to 
            // keep track of unacknowledged byte count and decrement accordingly
            // when ack arrives
            NormStreamFlush(tx_stream, eom, NORM_FLUSH_PASSIVE);
            setWatermark = true;
#else // ACK_LATER
            // Wait until flow control ACK is received before issuing another ACK request
            NormStreamFlush(tx_stream, eom, flushMode);
            tx_ack_pending = true;  // will call NormSetWatermark() upon flow control ack completion
#endif
        }
        else
        {
            // Since we're acking, use active ack request in lieu of active flush
            NormStreamFlush(tx_stream, eom, NORM_FLUSH_PASSIVE);
            setWatermark = true;
        }
        if (setWatermark) 
        {
            if (ack_ex)
            {
                const char* req = "Hello, acker";
                NormSetWatermarkEx(norm_session, tx_stream, req, strlen(req) + 1, true);
            }
            else
            {
                NormSetWatermark(norm_session, tx_stream, true);
            }
            tx_ack_pending = false;
        }
    }
    else
    {
        NormStreamFlush(tx_stream, eom, flushMode);
    }
}  // end NormStreamer::FlushStream()

void NormStreamer::RecvData()
{    
    // The loop count makes sure we don't spend too much time here
    // before going back to the main loop to handle NORM events, etc
    unsigned int loopCount = 0;
    // Reads data from rx_stream to available output_buffer
    NormSuspendInstance(NormGetInstance(norm_session));
    while (rx_needed && rx_ready && (loopCount < LOOP_MAX))
    {
        loopCount++;
        //if (100 == loopCount)
        //    fprintf(stderr, "normStreamer RecvData() loop count max reached.\n");
        // Make sure we have msg_sync (TBD - skip this for byte streaming)
        if (!msg_sync)
        {
            msg_sync = NormStreamSeekMsgStart(rx_stream);
            if (!msg_sync) 
            {
                rx_ready = false;
                break;  // wait for next NORM_RX_OBJECT_UPDATED to re-sync
            }
        }
        unsigned int bytesWanted;
        if (output_index < MSG_HEADER_SIZE)
        {
            // Receiving message header
            bytesWanted = MSG_HEADER_SIZE - output_index;
        }
        else
        {
            // Receiving message body
            assert(output_index < output_msg_length);
            bytesWanted = output_msg_length - output_index;
        }
        unsigned bytesRead = bytesWanted;
        if (!NormStreamRead(rx_stream, output_buffer + output_index, &bytesRead))
        {
            // Stream broken (should _not_ happen if norm_acking flow control)
            //fprintf(stderr, "normStreamer error: BROKEN stream detected, re-syncing ...\n");
            msg_sync = false;
            output_index = output_msg_length = 0;
            continue;
        }
        output_index += bytesRead;
        /*if (0 == bytesRead)
        {
            rx_ready = false;
        } 
        else*/ if (bytesRead != bytesWanted)
        {
            //continue;
            rx_ready = false;  // didn't get all we need
        }
        else if (MSG_HEADER_SIZE == output_index)
        {
            // We have now read the message size header
            // TBD - support other message header formats?
            // (for now, assume 2-byte message length header)
            uint16_t msgSize ;
            memcpy(&msgSize, output_buffer, MSG_HEADER_SIZE);
            output_msg_length = ntohs(msgSize);
        }
        else if (output_index == output_msg_length)
        {
            // Received full message
            rx_needed = false;
            output_index = 0;  // reset for writing to output
            if (output_ready && OutputBucketReady())
                WriteOutput();
        }
    }
    NormResumeInstance(NormGetInstance(norm_session));
    
}  // end NormStreamer::RecvData()

void NormStreamer::WriteOutputSocket()
{
    if (output_ready && !rx_needed)
    {
        assert(output_index < output_msg_length);
        unsigned int payloadSize = output_msg_length - MSG_HEADER_SIZE;
        unsigned int numBytes = payloadSize;
        if ((0 != check_sequence))
            CheckSequenceNumber(output_buffer+MSG_HEADER_SIZE, __func__);
        if (output_socket.SendTo(output_buffer+MSG_HEADER_SIZE, numBytes, relay_addr))
        {
            if (numBytes != payloadSize)
            {
                // sendto() was blocked
                output_ready = false;
                return;
            }
            if (0 != output_bucket_depth)
            {
                // Debit output token bucket since it's active
                ASSERT(output_bucket_count >= payloadSize);
                output_bucket_count -= payloadSize;
            }
            rx_needed = true;
            output_index = output_msg_length = 0;
        }
        else
        {
            output_ready = false;
        }
    }
}  // end NormStreamer::WriteOutputSocket()

void NormStreamer::WriteOutput()
{
    if (UdpRelayEnabled()) 
    {
         WriteOutputSocket();
         return;
    }
    while (output_ready && !rx_needed)
    {
        assert(output_index < output_msg_length);
        if ((0 != check_sequence) && (0 == output_index))
            CheckSequenceNumber(output_buffer+MSG_HEADER_SIZE,__func__);
        ssize_t result = write(output_fd, output_buffer + output_index, output_msg_length - output_index);
        if (result >= 0)
        {
            if (0 != output_bucket_depth)
            {
                // Debit output token bucket since it's active
                if (result > output_bucket_count)
                    TRACE("result:%d output_bucket_count:%u\n", (int)result, output_bucket_count);
                ASSERT(output_bucket_count >= result);
                output_bucket_count -= result; 
            }
            output_index += result;
            if (output_index == output_msg_length)
            {
                // Complete message written
                rx_needed = true;
                output_index = output_msg_length = 0;
                if ((NORM_OBJECT_INVALID == tx_stream) && (NORM_OBJECT_INVALID == rx_stream)) 
                    Stop();  // receive stream was terminated by sender
            }
            else
            {
                output_ready = false;
            }
        }
        else
        {
            switch (errno)
            {
                case EINTR:
                    perror("normStreamer output EINTR");
                    continue;  // interupted, try again
                case EAGAIN:
                    // output blocked, wait for next notification
                    //perror("normStreamer output blocked");
                    output_ready = false;
                    break;
                default:
                    perror("normStreamer error writing output");
                    break;
            }
            break;
        }
    }
}  // end NormStreamer::WriteOutput()

void NormStreamer::HandleNormEvent(const NormEvent& event)
{
    switch (event.type)
    {
        case NORM_TX_QUEUE_EMPTY:
            //TRACE("normStreamer: flow control empty ...\n");
            tx_ready = true;
            break;
        case NORM_TX_QUEUE_VACANCY:
            //TRACE("normStreamer: flow control relieved ...\n");
            tx_ready = true;
            break;
            
        case NORM_GRTT_UPDATED:
            //fprintf(stderr, "new GRTT = %lf\n", NormGetGrttEstimate(norm_session));
            break;
            
        case NORM_ACKING_NODE_NEW:
            if (0 == acking_node_count)
                NormRemoveAckingNode(event.session, NORM_NODE_NONE);
            acking_node_count++;
            break;
            
        case NORM_TX_WATERMARK_COMPLETED:
            TRACE("NORM_TX_WATERMARK_COMPLETED ...\n");
            if (NORM_ACK_SUCCESS == NormGetAckingStatus(norm_session))
            {
                //fprintf(stderr, "WATERMARK COMPLETED\n");
                if (0 == acking_node_count)
                {
                    // Keep probing until some receiver shows up
                    NormResetWatermark(norm_session);
                }                
                else if (tx_watermark_pending)
                {
                    // Flow control ack request was pending.
                    tx_watermark_pending = false;
                    tx_stream_buffer_count -= tx_stream_buffer_threshold;
                    //fprintf(stderr, "flow control ACK completed\n");
                    if (tx_ack_pending)
                    {
                        if (ack_ex)
                        {
                            const char* req = "Hello, acker";
                            NormSetWatermarkEx(norm_session, tx_stream, req, strlen(req) + 1, true);
                        }
                        else
                        {
                            NormSetWatermark(norm_session, tx_stream, true);
                        }
                        tx_ack_pending = false;
                    }
                }
            }
            else
            {
                // TBD - we could see who didn't ACK and possibly remove them
                //       from our acking list.  For now, we are infinitely
                //       persistent by always resetting the watermark ack request
                //       For example, an application could make a decision at this
                //       point, depending upon some count of ACK request failures
                //       to choose to remove a previously included receiver.
                fprintf(stderr, "flow control watermark reset\n");
                if (tx_ack_pending)
                {
                    // May as well advance the ack request point
                    if (ack_ex)
                    {
                        const char* req = "Hello, acker";
                        NormSetWatermarkEx(norm_session, tx_stream, req, strlen(req) + 1, true);
                    }
                    else
                    {
                        NormSetWatermark(norm_session, tx_stream, true);
                    }
                    tx_ack_pending = false;
                }
                else
                {
                    NormResetWatermark(norm_session);
                }
            }
            if (ack_ex)
            {
                // This iterates through the acking nodes looking for responses
                // to our application-defined NormSetWatermarkEx() request
                NormAckingStatus ackingStatus;
                NormNodeId nodeId = NORM_NODE_NONE;  // this inits NormGetNextAckingNode() iteration
                while (NormGetNextAckingNode(event.session, &nodeId, &ackingStatus))
                {
                    if (NORM_ACK_SUCCESS == ackingStatus)
                    {
                        // This node acked, so look for AckEx response
                        // In our example/test case here, we use strings for the content
                        char buffer[256];
                        buffer[0] = '\0';
                        unsigned int buflen = 256;
                        if (NormGetAckEx(event.session, nodeId, buffer, &buflen))
                            fprintf(stderr, "Received APP_ACK from node>%u \"%s\"\n", nodeId, buffer);
                    }
                }
            }
            break; 
            
        case NORM_TX_OBJECT_PURGED:
            // tx_stream graceful close completed
            NormStopSender(norm_session);
            tx_stream = NORM_OBJECT_INVALID;
            if (NORM_OBJECT_INVALID == rx_stream) Stop();
            break;
        
        case NORM_REMOTE_SENDER_INACTIVE:
            //fprintf(stderr, "REMOTE SENDER INACTIVE node: %u\n", NormNodeGetId(event.sender));
            //NormNodeDelete(event.sender);
            break;
            
        case NORM_RX_OBJECT_NEW:
            if ((NORM_OBJECT_INVALID == rx_stream) &&
                (NORM_OBJECT_STREAM == NormObjectGetType(event.object)))
            {
                rx_stream = event.object;
                rx_ready = true;
                // By setting initial "msg_sync" to true, we can detect when 
                // stream beginning was missed (for NORM_SYNC_STREAM only)
                msg_sync = false;
                rx_needed = true;
                output_index = output_msg_length = 0;
            }
            else
            {
                fprintf(stderr, "normStreamer warning: NORM_RX_OBJECT_NEW while already receiving?!\n");
            }
            
        case NORM_RX_OBJECT_UPDATED:
            rx_ready = true;
            break;
        
        case NORM_RX_OBJECT_ABORTED:
            //fprintf(stderr, "NORM_RX_OBJECT_ABORTED\n");// %hu\n", NormObjectGetTransportId(event.object));
            rx_stream = NORM_OBJECT_INVALID;
            rx_needed = false;
            rx_ready = false;
            break;
            
        case NORM_RX_OBJECT_COMPLETED:
            // Rx stream has closed 
            // TBD - set state variables so any pending output is
            //       written out and things shutdown if not sender, too
            fprintf(stderr, "normStreamer: rx_stream completed.\n");
            // if rx_needed is true, all output has been written
            if (rx_needed && (NORM_OBJECT_INVALID == tx_stream))
            {
                NormNodeHandle sender = NormObjectGetSender(rx_stream);
                // Wait a couple of GRTT's to ACK sender
                double exitTime = 20.0 * NormNodeGetGrtt(sender);
                if (exitTime < 1.0) exitTime = 1.0;
                fprintf(stderr, "normStreamer reception completed, exiting in %f seconds ...\n", (float)exitTime);
                sleep(exitTime);  // TBD - use our user-defined NormSession timeout instead? (retaining rx_stream)
                if (rx_needed && (NORM_OBJECT_INVALID == tx_stream)) 
                    Stop();  
            }
            rx_stream = NORM_OBJECT_INVALID;
            rx_ready = false;
            rx_needed = false;
            break;
            
        case NORM_RX_ACK_REQUEST:
        {
            char buffer[256];
            buffer[0] = '\0';
            unsigned int buflen = 256;
            NormNodeGetWatermarkEx(event.sender, buffer, &buflen);
            fprintf(stderr, "Received NORM_RX_ACK_REQUEST: \"%s\"\n", buffer);
            // Send a reply
            const char* ack = "Yes, master";
            NormNodeSendAckEx(event.sender, ack, strlen(ack) + 1);
            break;
        }
            
        default:
            break;     
    }
    //NormReleasePreviousEvent(NormGetInstance(norm_session));
        
}  // end NormStreamer::HandleNormEvent()

void Usage()
{
    fprintf(stderr, "Usage: normStreamer id <nodeIdInteger> {send|recv} [addr <addr>[/<port>]]\n"
                    "                    [interface <name>] [loopback] [info] [ptos <value>] [ex]\n"
                    "                    [cc|cce|ccl|rate <bitsPerSecond>]\n"
                    "                    [ack auto|<node1>[,<node2>,...]]\n"
                    "                    [flush {none|passive|active}]\n"
                    "                    [listen [<mcastAddr>/]<port>] [linterface <name>]\n"
                    "                    [relay <dstAddr>/<port>] [limit [<rate>/]<depth>]\n"
                    "                    [output <device>] [boost] [debug <level>] [trace]\n"
                    "                    [log <logfile>] [segment <bytes>] [block <count>]\n"
                    "                    [parity <count>] [auto <count>]\n"
                    "                    [insockbuffer <bytes>] [outsockbuffer <bytes>]\n"
                    "                    [txsockbuffer <bytes>] [rxsockbuffer <bytes>]\n"
                    "                    [streambuffer <bytes>]\n"
                    "                    [check64 | check32]\n"
                    "                    [omit] [silent] [txloss <lossFraction>]\n");
}  // end Usage()

void PrintHelp()
{
    fprintf(stderr, "\nHelp for normStreamer:\n\n") ;
    fprintf(stderr,
            "The 'normStreamer' application sends messages from STDIN (or a listening UDP socket) to one or more\n"
            "receiving nodes using the NORM protocol.  Received messages are output to STDOUT (or relayed to\n"
            "to a UDP destination address/port).  Key command line options are:\n\n"
            "   id <nodeId>             -- Specifies the node id for the local NORM instance (required)\n"
            "   send | recv             -- Specifies whether this node will be a sender and/or receiver (must choose  at least one)\n"
            "   addr <addr>[/<port>]    -- specifies the network address over which to send/receive NORM protocol\n"
            "   interface <name>        -- Specifies the name of the network interface on which to conduct NORM protocol\n"
            "                              (e.g., 'eth0')\n"
            "   loopback                -- Enables 'loopback' sessions on the same host machine.  Required for multicast loopback.\n"
            "   ptos <value>            -- Set special IP traffic class (TOS) for GRTT probing and acknowledgments\n"
            "   info                    -- Limits FTI header extension to NORM_INFO message only (reduced overhead)\n"
            "   rate <bitsPerSecond>    -- sets fixed sender rate (and receiver token bucket rate if 'limit' option is used)\n"
            "   [cc|cce|ccl]            -- Enables optional NORM congestion control mode (overrides 'rate')\n"
            "   ack [<nodeId list>]     -- Instructs sender to request positive acknowledgement from listed receiver nodes\n"
            "   flush [<flushMode>]     -- Choose 'none', 'passive', or 'active' message stream flushing mode.  If 'none',\n"
            "                              NORM_DATA packets will always be packed with message content up to the full\n"
            "                              segment size.  If 'passive', short NORM_DATA packets will be sent to transmit\n"
            "                              any messages as soon as possible.  If 'active', NORM stream will be flushed\n"
            "                              on a per-message basis as with 'passive' mode, but positive acknowledgment will\n"
            "                              _also_ be requested if a list of acking receiver node ids has beeen provided.\n"
            "   listen [<addr>/]<port>  -- Specifies the port and optional multicast address which the sender uses to listen\n"
            "                              for UDP packets to transmit to the receiver(s) via the NORM protocol\n"
            "   linterface <name>       -- Specifies the name of the network interface on which to listen for UDP packet\n"
            "                              payloads to send to the receiver(s) via NORM protocol\n"
            "   relay <dstAddr>/<port>  -- Specifies the address/port for which to relay (as UDP datagrams) received messages\n"
            "   limit [<rate>/]<depth>  -- Token bucket rate/depth for optional receiver output limiter (smooths bursty output\n" 
            "                              upon NORM loss recovery).  When UDP 'relay' is used, this option is useful to avoid\n"
            "                              overly bursty UDP output.  The <rate> is in units of bits/second and the <depth> is\n"
            "                              in units of bytes.  If not specified  here, the value set by 'rate' command is used\n"
            "                              as the token bucket rate.\n"
            "   check64 | check32       -- Enables checking that packet sequence numbers in the first 4/8 bytes of received\n"
            "                              packets increment properly (optional)\n"
            "   insockbuffer <bytes>    -- Specifies the size of the 'listen' UDP socket buffer (optional).\n"
            "   outsockbuffer <bytes>   -- Specifies the size of the 'relay' UDP socket buffer (optional).\n"
            "   txsockbuffer <bytes>    -- Specifies the size of the NORM/UDP transmit socket buffer (optional).\n"
            "   rxsockbuffer <bytes>    -- Specifies the size of the NORM/UDP receive socket buffer (optional).\n"
            "   streambuffer <bytes>    -- Specifies the size of the NORM stream buffer (optional).\n\n");
    Usage();

}  // end PrintHelp()

int main(int argc, char* argv[])
{
    // REQUIRED parameters initiailization
    NormNodeId nodeId = NORM_NODE_NONE;
    bool send = false;
    bool recv = false;
    
    char sessionAddr[64];
    strcpy(sessionAddr, "224.1.2.3");
    unsigned int sessionPort = 6003;
    
    char listenAddr[64];            // UDP :listen" multicast addr 
    listenAddr[0] = '\0';
    unsigned int listenPort = 0;    // UDP "listen" port for UDP "listen"
    const char* listenIface = NULL; // UDP "listen" interface
    
    char relayAddr[64]; 
    relayAddr[0] = '\0';
    unsigned int relayPort = 0;
    
    double txRate = 0.0; // used for non-default NORM_FIXED ccMode
    NormStreamer::CCMode ccMode = NormStreamer::NORM_CC;
    const char* mcastIface = NULL;
    NormNodeId ackingNodeList[256]; 
    unsigned int ackingNodeCount = 0;
            
    bool loopback = false;
    bool ftiInfo = false;
    bool ackEx = false;
    int debugLevel = 0;
    bool trace = false;
    const char* logFile = NULL;
    bool omitHeaderOnOutput = false;
    bool silentReceiver = false;
    double txloss = 0.0;
    bool boostPriority = false;
    unsigned int checkSequence = 0;  // can set to 64 or 32
    // TBD - set these defaults to reasonable values or just use NormStreamer constructor defaults
    // A zero value for socket buffers means use the operating system default sizing
    unsigned long inputSocketBufferSize = 0;    // 6*1024*1024;
    unsigned long outputSocketBufferSize = 0;   // 6*1024*1024;
    unsigned long txSocketBufferSize = 0;       // 6*1024*1024;
    unsigned long rxSocketBufferSize = 0;       // 6*1024*1024;
    unsigned long streamBufferSize = 1*1024*1024;

    // Instantiate a NormStreamer and set default params
    NormStreamer normStreamer;
    normStreamer.SetFlushMode(NORM_FLUSH_NONE);
    
    // Parse command-line
    int i = 1;
    while (i < argc)
    {
        const char* cmd = argv[i++];
        size_t len = strlen(cmd);
        if (0 == strncmp(cmd, "help", len))
        {
            PrintHelp() ;
            exit(0);
        }
        else if (0 == strncmp(cmd, "send", len))
        {
            send = true;
        }
        else if (0 == strncmp(cmd, "recv", len))
        {
            recv = true;
        }
        else if (0 == strncmp(cmd, "loopback", len))
        {
            loopback = true;
        }
        else if (0 == strncmp(cmd, "ptos", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'ptos' value!\n");
                Usage();
                return -1;
            }
            int tos = -1;
            int result = sscanf(argv[i], "%i", &tos);
            if (1 != result)
            {
                unsigned int utos;
                result = sscanf(argv[i], "%x", &utos);
                tos = utos;
            }
            if ((1 != result) || (tos < 0) || (tos > 255))
            {
                fprintf(stderr, "normStreamer error: invalid 'ptos' value!\n");
                Usage();
                return -1;
            }
            i++;
            normStreamer.SetProbeTOS((UINT8)tos);
        }
        else if (0 == strncmp(cmd, "info", len))
        {
            ftiInfo = true;
        }
        else if (0 == strncmp(cmd, "ex", len))
        {
            // This enables testing/demonstrating NormSetWatermarkEx() operation
            ackEx = true;
        }
        else if (0 == strncmp(cmd, "addr", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'addr[/port]' value!\n");
                Usage();
                return -1;
            }
            const char* addrPtr = argv[i++];
            const char* portPtr = strchr(addrPtr, '/');
            if (NULL == portPtr)
            {
                strncpy(sessionAddr, addrPtr, 63);
                sessionAddr[63] = '\0';
            }
            else
            {
                size_t addrLen = portPtr - addrPtr;
                if (addrLen > 63) addrLen = 63;  // should issue error message
                strncpy(sessionAddr, addrPtr, addrLen);
                sessionAddr[addrLen] = '\0';
                portPtr++;
                sessionPort = atoi(portPtr);
            }
        }
        else if (0 == strncmp(cmd, "listen", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing '[mcastAddr/]port]' value!\n");
                Usage();
                return -1;
            }
            const char* addrPtr = argv[i++];
            const char* portPtr = strchr(addrPtr, '/');
            if (NULL != portPtr)
            {
                size_t addrLen = portPtr - addrPtr;
                if (addrLen > 63) addrLen = 63;  // should issue error message
                strncpy(listenAddr, addrPtr, addrLen);
                listenAddr[addrLen] = '\0';
                portPtr++;
                listenPort = atoi(portPtr);
            }
            else
            {
                // no address, just port
                listenPort = atoi(addrPtr);
                addrPtr = NULL;
            }
        }
        else if (0 == strncmp(cmd, "relay", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing relay 'dstAddr/port' value!\n");
                Usage();
                return -1;
            }
            const char* addrPtr = argv[i++];
            const char* portPtr = strchr(addrPtr, '/');
            if (NULL == portPtr)
            {
                fprintf(stderr, "normStreamer error: missing relay 'port' value!\n");
                Usage();
                return -1;
            }
            if (NULL != portPtr)
            {
                size_t addrLen = portPtr - addrPtr;
                if (addrLen > 63) addrLen = 63;  // should issue error message
                strncpy(relayAddr, addrPtr, addrLen);
                relayAddr[addrLen] = '\0';
                portPtr++;
                relayPort = atoi(portPtr);
            }
            
        }
        else if (0 == strncmp(cmd, "output", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing output 'device' name!\n");
                Usage();
                return -1;
            }
            FILE* outfile = fopen(argv[i++], "w+");
            if (NULL == outfile)
            {
                fprintf(stderr, "normStreamer output device fopen() error: %s\n", GetErrorString());
                Usage();
                return -1;
            }
            normStreamer.SetOutputFile(outfile);
        }
        else if (0 == strncmp(cmd, "id", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'id' value!\n");
                Usage();
                return -1;
            }
            nodeId = atoi(argv[i++]);
        }
        else if (0 == strncmp(cmd, "ack", len))
        {
            // comma-delimited acking node id list
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'id' <nodeId> value!\n");
                Usage();
                return -1;
            }
            const char* alist = argv[i++];
            if (0 == strcmp(alist, "auto"))
            {
                normStreamer.SetAutoAck(true);
            }
            else
            {
                while ((NULL != alist) && (*alist != '\0'))
                {
                    // TBD - Do we need to skip leading white space?
                    int id;
                    if (1 != sscanf(alist, "%d", &id))
                    {
                        fprintf(stderr, "normStreamer error: invalid acking node list!\n");
                        Usage();
                        return -1;
                    }
                    ackingNodeList[ackingNodeCount] = NormNodeId(id);
                    ackingNodeCount++;
                    alist = strchr(alist, ',');
                    if (NULL != alist) alist++;  // point past comma
                }
            }
        }
        else if (0 == strncmp(cmd, "flush", len))
        {
            // "none", "passive", or "active"
            if (i >= argc)
            {
                fprintf(stderr, "nodeMsgr error: missing 'flush' <mode>!\n");
                Usage();
                return -1;
            }
            const char* mode = argv[i++];
            if (0 == strcmp(mode, "none"))
            {
                normStreamer.SetFlushMode(NORM_FLUSH_NONE);
            }
            else if (0 == strcmp(mode, "passive"))
            {
                normStreamer.SetFlushMode(NORM_FLUSH_PASSIVE);
            }
            else if (0 == strcmp(mode, "active"))
            {
                normStreamer.SetFlushMode(NORM_FLUSH_ACTIVE);
            }
            else
            {
                fprintf(stderr, "normMsgr error: invalid 'flush' mode \"%s\"\n", mode);
                return -1;
            }   
        }
        else if (0 == strncmp(cmd, "rate", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'rate' <bitsPerSecond> value!\n");
                Usage();
                return -1;
            }
            if (1 != sscanf(argv[i++], "%lf", &txRate))
            {
                fprintf(stderr, "normStreamer error: invalid transmit rate!\n");
                Usage();
                return -1;
            }       
            // set fixed-rate operation
            ccMode = NormStreamer::NORM_FIXED;     
            normStreamer.SetOutputBucketRate(txRate);
        }
        else if (0 == strcmp(cmd, "cc"))
        {
            ccMode = NormStreamer::NORM_CC;
        }
        else if (0 == strcmp(cmd, "cce"))
        {
            ccMode = NormStreamer::NORM_CCE;
        }
        else if (0 == strcmp(cmd, "ccl"))
        {
            ccMode = NormStreamer::NORM_CCL;
        }
        else if (0 == strncmp(cmd, "interface", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'interface' <name>!\n");
                Usage();
                return -1;
            }
            mcastIface = argv[i++];
        }
        else if (0 == strncmp(cmd, "linterface", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'linterface' <name>!\n");
                Usage();
                return -1;
             }
             listenIface = argv[i++];
        }
        else if (0 == strncmp(cmd, "insockbuffer", len))
        {
            unsigned long value = 0 ;
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'insockbuffer' size!\n");
                Usage();
                return -1;
            }
            if (1 != sscanf(argv[i++], "%lu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'insockbuffer' size\n");
                Usage();
                return -1;
            }
            inputSocketBufferSize = value;
        }
        else if (0 == strncmp(cmd, "outsockbuffer", len))
        {
            unsigned long value = 0 ;
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'outsockbuffer' size!\n");
                Usage();
                return -1;
            }
            if (1 != sscanf(argv[i++], "%lu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'outsockbuffer' size!\n");
                Usage();
                return -1;
            }
            outputSocketBufferSize = value;
            }
        else if (0 == strncmp(cmd, "limit", len))
        {
            // format: limit [<rate>/<size>]  with 'rate' in bps and 'size' in bytes
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'limit' size!\n");
                Usage();
                return -1;
            }
            const char* ratePtr = argv[i++];
            const char* sizePtr = strchr(ratePtr, '/');
            unsigned int rateLen = 0;
            if (NULL != sizePtr)
                rateLen = sizePtr++ - ratePtr;
            else
                sizePtr = ratePtr;
            if (0 != rateLen)
            {
                if (rateLen > 63)
                {
                    fprintf(stderr, "normStreamer error: out-of-bounds 'limit' rate\n");
                    Usage();
                    return -1;
                }
                char rateText[64];
                strncpy(rateText, ratePtr, rateLen);
                rateText[rateLen] = '\0';
                double value;
                if (1 != sscanf(rateText, "%lf", &value))
                {
                    fprintf(stderr, "normStreamer error: invalid 'limit' rate\n");
                    Usage();
                    return -1;
                }
                normStreamer.SetOutputBucketRate(value);
            }
            unsigned long value;
            if (1 != sscanf(sizePtr, "%lu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'limit' size\n");
                Usage();
                return -1;
            }
            normStreamer.SetOutputBucketDepth(value);
        }
        else if (0 == strncmp(cmd, "txsockbuffer", len))
        {
            unsigned long value = 0 ;
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'txsockbuffer' size!\n");
                Usage();
                return -1;
            }
            if (1 != sscanf(argv[i++], "%lu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'txsockbuffer' size!\n");
                Usage();
                return -1;
            }
            txSocketBufferSize = value;
        }
        else if (0 == strncmp(cmd, "rxsockbuffer", len))
        {
            unsigned long value = 0 ;
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'rxsockbuffer' size!\n");
                Usage();
                return -1;
            }
            if (1 != sscanf(argv[i++], "%lu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'rxsockbuffer' size!\n");
                Usage();
                return -1;
            }
            rxSocketBufferSize = value;
        }
        else if (0 == strncmp(cmd, "segment", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'segment' size!\n");
                Usage();
                return -1;
            }
            unsigned short value;
            if (1 != sscanf(argv[i++], "%hu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'segment' size!\n");
                Usage();
                return -1;
            }
            normStreamer.SetSegmentSize(value);
        }
        else if (0 == strncmp(cmd, "block", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'block' size!\n");
                Usage();
                return -1;
            }
            unsigned short value;
            if (1 != sscanf(argv[i++], "%hu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'block' size!\n");
                Usage();
                return -1;
            }
            normStreamer.SetBlockSize(value);
        }
        else if (0 == strncmp(cmd, "parity", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'parity' count!\n");
                Usage();
                return -1;
            }
            unsigned short value;
            if (1 != sscanf(argv[i++], "%hu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'parity' count!\n");
                Usage();
                return -1;
            }
            normStreamer.SetNumParity(value);
        }
        else if (0 == strncmp(cmd, "auto", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'auto' parity count!\n");
                Usage();
                return -1;
            }
            unsigned short value;
            if (1 != sscanf(argv[i++], "%hu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'auto' parity count!\n");
                Usage();
                return -1;
            }
            normStreamer.SetAutoParity(value);
        }
        else if (0 == strncmp(cmd, "streambuffer", len))
        {
            unsigned long value = 0 ;
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'streambuffer' size!\n");
                Usage();
                return -1;
            }
            if (1 != sscanf(argv[i++], "%lu", &value))
            {
                fprintf(stderr, "normStreamer error: invalid 'streambuffer' size!\n");
                Usage();
                return -1;
            }
            streamBufferSize = value;
        }
        else if ( 0 == strncmp(cmd,"chkseq", len) )
        {
            checkSequence = 64;  // same as "check64" for "historical" reasons
        }
        else if ( 0 == strncmp(cmd,"check64", len) )
        {
            checkSequence = 64;
        }
        else if ( 0 == strncmp(cmd,"check32", len) )
        {
            checkSequence = 32;
        }
        else if (0 == strncmp(cmd, "omit", len))
        {
            omitHeaderOnOutput = true;
        }
        else if (0 == strncmp(cmd, "silent", len))
        {
            silentReceiver = true;
        }
        else if (0 == strncmp(cmd, "boost", len))
        {
            boostPriority = true;
        }
        else if (0 == strncmp(cmd, "txloss", len))
        {
            if (1 != sscanf(argv[i++], "%lf", &txloss))
            {
                fprintf(stderr, "normStreamer error: invalid 'txloss' value!\n");
                Usage();
                return -1;
            }
        }
        else if (0 == strncmp(cmd, "debug", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'debug' <level>!\n");
                Usage();
                return -1;
            }
            debugLevel = atoi(argv[i++]);
        }
        else if (0 == strncmp(cmd, "trace", len))
        {
            trace = true;
        }
        else if (0 == strncmp(cmd, "log", len))
        {
            if (i >= argc)
            {
                fprintf(stderr, "normStreamer error: missing 'log' <fileName>!\n");
                Usage();
                return -1;
            }
            logFile = argv[i++];
        }
        else if (0 == strncmp(cmd, "help", len))
        {
            Usage();
            return 0;
        }
        else
        {
            fprintf(stderr, "normStreamer error: invalid command \"%s\"!\n", cmd);
            Usage();
            return -1;
        }
    }
    
    if (!send && !recv)
    {
        fprintf(stderr, "normStreamer error: not configured to send or recv!\n");
        Usage();
        return -1;
    }
    /*
    if (NORM_NODE_NONE == nodeId)
    {
        fprintf(stderr, "normStreamer error: no local 'id' provided!\n");
        Usage();
        return -1;
    }
    */
    
    if (boostPriority)
    {
        if (!normStreamer.BoostPriority())
        {
            fprintf(stderr, "normStreamer error: setting scheduler/ priority boost failed (requires 'sudo').\n");
            return -1;
        }
    }
    
    
    
    if (0 != listenPort)
    {
        normStreamer.SetInputSocketBufferSize(inputSocketBufferSize);
        if (!normStreamer.EnableUdpListener(listenPort, listenAddr, listenIface))
        {
            fprintf(stderr, "normStreamer error: Failed to enable UDP listener\n") ;
            return -1;
        }
    }
    if (0 != relayPort)
    {
        // TBD - check addr/port validity?
        normStreamer.SetOutputSocketBufferSize(outputSocketBufferSize);
        if (! normStreamer.EnableUdpRelay(relayAddr, relayPort))
        {
            fprintf(stderr, "normStreamer error: Failed to open UDP relay socket\n") ;
            return -1;
        }
    }
    
    // TBD - should provide more error checking of NORM API calls
    NormInstanceHandle normInstance = NormCreateInstance(boostPriority);
    NormSetDebugLevel(debugLevel);
    if ((NULL != logFile) && !NormOpenDebugLog(normInstance, logFile))
    {
        perror("normStreamer error: unable to open log file");
        Usage();
        return -1;
    }
    normStreamer.SetCheckSequence(checkSequence);
    
    
    normStreamer.SetTxSocketBufferSize(txSocketBufferSize);
    normStreamer.SetRxSocketBufferSize(rxSocketBufferSize);
    normStreamer.SetStreamBufferSize(streamBufferSize);

    normStreamer.SetLoopback(loopback);
    normStreamer.SetFtiInfo(ftiInfo);
    normStreamer.SetAckEx(ackEx);
    
    if (omitHeaderOnOutput) normStreamer.OmitHeader(true);
    
    if (!normStreamer.OpenNormSession(normInstance, sessionAddr, sessionPort, (NormNodeId)nodeId))
    {
        fprintf(stderr, "normStreamer error: unable to open NORM session\n");
        NormDestroyInstance(normInstance);
        return -1;
    }
    
    if (silentReceiver) normStreamer.SetSilentReceiver(true);
    if (txloss > 0.0) normStreamer.SetTxLoss(txloss);
    
    for (unsigned int i = 0; i < ackingNodeCount; i++)
        normStreamer.AddAckingNode(ackingNodeList[i]);
    
    normStreamer.SetNormCongestionControl(ccMode);
    if (NormStreamer::NORM_FIXED == ccMode)
        normStreamer.SetNormTxRate(txRate);
    if (NULL != mcastIface)
        normStreamer.SetNormMulticastInterface(mcastIface);
    
    if (trace) normStreamer.SetNormMessageTrace(true);
    
    // TBD - set NORM session parameters
    normStreamer.Start(send, recv); 
    
    // TBD - add WIN32 support using win32InputHandler code
    //       and MsgWaitForMultipleObjectsEx() instead of select()
    
    int normfd = NormGetDescriptor(normInstance);
    // Get input/output descriptors and set to non-blocking i/o
    int inputfd = normStreamer.GetInputDescriptor();
    int outputfd = normStreamer.GetOutputDescriptor();
    if (-1 == fcntl(inputfd, F_SETFL, fcntl(inputfd, F_GETFL, 0) | O_NONBLOCK))
        perror("normStreamer: fcntl(inputfd, O_NONBLOCK) error");
    //if (!normStreamer.UdpRelayEnabled())
    if (-1 == fcntl(outputfd, F_SETFL, fcntl(outputfd, F_GETFL, 0) | O_NONBLOCK))
        perror("normStreamer: fcntl(outputfd, O_NONBLOCK) error");
    fd_set fdsetInput, fdsetOutput;
    FD_ZERO(&fdsetInput);
    FD_ZERO(&fdsetOutput);
    
#ifdef LINUX
    // We user timerfd on Linux for more precise timeouts
    int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
    if (timerfd < 0)
    {
        perror("normStreamer: timerfd_create() error");
        return -1;  
    }
#endif // LINUX 
    struct timeval lastTime;
    gettimeofday(&lastTime, NULL);
    struct timeval bucketTime = lastTime;
    while (normStreamer.IsRunning())
    {
        int maxfd = -1;
        int fdMask = 0;
        bool waitOnNorm = false;
        double timeoutInterval = -1.0;
        if (send)
        {
            if (normStreamer.InputNeeded())
            {
                if (normStreamer.InputReady())
                {
                    FD_CLR(inputfd, &fdsetInput);
                    timeoutInterval = 0.0;
                }
                else
                {
                    FD_SET(inputfd, &fdsetInput);
                    if (inputfd > maxfd) maxfd = inputfd;
                    fdMask |= 0x01;
                }
            }
            else
            {
                FD_CLR(inputfd, &fdsetInput);
            } 
            if (normStreamer.TxPending())
            {
                if (normStreamer.TxReady())
                    timeoutInterval = 0.0;
                else
                    waitOnNorm = true;
            }
        }
        if (recv)
        {
            if (normStreamer.RxNeeded())
            {
                if (normStreamer.RxReady())
                    timeoutInterval = 0.0;
                else
                    waitOnNorm = true;
            }
            if (normStreamer.OutputPending())
            {
                if (normStreamer.OutputReady())
                {
                    FD_CLR(outputfd, &fdsetOutput);
                    if (timeoutInterval < 0.0)
                        timeoutInterval = normStreamer.GetOutputBucketTimeout();
                }
                else
                {
                    FD_SET(outputfd, &fdsetOutput);
                    if (outputfd > maxfd) maxfd = outputfd;
                    fdMask |= 0x02;
                }
            }
            else
            {
                FD_CLR(outputfd, &fdsetOutput);
            }
        }
        if (waitOnNorm)
        {
            // we need to wait until NORM is tx_ready or rx_ready
            FD_SET(normfd, &fdsetInput);
            if (normfd > maxfd) maxfd = normfd;
            fdMask |= 0x04;
        }
        else
        {
            FD_CLR(normfd, &fdsetInput);
        }
        // Set timeout for select() ... TBD - it may be a slight
        // performance enhancement to skip the select() call when
        // the timeout needed is zero???
        struct timeval timeout;
        struct timeval* timeoutPtr = &timeout;
#ifdef LINUX
        if (timeoutInterval > 0.0)   
        {   
            // On Linux, we use the timerfd with our select() call to get
            // more precise timeouts than select() does alone on Linux
            struct timespec timeoutSpec;
            timeoutSpec.tv_sec = (unsigned int)timeoutInterval;
            timeoutSpec.tv_nsec = 1.0e+09*(timeoutInterval - (double)timeoutSpec.tv_sec);
            struct itimerspec timerSpec;
            timerSpec.it_interval.tv_sec = timerSpec.it_interval.tv_nsec = 0;
            timerSpec.it_value = timeoutSpec;
            if (0 == timerfd_settime(timerfd, 0, &timerSpec, 0))
            {
                timeoutPtr = NULL;
                FD_SET(timerfd, &fdsetInput);
                if (outputfd > maxfd) maxfd = timerfd;
                fdMask |= 0x08;
            }
            else
            {
                FD_CLR(timerfd, &fdsetInput); 
                timeout.tv_sec = (unsigned int)timeoutInterval;
                timeout.tv_usec = 1.0e+06*(timeoutInterval - (double)timeout.tv_sec);
                perror("normStreamer: timerfd_settime() error");
            }
        }
        else
        {
            // No precision timing needed 
            FD_CLR(timerfd, &fdsetInput);   
            if (timeoutInterval < 0.0)
            {
                // We wait one second maximum for debugging purposes
                timeout.tv_sec = 1;
                timeout.tv_usec = 0;
            }
            else // if (0.0 == timeoutInterval)
            {
                timeout.tv_sec = timeout.tv_usec = 0;
            }
        }
#else // non-LINUX  
        if (timeoutInterval > 0.0)
        {
            timeout.tv_sec = (unsigned int)timeoutInterval;
            timeout.tv_usec = 1.0e+06*(timeoutInterval - (double)timeout.tv_sec);
        }
        else if (timeoutInterval < 0.0)
        {
            // We wait one second maximum for debugging purposes
            timeout.tv_sec = 1;
            timeout.tv_usec = 0;
        }
        else // if (0.0 == timeoutInterval)
        {
            timeout.tv_sec = timeout.tv_usec = 0;
        }
#endif // if/else LINUX
        int result = select(maxfd+1, &fdsetInput, &fdsetOutput, NULL, timeoutPtr);
        switch (result)
        {
            case -1:
                switch (errno)
                {
                    case EINTR:
                    case EAGAIN:
                        continue;
                    default:
                        perror("normStreamer select() error");
                        // TBD - stop NormStreamer
                        break;
                }
                break;
            case 0:
                // timeout
                break;
            default:
                if (FD_ISSET(inputfd, &fdsetInput))
                    normStreamer.SetInputReady();
                if (FD_ISSET(outputfd, &fdsetOutput))
                    normStreamer.SetOutputReady();
#ifdef LINUX
                if (FD_ISSET(timerfd, &fdsetInput))
                {
                    // clear the timerfd status by reading from it
                    uint64_t expirations = 0;
                    if (read(timerfd, &expirations, sizeof(expirations)) < 0)
                        perror("normStreamer read(timerfd) error");
                }
#endif // LINUX
                break; 
        }
        // We always clear out/handle pending NORM API events
        // (to keep event queue from building up)
        NormEvent event;
        while (NormGetNextEvent(normInstance, &event, false))
            normStreamer.HandleNormEvent(event);
        
        struct timeval thisTime;
        gettimeofday(&thisTime, NULL);
        
        if (0 != normStreamer.GetOutputBucketDepth())
        {
            // Credit output token bucket for time that has passed
            double interval = (double)(thisTime.tv_sec - bucketTime.tv_sec);
            if (thisTime.tv_usec > bucketTime.tv_usec)
                interval += 1.0e-06 * (thisTime.tv_usec - bucketTime.tv_usec);
            else
                interval -= 1.0e-06 * (bucketTime.tv_usec - thisTime.tv_usec);
            normStreamer.CreditOutputBucket(interval);
            bucketTime = thisTime;
        }
        
        // for debugging to see if anything gets "stuck"
        if ((thisTime.tv_sec - lastTime.tv_sec) >= 100)
        {
            if (send)
                fprintf(stderr, "normStreamer: inputNeeded:%d inputReady:%d txPending:%d txReady:%d inputCount:%lu txCount:%lu fdMask:%d\n",
                            normStreamer.InputNeeded(), normStreamer.InputReady(), normStreamer.TxPending(), normStreamer.TxReady(),
                            normStreamer.GetInputByteCount(), normStreamer.GetTxByteCount(), fdMask);
            if (recv)
                fprintf(stderr, "normStreamer: rxNeeded:%d rxReady:%d outputPending:%d outputReady:%d fdMask:%d\n",
                            normStreamer.RxNeeded(), normStreamer.RxReady(), normStreamer.OutputPending(), normStreamer.OutputReady(), fdMask);
            
            lastTime = thisTime;
        }   
        
        // As a result of input/output ready or NORM notification events:
        // 1) Recv from rx_stream if needed and ready
        if (normStreamer.RxNeeded() && normStreamer.RxReady())
            normStreamer.RecvData(); 
        // 2) Write any pending data to output if output is ready
        if (normStreamer.OutputPending() && normStreamer.OutputReady())
        {
            if (normStreamer.OutputBucketReady())
                normStreamer.WriteOutput();  
        }
        // 3) Read from input if needed and ready 
        if (normStreamer.InputNeeded() && normStreamer.InputReady())
            normStreamer.ReadInput(); 
        // 4) Send any pending tx message
        if (normStreamer.TxPending() && normStreamer.TxReady())
            normStreamer.SendData();
        
    }  // end while(normStreamer.IsRunning()
    
#ifdef LINUX
    close(timerfd);
#endif // LINUX
    fflush(stderr);
    
    close(normStreamer.GetOutputDescriptor());  // TBD - do this in the destructor?
    
    NormDestroyInstance(normInstance);
    
    fprintf(stderr, "normStreamer exiting ...\n");
    
    return 0;
    
}  // end main()