File: rtp.c

package info (click to toggle)
asterisk 1:1.6.2.9-2+squeeze12
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 67,296 kB
  • ctags: 65,026
  • sloc: ansic: 327,660; sh: 11,153; cpp: 5,940; perl: 3,078; makefile: 2,594; yacc: 2,140; asm: 642; xml: 309; sql: 290; tcl: 113; php: 62
file content (4975 lines) | stat: -rw-r--r-- 164,221 bytes parent folder | download
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
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
/*
 * Asterisk -- An open source telephony toolkit.
 *
 * Copyright (C) 1999 - 2006, Digium, Inc.
 *
 * Mark Spencer <markster@digium.com>
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 */

/*! 
 * \file 
 *
 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
 *
 * \author Mark Spencer <markster@digium.com>
 * 
 * \note RTP is defined in RFC 3550.
 */

#include "asterisk.h"

ASTERISK_FILE_VERSION(__FILE__, "$Revision: 264115 $")

#include <sys/time.h>
#include <signal.h>
#include <fcntl.h>
#include <math.h> 

#include "asterisk/rtp.h"
#include "asterisk/pbx.h"
#include "asterisk/frame.h"
#include "asterisk/channel.h"
#include "asterisk/acl.h"
#include "asterisk/config.h"
#include "asterisk/lock.h"
#include "asterisk/utils.h"
#include "asterisk/netsock.h"
#include "asterisk/cli.h"
#include "asterisk/manager.h"
#include "asterisk/unaligned.h"

#define MAX_TIMESTAMP_SKEW	640

#define RTP_SEQ_MOD     (1<<16) 	/*!< A sequence number can't be more than 16 bits */
#define RTCP_DEFAULT_INTERVALMS   5000	/*!< Default milli-seconds between RTCP reports we send */
#define RTCP_MIN_INTERVALMS       500	/*!< Min milli-seconds between RTCP reports we send */
#define RTCP_MAX_INTERVALMS       60000	/*!< Max milli-seconds between RTCP reports we send */

#define RTCP_PT_FUR     192
#define RTCP_PT_SR      200
#define RTCP_PT_RR      201
#define RTCP_PT_SDES    202
#define RTCP_PT_BYE     203
#define RTCP_PT_APP     204

#define RTP_MTU		1200

#define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000))	/*!< samples */

static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;

static int rtpstart = 5000;     /*!< First port for RTP sessions (set in rtp.conf) */
static int rtpend = 31000;      /*!< Last port for RTP sessions (set in rtp.conf) */
static int rtpdebug;			/*!< Are we debugging? */
static int rtcpdebug;			/*!< Are we debugging RTCP? */
static int rtcpstats;			/*!< Are we debugging RTCP? */
static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
static int stundebug;			/*!< Are we debugging stun? */
static struct sockaddr_in rtpdebugaddr;	/*!< Debug packets to/from this host */
static struct sockaddr_in rtcpdebugaddr;	/*!< Debug RTCP packets to/from this host */
#ifdef SO_NO_CHECK
static int nochecksums;
#endif
static int strictrtp;

enum strict_rtp_state {
	STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
	STRICT_RTP_LEARN,    /*! Accept next packet as source */
	STRICT_RTP_CLOSED,   /*! Drop all RTP packets not coming from source that was learned */
};

/* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
/* #define P2P_INTENSE */

/*!
 * \brief Structure representing a RTP session.
 *
 * RTP session is defined on page 9 of RFC 3550: "An association among a set of participants communicating with RTP.  A participant may be involved in multiple RTP sessions at the same time [...]"
 *
 */

/*! \brief RTP session description */
struct ast_rtp {
	int s;
	struct ast_frame f;
	unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
	unsigned int ssrc;		/*!< Synchronization source, RFC 3550, page 10. */
	unsigned int themssrc;		/*!< Their SSRC */
	unsigned int rxssrc;
	unsigned int lastts;
	unsigned int lastrxts;
	unsigned int lastividtimestamp;
	unsigned int lastovidtimestamp;
	unsigned int lastitexttimestamp;
	unsigned int lastotexttimestamp;
	unsigned int lasteventseqn;
	int lastrxseqno;                /*!< Last received sequence number */
	unsigned short seedrxseqno;     /*!< What sequence number did they start with?*/
	unsigned int seedrxts;          /*!< What RTP timestamp did they start with? */
	unsigned int rxcount;           /*!< How many packets have we received? */
	unsigned int rxoctetcount;      /*!< How many octets have we received? should be rxcount *160*/
	unsigned int txcount;           /*!< How many packets have we sent? */
	unsigned int txoctetcount;      /*!< How many octets have we sent? (txcount*160)*/
	unsigned int cycles;            /*!< Shifted count of sequence number cycles */
	double rxjitter;                /*!< Interarrival jitter at the moment */
	double rxtransit;               /*!< Relative transit time for previous packet */
	int lasttxformat;
	int lastrxformat;

	int rtptimeout;			/*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
	int rtpholdtimeout;		/*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
	int rtpkeepalive;		/*!< Send RTP comfort noice packets for keepalive */

	/* DTMF Reception Variables */
	char resp;
	unsigned int lastevent;
	unsigned int dtmf_duration;     /*!< Total duration in samples since the digit start event */
	unsigned int dtmf_timeout;      /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
	unsigned int dtmfsamples;
	/* DTMF Transmission Variables */
	unsigned int lastdigitts;
	char sending_digit;	/*!< boolean - are we sending digits */
	char send_digit;	/*!< digit we are sending */
	int send_payload;
	int send_duration;
	int nat;
	unsigned int flags;
	struct sockaddr_in us;		/*!< Socket representation of the local endpoint. */
	struct sockaddr_in them;	/*!< Socket representation of the remote endpoint. */
	struct sockaddr_in altthem;	/*!< Alternate source of remote media */
	struct timeval rxcore;
	struct timeval txcore;
	double drxcore;                 /*!< The double representation of the first received packet */
	struct timeval lastrx;          /*!< timeval when we last received a packet */
	struct timeval dtmfmute;
	struct ast_smoother *smoother;
	int *ioid;
	unsigned short seqno;		/*!< Sequence number, RFC 3550, page 13. */
	unsigned short rxseqno;
	struct sched_context *sched;
	struct io_context *io;
	void *data;
	ast_rtp_callback callback;
#ifdef P2P_INTENSE
	ast_mutex_t bridge_lock;
#endif
	struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
	int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
	int rtp_lookup_code_cache_code;
	int rtp_lookup_code_cache_result;
	struct ast_rtcp *rtcp;
	struct ast_codec_pref pref;
	struct ast_rtp *bridged;        /*!< Who we are Packet bridged to */

	enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
	struct sockaddr_in strict_rtp_address;  /*!< Remote address information for strict RTP purposes */

	int set_marker_bit:1;           /*!< Whether to set the marker bit or not */
	struct rtp_red *red;
};

static struct ast_frame *red_t140_to_red(struct rtp_red *red);
static int red_write(const void *data);
 
struct rtp_red {
	struct ast_frame t140;  /*!< Primary data  */
	struct ast_frame t140red;   /*!< Redundant t140*/
	unsigned char pt[RED_MAX_GENERATION];  /*!< Payload types for redundancy data */
	unsigned char ts[RED_MAX_GENERATION]; /*!< Time stamps */
	unsigned char len[RED_MAX_GENERATION]; /*!< length of each generation */
	int num_gen; /*!< Number of generations */
	int schedid; /*!< Timer id */
	int ti; /*!< How long to buffer data before send */
	unsigned char t140red_data[64000];  
	unsigned char buf_data[64000]; /*!< buffered primary data */
	int hdrlen; 
	long int prev_ts;
};

AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);

/* Forward declarations */
static int ast_rtcp_write(const void *data);
static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
static int ast_rtcp_write_sr(const void *data);
static int ast_rtcp_write_rr(const void *data);
static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);

#define FLAG_3389_WARNING		(1 << 0)
#define FLAG_NAT_ACTIVE			(3 << 1)
#define FLAG_NAT_INACTIVE		(0 << 1)
#define FLAG_NAT_INACTIVE_NOWARN	(1 << 1)
#define FLAG_HAS_DTMF			(1 << 3)
#define FLAG_P2P_SENT_MARK              (1 << 4)
#define FLAG_P2P_NEED_DTMF              (1 << 5)
#define FLAG_CALLBACK_MODE              (1 << 6)
#define FLAG_DTMF_COMPENSATE            (1 << 7)
#define FLAG_HAS_STUN                   (1 << 8)

/*!
 * \brief Structure defining an RTCP session.
 * 
 * The concept "RTCP session" is not defined in RFC 3550, but since 
 * this structure is analogous to ast_rtp, which tracks a RTP session, 
 * it is logical to think of this as a RTCP session.
 *
 * RTCP packet is defined on page 9 of RFC 3550.
 * 
 */
struct ast_rtcp {
	int rtcp_info;
	int s;				/*!< Socket */
	struct sockaddr_in us;		/*!< Socket representation of the local endpoint. */
	struct sockaddr_in them;	/*!< Socket representation of the remote endpoint. */
	struct sockaddr_in altthem;	/*!< Alternate source for RTCP */
	unsigned int soc;		/*!< What they told us */
	unsigned int spc;		/*!< What they told us */
	unsigned int themrxlsr;		/*!< The middle 32 bits of the NTP timestamp in the last received SR*/
	struct timeval rxlsr;		/*!< Time when we got their last SR */
	struct timeval txlsr;		/*!< Time when we sent or last SR*/
	unsigned int expected_prior;	/*!< no. packets in previous interval */
	unsigned int received_prior;	/*!< no. packets received in previous interval */
	int schedid;			/*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
	unsigned int rr_count;		/*!< number of RRs we've sent, not including report blocks in SR's */
	unsigned int sr_count;		/*!< number of SRs we've sent */
	unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
	double accumulated_transit;	/*!< accumulated a-dlsr-lsr */
	double rtt;			/*!< Last reported rtt */
	unsigned int reported_jitter;	/*!< The contents of their last jitter entry in the RR */
	unsigned int reported_lost;	/*!< Reported lost packets in their RR */
	char quality[AST_MAX_USER_FIELD];
	char quality_jitter[AST_MAX_USER_FIELD];
	char quality_loss[AST_MAX_USER_FIELD];
	char quality_rtt[AST_MAX_USER_FIELD];

	double reported_maxjitter;
	double reported_minjitter;
	double reported_normdev_jitter;
	double reported_stdev_jitter;
	unsigned int reported_jitter_count;

	double reported_maxlost;
	double reported_minlost;
	double reported_normdev_lost;
	double reported_stdev_lost;

	double rxlost;
	double maxrxlost;
	double minrxlost;
	double normdev_rxlost;
	double stdev_rxlost;
	unsigned int rxlost_count;

	double maxrxjitter;
	double minrxjitter;
	double normdev_rxjitter;
	double stdev_rxjitter;
	unsigned int rxjitter_count;
	double maxrtt;
	double minrtt;
	double normdevrtt;
	double stdevrtt;
	unsigned int rtt_count;
	int sendfur;
};

/*!
 * \brief STUN support code
 *
 * This code provides some support for doing STUN transactions.
 * Eventually it should be moved elsewhere as other protocols
 * than RTP can benefit from it - e.g. SIP.
 * STUN is described in RFC3489 and it is based on the exchange
 * of UDP packets between a client and one or more servers to
 * determine the externally visible address (and port) of the client
 * once it has gone through the NAT boxes that connect it to the
 * outside.
 * The simplest request packet is just the header defined in
 * struct stun_header, and from the response we may just look at
 * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
 * By doing more transactions with different server addresses we
 * may determine more about the behaviour of the NAT boxes, of
 * course - the details are in the RFC.
 *
 * All STUN packets start with a simple header made of a type,
 * length (excluding the header) and a 16-byte random transaction id.
 * Following the header we may have zero or more attributes, each
 * structured as a type, length and a value (whose format depends
 * on the type, but often contains addresses).
 * Of course all fields are in network format.
 */

typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;

struct stun_header {
	unsigned short msgtype;
	unsigned short msglen;
	stun_trans_id  id;
	unsigned char ies[0];
} __attribute__((packed));

struct stun_attr {
	unsigned short attr;
	unsigned short len;
	unsigned char value[0];
} __attribute__((packed));

/*
 * The format normally used for addresses carried by STUN messages.
 */
struct stun_addr {
	unsigned char unused;
	unsigned char family;
	unsigned short port;
	unsigned int addr;
} __attribute__((packed));

#define STUN_IGNORE		(0)
#define STUN_ACCEPT		(1)

/*! \brief STUN message types
 * 'BIND' refers to transactions used to determine the externally
 * visible addresses. 'SEC' refers to transactions used to establish
 * a session key for subsequent requests.
 * 'SEC' functionality is not supported here.
 */
 
#define STUN_BINDREQ	0x0001
#define STUN_BINDRESP	0x0101
#define STUN_BINDERR	0x0111
#define STUN_SECREQ	0x0002
#define STUN_SECRESP	0x0102
#define STUN_SECERR	0x0112

/*! \brief Basic attribute types in stun messages.
 * Messages can also contain custom attributes (codes above 0x7fff)
 */
#define STUN_MAPPED_ADDRESS	0x0001
#define STUN_RESPONSE_ADDRESS	0x0002
#define STUN_CHANGE_REQUEST	0x0003
#define STUN_SOURCE_ADDRESS	0x0004
#define STUN_CHANGED_ADDRESS	0x0005
#define STUN_USERNAME		0x0006
#define STUN_PASSWORD		0x0007
#define STUN_MESSAGE_INTEGRITY	0x0008
#define STUN_ERROR_CODE		0x0009
#define STUN_UNKNOWN_ATTRIBUTES	0x000a
#define STUN_REFLECTED_FROM	0x000b

/*! \brief helper function to print message names */
static const char *stun_msg2str(int msg)
{
	switch (msg) {
	case STUN_BINDREQ:
		return "Binding Request";
	case STUN_BINDRESP:
		return "Binding Response";
	case STUN_BINDERR:
		return "Binding Error Response";
	case STUN_SECREQ:
		return "Shared Secret Request";
	case STUN_SECRESP:
		return "Shared Secret Response";
	case STUN_SECERR:
		return "Shared Secret Error Response";
	}
	return "Non-RFC3489 Message";
}

/*! \brief helper function to print attribute names */
static const char *stun_attr2str(int msg)
{
	switch (msg) {
	case STUN_MAPPED_ADDRESS:
		return "Mapped Address";
	case STUN_RESPONSE_ADDRESS:
		return "Response Address";
	case STUN_CHANGE_REQUEST:
		return "Change Request";
	case STUN_SOURCE_ADDRESS:
		return "Source Address";
	case STUN_CHANGED_ADDRESS:
		return "Changed Address";
	case STUN_USERNAME:
		return "Username";
	case STUN_PASSWORD:
		return "Password";
	case STUN_MESSAGE_INTEGRITY:
		return "Message Integrity";
	case STUN_ERROR_CODE:
		return "Error Code";
	case STUN_UNKNOWN_ATTRIBUTES:
		return "Unknown Attributes";
	case STUN_REFLECTED_FROM:
		return "Reflected From";
	}
	return "Non-RFC3489 Attribute";
}

/*! \brief here we store credentials extracted from a message */
struct stun_state {
	const char *username;
	const char *password;
};

static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
{
	if (stundebug)
		ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
			    stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
	switch (ntohs(attr->attr)) {
	case STUN_USERNAME:
		state->username = (const char *) (attr->value);
		break;
	case STUN_PASSWORD:
		state->password = (const char *) (attr->value);
		break;
	default:
		if (stundebug)
			ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n", 
				    stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
	}
	return 0;
}

/*! \brief append a string to an STUN message */
static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
{
	int size = sizeof(**attr) + strlen(s);
	if (*left > size) {
		(*attr)->attr = htons(attrval);
		(*attr)->len = htons(strlen(s));
		memcpy((*attr)->value, s, strlen(s));
		(*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
		*len += size;
		*left -= size;
	}
}

/*! \brief append an address to an STUN message */
static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sock_in, int *len, int *left)
{
	int size = sizeof(**attr) + 8;
	struct stun_addr *addr;
	if (*left > size) {
		(*attr)->attr = htons(attrval);
		(*attr)->len = htons(8);
		addr = (struct stun_addr *)((*attr)->value);
		addr->unused = 0;
		addr->family = 0x01;
		addr->port = sock_in->sin_port;
		addr->addr = sock_in->sin_addr.s_addr;
		(*attr) = (struct stun_attr *)((*attr)->value + 8);
		*len += size;
		*left -= size;
	}
}

/*! \brief wrapper to send an STUN message */
static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
{
	return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
		      (struct sockaddr *)dst, sizeof(*dst));
}

/*! \brief helper function to generate a random request id */
static void stun_req_id(struct stun_header *req)
{
	int x;
	for (x = 0; x < 4; x++)
		req->id.id[x] = ast_random();
}

size_t ast_rtp_alloc_size(void)
{
	return sizeof(struct ast_rtp);
}

/*! \brief callback type to be invoked on stun responses. */
typedef int (stun_cb_f)(struct stun_attr *attr, void *arg);

/*! \brief handle an incoming STUN message.
 *
 * Do some basic sanity checks on packet size and content,
 * try to extract a bit of information, and possibly reply.
 * At the moment this only processes BIND requests, and returns
 * the externally visible address of the request.
 * If a callback is specified, invoke it with the attribute.
 */
static int stun_handle_packet(int s, struct sockaddr_in *src,
	unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
{
	struct stun_header *hdr = (struct stun_header *)data;
	struct stun_attr *attr;
	struct stun_state st;
	int ret = STUN_IGNORE;	
	int x;

	/* On entry, 'len' is the length of the udp payload. After the
	 * initial checks it becomes the size of unprocessed options,
	 * while 'data' is advanced accordingly.
	 */
	if (len < sizeof(struct stun_header)) {
		ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
		return -1;
	}
	len -= sizeof(struct stun_header);
	data += sizeof(struct stun_header);
	x = ntohs(hdr->msglen);	/* len as advertised in the message */
	if (stundebug)
		ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
	if (x > len) {
		ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
	} else
		len = x;
	memset(&st, 0, sizeof(st));
	while (len) {
		if (len < sizeof(struct stun_attr)) {
			ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
			break;
		}
		attr = (struct stun_attr *)data;
		/* compute total attribute length */
		x = ntohs(attr->len) + sizeof(struct stun_attr);
		if (x > len) {
			ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
			break;
		}
		if (stun_cb)
			stun_cb(attr, arg);
		if (stun_process_attr(&st, attr)) {
			ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
			break;
		}
		/* Clear attribute id: in case previous entry was a string,
		 * this will act as the terminator for the string.
		 */
		attr->attr = 0;
		data += x;
		len -= x;
	}
	/* Null terminate any string.
	 * XXX NOTE, we write past the size of the buffer passed by the
	 * caller, so this is potentially dangerous. The only thing that
	 * saves us is that usually we read the incoming message in a
	 * much larger buffer in the struct ast_rtp
	 */
	*data = '\0';

	/* Now prepare to generate a reply, which at the moment is done
	 * only for properly formed (len == 0) STUN_BINDREQ messages.
	 */
	if (len == 0) {
		unsigned char respdata[1024];
		struct stun_header *resp = (struct stun_header *)respdata;
		int resplen = 0;	/* len excluding header */
		int respleft = sizeof(respdata) - sizeof(struct stun_header);

		resp->id = hdr->id;
		resp->msgtype = 0;
		resp->msglen = 0;
		attr = (struct stun_attr *)resp->ies;
		switch (ntohs(hdr->msgtype)) {
		case STUN_BINDREQ:
			if (stundebug)
				ast_verbose("STUN Bind Request, username: %s\n", 
					    st.username ? st.username : "<none>");
			if (st.username)
				append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
			append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
			resp->msglen = htons(resplen);
			resp->msgtype = htons(STUN_BINDRESP);
			stun_send(s, src, resp);
			ret = STUN_ACCEPT;
			break;
		default:
			if (stundebug)
				ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
		}
	}
	return ret;
}

/*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
 * This is used as a callback for stun_handle_response
 * when called from ast_stun_request.
 */
static int stun_get_mapped(struct stun_attr *attr, void *arg)
{
	struct stun_addr *addr = (struct stun_addr *)(attr + 1);
	struct sockaddr_in *sa = (struct sockaddr_in *)arg;

	if (ntohs(attr->attr) != STUN_MAPPED_ADDRESS || ntohs(attr->len) != 8)
		return 1;	/* not us. */
	sa->sin_port = addr->port;
	sa->sin_addr.s_addr = addr->addr;
	return 0;
}

/*! \brief Generic STUN request
 * Send a generic stun request to the server specified,
 * possibly waiting for a reply and filling the 'reply' field with
 * the externally visible address. Note that in this case the request
 * will be blocking.
 * (Note, the interface may change slightly in the future).
 *
 * \param s the socket used to send the request
 * \param dst the address of the STUN server
 * \param username if non null, add the username in the request
 * \param answer if non null, the function waits for a response and
 *    puts here the externally visible address.
 * \return 0 on success, other values on error.
 */
int ast_stun_request(int s, struct sockaddr_in *dst,
	const char *username, struct sockaddr_in *answer)
{
	struct stun_header *req;
	unsigned char reqdata[1024];
	int reqlen, reqleft;
	struct stun_attr *attr;
	int res = 0;
	int retry;
	
	req = (struct stun_header *)reqdata;
	stun_req_id(req);
	reqlen = 0;
	reqleft = sizeof(reqdata) - sizeof(struct stun_header);
	req->msgtype = 0;
	req->msglen = 0;
	attr = (struct stun_attr *)req->ies;
	if (username)
		append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
	req->msglen = htons(reqlen);
	req->msgtype = htons(STUN_BINDREQ);
	for (retry = 0; retry < 3; retry++) {	/* XXX make retries configurable */
		/* send request, possibly wait for reply */
		unsigned char reply_buf[1024];
		fd_set rfds;
		struct timeval to = { 3, 0 };	/* timeout, make it configurable */
		struct sockaddr_in src;
		socklen_t srclen;

		res = stun_send(s, dst, req);
		if (res < 0) {
			ast_log(LOG_WARNING, "ast_stun_request send #%d failed error %d, retry\n",
				retry, res);
			continue;
		}
		if (answer == NULL)
			break;
		FD_ZERO(&rfds);
		FD_SET(s, &rfds);
		res = ast_select(s + 1, &rfds, NULL, NULL, &to);
		if (res <= 0)	/* timeout or error */
			continue;
		memset(&src, '\0', sizeof(src));
		srclen = sizeof(src);
		/* XXX pass -1 in the size, because stun_handle_packet might
		 * write past the end of the buffer.
		 */
		res = recvfrom(s, reply_buf, sizeof(reply_buf) - 1,
			0, (struct sockaddr *)&src, &srclen);
		if (res < 0) {
			ast_log(LOG_WARNING, "ast_stun_request recvfrom #%d failed error %d, retry\n",
				retry, res);
			continue;
		}
		memset(answer, '\0', sizeof(struct sockaddr_in));
		stun_handle_packet(s, &src, reply_buf, res,
			stun_get_mapped, answer);
		res = 0; /* signal regular exit */
		break;
	}
	return res;
}

/*! \brief send a STUN BIND request to the given destination.
 * Optionally, add a username if specified.
 */
void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
{
	ast_stun_request(rtp->s, suggestion, username, NULL);
}

/*! \brief List of current sessions */
static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);

static void timeval2ntp(struct timeval when, unsigned int *msw, unsigned int *lsw)
{
	unsigned int sec, usec, frac;
	sec = when.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
	usec = when.tv_usec;
	frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
	*msw = sec;
	*lsw = frac;
}

int ast_rtp_fd(struct ast_rtp *rtp)
{
	return rtp->s;
}

int ast_rtcp_fd(struct ast_rtp *rtp)
{
	if (rtp->rtcp)
		return rtp->rtcp->s;
	return -1;
}

static int rtp_get_rate(int subclass)
{
	return (subclass == AST_FORMAT_G722) ? 8000 : ast_format_rate(subclass);
}

unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
{
	unsigned int interval;
	/*! \todo XXX Do a more reasonable calculation on this one
	 * Look in RFC 3550 Section A.7 for an example*/
	interval = rtcpinterval;
	return interval;
}

/* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
{
	rtp->rtptimeout = (-1) * rtp->rtptimeout;
	rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
}

/*! \brief Set rtp timeout */
void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
{
	rtp->rtptimeout = timeout;
}

/*! \brief Set rtp hold timeout */
void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
{
	rtp->rtpholdtimeout = timeout;
}

/*! \brief set RTP keepalive interval */
void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
{
	rtp->rtpkeepalive = period;
}

/*! \brief Get rtp timeout */
int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
{
	if (rtp->rtptimeout < 0)	/* We're not checking, but remembering the setting (during T.38 transmission) */
		return 0;
	return rtp->rtptimeout;
}

/*! \brief Get rtp hold timeout */
int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
{
	if (rtp->rtptimeout < 0)	/* We're not checking, but remembering the setting (during T.38 transmission) */
		return 0;
	return rtp->rtpholdtimeout;
}

/*! \brief Get RTP keepalive interval */
int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
{
	return rtp->rtpkeepalive;
}

void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
{
	rtp->data = data;
}

void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
{
	rtp->callback = callback;
}

void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
{
	rtp->nat = nat;
}

int ast_rtp_getnat(struct ast_rtp *rtp)
{
	return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
}

void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
{
	ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
}

void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
{
	ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
}

void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
{
	ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
}

static void rtp_bridge_lock(struct ast_rtp *rtp)
{
#ifdef P2P_INTENSE
	ast_mutex_lock(&rtp->bridge_lock);
#endif
	return;
}

static void rtp_bridge_unlock(struct ast_rtp *rtp)
{
#ifdef P2P_INTENSE
	ast_mutex_unlock(&rtp->bridge_lock);
#endif
	return;
}

/*! \brief Calculate normal deviation */
static double normdev_compute(double normdev, double sample, unsigned int sample_count)
{
	normdev = normdev * sample_count + sample;
	sample_count++;

	return normdev / sample_count;
}

static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
{
/*
		for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
		return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
		we can compute the sigma^2 and that way we would have to do the sqrt only 1 time at the end and would save another pow 2 compute
		optimized formula
*/
#define SQUARE(x) ((x) * (x))

	stddev = sample_count * stddev;
	sample_count++;

	return stddev + 
	       ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) + 
	       ( SQUARE(sample - normdev_curent) / sample_count );

#undef SQUARE
}

static struct ast_frame *create_dtmf_frame(struct ast_rtp *rtp, enum ast_frame_type type)
{
	if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
	     (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
		ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
		rtp->resp = 0;
		rtp->dtmfsamples = 0;
		return &ast_null_frame;
	}
	ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
	if (rtp->resp == 'X') {
		rtp->f.frametype = AST_FRAME_CONTROL;
		rtp->f.subclass = AST_CONTROL_FLASH;
	} else {
		rtp->f.frametype = type;
		rtp->f.subclass = rtp->resp;
	}
	rtp->f.datalen = 0;
	rtp->f.samples = 0;
	rtp->f.mallocd = 0;
	rtp->f.src = "RTP";
	AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
	return &rtp->f;
	
}

static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
{
	if (rtpdebug == 0)
		return 0;
	if (rtpdebugaddr.sin_addr.s_addr) {
		if (((ntohs(rtpdebugaddr.sin_port) != 0)
		     && (rtpdebugaddr.sin_port != addr->sin_port))
		    || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
			return 0;
	}
	return 1;
}

static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
{
	if (rtcpdebug == 0)
		return 0;
	if (rtcpdebugaddr.sin_addr.s_addr) {
		if (((ntohs(rtcpdebugaddr.sin_port) != 0)
		     && (rtcpdebugaddr.sin_port != addr->sin_port))
		    || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
			return 0;
	}
	return 1;
}


static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
{
	unsigned int event;
	char resp = 0;
	struct ast_frame *f = NULL;
	unsigned char seq;
	unsigned int flags;
	unsigned int power;

	/* We should have at least 4 bytes in RTP data */
	if (len < 4)
		return f;

	/*	The format of Cisco RTP DTMF packet looks like next:
		+0				- sequence number of DTMF RTP packet (begins from 1,
						  wrapped to 0)
		+1				- set of flags
		+1 (bit 0)		- flaps by different DTMF digits delimited by audio
						  or repeated digit without audio???
		+2 (+4,+6,...)	- power level? (rises from 0 to 32 at begin of tone
						  then falls to 0 at its end)
		+3 (+5,+7,...)	- detected DTMF digit (0..9,*,#,A-D,...)
		Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
		by each new packet and thus provides some redudancy.
		
		Sample of Cisco RTP DTMF packet is (all data in hex):
			19 07 00 02 12 02 20 02
		showing end of DTMF digit '2'.

		The packets
			27 07 00 02 0A 02 20 02
			28 06 20 02 00 02 0A 02
		shows begin of new digit '2' with very short pause (20 ms) after
		previous digit '2'. Bit +1.0 flips at begin of new digit.
		
		Cisco RTP DTMF packets comes as replacement of audio RTP packets
		so its uses the same sequencing and timestamping rules as replaced
		audio packets. Repeat interval of DTMF packets is 20 ms and not rely
		on audio framing parameters. Marker bit isn't used within stream of
		DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
		are not sequential at borders between DTMF and audio streams,
	*/

	seq = data[0];
	flags = data[1];
	power = data[2];
	event = data[3] & 0x1f;

	if (option_debug > 2 || rtpdebug)
		ast_debug(0, "Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%d, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
	if (event < 10) {
		resp = '0' + event;
	} else if (event < 11) {
		resp = '*';
	} else if (event < 12) {
		resp = '#';
	} else if (event < 16) {
		resp = 'A' + (event - 12);
	} else if (event < 17) {
		resp = 'X';
	}
	if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
		rtp->resp = resp;
		/* Why we should care on DTMF compensation at reception? */
		if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
			f = create_dtmf_frame(rtp, AST_FRAME_DTMF_BEGIN);
			rtp->dtmfsamples = 0;
		}
	} else if ((rtp->resp == resp) && !power) {
		f = create_dtmf_frame(rtp, AST_FRAME_DTMF_END);
		f->samples = rtp->dtmfsamples * (rtp->lastrxformat ? (rtp_get_rate(rtp->lastrxformat) / 1000) : 8);
		rtp->resp = 0;
	} else if (rtp->resp == resp)
		rtp->dtmfsamples += 20 * (rtp->lastrxformat ? (rtp_get_rate(rtp->lastrxformat) / 1000) : 8);
	rtp->dtmf_timeout = dtmftimeout;
	return f;
}

/*! 
 * \brief Process RTP DTMF and events according to RFC 2833.
 * 
 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
 * 
 * \param rtp
 * \param data
 * \param len
 * \param seqno
 * \param timestamp
 * \param frames
 * \returns
 */
static void process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct frame_list *frames)
{
	unsigned int event;
	unsigned int event_end;
	unsigned int samples;
	char resp = 0;
	struct ast_frame *f = NULL;

	/* Figure out event, event end, and samples */
	event = ntohl(*((unsigned int *)(data)));
	event >>= 24;
	event_end = ntohl(*((unsigned int *)(data)));
	event_end <<= 8;
	event_end >>= 24;
	samples = ntohl(*((unsigned int *)(data)));
	samples &= 0xFFFF;

	/* Print out debug if turned on */
	if (rtpdebug || option_debug > 2)
		ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);

	/* Figure out what digit was pressed */
	if (event < 10) {
		resp = '0' + event;
	} else if (event < 11) {
		resp = '*';
	} else if (event < 12) {
		resp = '#';
	} else if (event < 16) {
		resp = 'A' + (event - 12);
	} else if (event < 17) {	/* Event 16: Hook flash */
		resp = 'X';	
	} else {
		/* Not a supported event */
		ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
		return;
	}

	if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
		if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
			rtp->resp = resp;
			rtp->dtmf_timeout = 0;
			f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
			f->len = 0;
			rtp->lastevent = timestamp;
			AST_LIST_INSERT_TAIL(frames, f, frame_list);
		}
	} else {
		/*  The duration parameter measures the complete
		    duration of the event (from the beginning) - RFC2833.
		    Account for the fact that duration is only 16 bits long
		    (about 8 seconds at 8000 Hz) and can wrap is digit
		    is hold for too long. */
		unsigned int new_duration = rtp->dtmf_duration;
		unsigned int last_duration = new_duration & 0xFFFF;

		if (last_duration > 64000 && samples < last_duration)
			new_duration += 0xFFFF + 1;
		new_duration = (new_duration & ~0xFFFF) | samples;

		if (rtp->lastevent > seqno) {
			/* Out of order frame. Processing this can cause us to
			 * improperly duplicate incoming DTMF, so just drop
			 * this.
			 */
			return;
		}

		if (event_end & 0x80) {
			/* End event */
			if ((rtp->lastevent != seqno) && rtp->resp) {
				rtp->dtmf_duration = new_duration;
				f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
				f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
				rtp->resp = 0;
				rtp->dtmf_duration = rtp->dtmf_timeout = 0;
				AST_LIST_INSERT_TAIL(frames, f, frame_list);
			}
		} else {
			/* Begin/continuation */

			if (rtp->resp && rtp->resp != resp) {
				/* Another digit already began. End it */
				f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
				f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
				rtp->resp = 0;
				rtp->dtmf_duration = rtp->dtmf_timeout = 0;
				AST_LIST_INSERT_TAIL(frames, f, frame_list);
			}


			if (rtp->resp) {
				/* Digit continues */
				rtp->dtmf_duration = new_duration;
			} else {
				/* New digit began */
				rtp->resp = resp;
				f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_BEGIN));
				rtp->dtmf_duration = samples;
				AST_LIST_INSERT_TAIL(frames, f, frame_list);
			}

			rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
		}

		rtp->lastevent = seqno;
	}

	rtp->dtmfsamples = samples;
}

/*!
 * \brief Process Comfort Noise RTP.
 * 
 * This is incomplete at the moment.
 * 
*/
static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
{
	struct ast_frame *f = NULL;
	/* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
	   totally help us out becuase we don't have an engine to keep it going and we are not
	   guaranteed to have it every 20ms or anything */
	if (rtpdebug)
		ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);

	if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
		ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
			ast_inet_ntoa(rtp->them.sin_addr));
		ast_set_flag(rtp, FLAG_3389_WARNING);
	}
	
	/* Must have at least one byte */
	if (!len)
		return NULL;
	if (len < 24) {
		rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
		rtp->f.datalen = len - 1;
		rtp->f.offset = AST_FRIENDLY_OFFSET;
		memcpy(rtp->f.data.ptr, data + 1, len - 1);
	} else {
		rtp->f.data.ptr = NULL;
		rtp->f.offset = 0;
		rtp->f.datalen = 0;
	}
	rtp->f.frametype = AST_FRAME_CNG;
	rtp->f.subclass = data[0] & 0x7f;
	rtp->f.samples = 0;
	rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
	f = &rtp->f;
	return f;
}

static int rtpread(int *id, int fd, short events, void *cbdata)
{
	struct ast_rtp *rtp = cbdata;
	struct ast_frame *f;
	f = ast_rtp_read(rtp);
	if (f) {
		if (rtp->callback)
			rtp->callback(rtp, f, rtp->data);
	}
	return 1;
}

struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
{
	socklen_t len;
	int position, i, packetwords;
	int res;
	struct sockaddr_in sock_in;
	unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
	unsigned int *rtcpheader;
	int pt;
	struct timeval now;
	unsigned int length;
	int rc;
	double rttsec;
	uint64_t rtt = 0;
	unsigned int dlsr;
	unsigned int lsr;
	unsigned int msw;
	unsigned int lsw;
	unsigned int comp;
	struct ast_frame *f = &ast_null_frame;
	
	double reported_jitter;
	double reported_normdev_jitter_current;
	double normdevrtt_current;
	double reported_lost;
	double reported_normdev_lost_current;

	if (!rtp || !rtp->rtcp)
		return &ast_null_frame;

	len = sizeof(sock_in);
	
	res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
					0, (struct sockaddr *)&sock_in, &len);
	rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
	
	if (res < 0) {
		ast_assert(errno != EBADF);
		if (errno != EAGAIN) {
			ast_log(LOG_WARNING, "RTCP Read error: %s.  Hanging up.\n", strerror(errno));
			return NULL;
		}
		return &ast_null_frame;
	}

	packetwords = res / 4;
	
	if (rtp->nat) {
		/* Send to whoever sent to us */
		if (((rtp->rtcp->them.sin_addr.s_addr != sock_in.sin_addr.s_addr) ||
		    (rtp->rtcp->them.sin_port != sock_in.sin_port)) && 
		    ((rtp->rtcp->altthem.sin_addr.s_addr != sock_in.sin_addr.s_addr) || 
		    (rtp->rtcp->altthem.sin_port != sock_in.sin_port))) {
			memcpy(&rtp->rtcp->them, &sock_in, sizeof(rtp->rtcp->them));
			if (option_debug || rtpdebug)
				ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
		}
	}

	ast_debug(1, "Got RTCP report of %d bytes\n", res);

	/* Process a compound packet */
	position = 0;
	while (position < packetwords) {
		i = position;
		length = ntohl(rtcpheader[i]);
		pt = (length & 0xff0000) >> 16;
		rc = (length & 0x1f000000) >> 24;
		length &= 0xffff;
 
		if ((i + length) > packetwords) {
			if (option_debug || rtpdebug)
				ast_log(LOG_DEBUG, "RTCP Read too short\n");
			return &ast_null_frame;
		}
		
		if (rtcp_debug_test_addr(&sock_in)) {
		  	ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port));
		  	ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
		  	ast_verbose("Reception reports: %d\n", rc);
		  	ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
		}
 
		i += 2; /* Advance past header and ssrc */
		
		switch (pt) {
		case RTCP_PT_SR:
			gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
			rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
			rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
			rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
 
			if (rtcp_debug_test_addr(&sock_in)) {
				ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
				ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
				ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
			}
			i += 5;
			if (rc < 1)
				break;
			/* Intentional fall through */
		case RTCP_PT_RR:
			/* Don't handle multiple reception reports (rc > 1) yet */
			/* Calculate RTT per RFC */
			gettimeofday(&now, NULL);
			timeval2ntp(now, &msw, &lsw);
			if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
				comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
				lsr = ntohl(rtcpheader[i + 4]);
				dlsr = ntohl(rtcpheader[i + 5]);
				rtt = comp - lsr - dlsr;

				/* Convert end to end delay to usec (keeping the calculation in 64bit space)
				   sess->ee_delay = (eedelay * 1000) / 65536; */
				if (rtt < 4294) {
				    rtt = (rtt * 1000000) >> 16;
				} else {
				    rtt = (rtt * 1000) >> 16;
				    rtt *= 1000;
				}
				rtt = rtt / 1000.;
				rttsec = rtt / 1000.;
				rtp->rtcp->rtt = rttsec;

				if (comp - dlsr >= lsr) {
					rtp->rtcp->accumulated_transit += rttsec;

					if (rtp->rtcp->rtt_count == 0) 
						rtp->rtcp->minrtt = rttsec;

					if (rtp->rtcp->maxrtt<rttsec)
						rtp->rtcp->maxrtt = rttsec;

					if (rtp->rtcp->minrtt>rttsec)
						rtp->rtcp->minrtt = rttsec;

					normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);

					rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);

					rtp->rtcp->normdevrtt = normdevrtt_current;

					rtp->rtcp->rtt_count++;
				} else if (rtcp_debug_test_addr(&sock_in)) {
					ast_verbose("Internal RTCP NTP clock skew detected: "
							   "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
							   "diff=%d\n",
							   lsr, comp, dlsr, dlsr / 65536,
							   (dlsr % 65536) * 1000 / 65536,
							   dlsr - (comp - lsr));
				}
			}

			rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
			reported_jitter = (double) rtp->rtcp->reported_jitter;

			if (rtp->rtcp->reported_jitter_count == 0) 
				rtp->rtcp->reported_minjitter = reported_jitter;

			if (reported_jitter < rtp->rtcp->reported_minjitter) 
				rtp->rtcp->reported_minjitter = reported_jitter;

			if (reported_jitter > rtp->rtcp->reported_maxjitter) 
				rtp->rtcp->reported_maxjitter = reported_jitter;

			reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);

			rtp->rtcp->reported_stdev_jitter = stddev_compute(rtp->rtcp->reported_stdev_jitter, reported_jitter, rtp->rtcp->reported_normdev_jitter, reported_normdev_jitter_current, rtp->rtcp->reported_jitter_count);

			rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;

			rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;

			reported_lost = (double) rtp->rtcp->reported_lost;

			/* using same counter as for jitter */
			if (rtp->rtcp->reported_jitter_count == 0)
				rtp->rtcp->reported_minlost = reported_lost;

			if (reported_lost < rtp->rtcp->reported_minlost)
				rtp->rtcp->reported_minlost = reported_lost;

			if (reported_lost > rtp->rtcp->reported_maxlost) 
				rtp->rtcp->reported_maxlost = reported_lost;

			reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);

			rtp->rtcp->reported_stdev_lost = stddev_compute(rtp->rtcp->reported_stdev_lost, reported_lost, rtp->rtcp->reported_normdev_lost, reported_normdev_lost_current, rtp->rtcp->reported_jitter_count);

			rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;

			rtp->rtcp->reported_jitter_count++;

			if (rtcp_debug_test_addr(&sock_in)) {
				ast_verbose("  Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
				ast_verbose("  Packets lost so far: %d\n", rtp->rtcp->reported_lost);
				ast_verbose("  Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
				ast_verbose("  Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
				ast_verbose("  Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
				ast_verbose("  Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
				ast_verbose("  DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
				if (rtt)
					ast_verbose("  RTT: %lu(sec)\n", (unsigned long) rtt);
			}

			if (rtt) {
				manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s:%d\r\n"
								    "PT: %d(%s)\r\n"
								    "ReceptionReports: %d\r\n"
								    "SenderSSRC: %u\r\n"
								    "FractionLost: %ld\r\n"
								    "PacketsLost: %d\r\n"
								    "HighestSequence: %ld\r\n"
								    "SequenceNumberCycles: %ld\r\n"
								    "IAJitter: %u\r\n"
								    "LastSR: %lu.%010lu\r\n"
								    "DLSR: %4.4f(sec)\r\n"
								    "RTT: %llu(sec)\r\n",
								    ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port),
								    pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
								    rc,
								    rtcpheader[i + 1],
								    (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
								    rtp->rtcp->reported_lost,
								    (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
								    (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
								    rtp->rtcp->reported_jitter,
								    (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
								    ntohl(rtcpheader[i + 5])/65536.0,
								    (unsigned long long)rtt);
			} else {
				manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s:%d\r\n"
								    "PT: %d(%s)\r\n"
								    "ReceptionReports: %d\r\n"
								    "SenderSSRC: %u\r\n"
								    "FractionLost: %ld\r\n"
								    "PacketsLost: %d\r\n"
								    "HighestSequence: %ld\r\n"
								    "SequenceNumberCycles: %ld\r\n"
								    "IAJitter: %u\r\n"
								    "LastSR: %lu.%010lu\r\n"
								    "DLSR: %4.4f(sec)\r\n",
								    ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port),
								    pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
								    rc,
								    rtcpheader[i + 1],
								    (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
								    rtp->rtcp->reported_lost,
								    (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
								    (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
								    rtp->rtcp->reported_jitter,
								    (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
								    ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
								    ntohl(rtcpheader[i + 5])/65536.0);
			}
			break;
		case RTCP_PT_FUR:
			if (rtcp_debug_test_addr(&sock_in))
				ast_verbose("Received an RTCP Fast Update Request\n");
			rtp->f.frametype = AST_FRAME_CONTROL;
			rtp->f.subclass = AST_CONTROL_VIDUPDATE;
			rtp->f.datalen = 0;
			rtp->f.samples = 0;
			rtp->f.mallocd = 0;
			rtp->f.src = "RTP";
			f = &rtp->f;
			break;
		case RTCP_PT_SDES:
			if (rtcp_debug_test_addr(&sock_in))
				ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
			break;
		case RTCP_PT_BYE:
			if (rtcp_debug_test_addr(&sock_in))
				ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
			break;
		default:
			ast_debug(1, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
			break;
		}
		position += (length + 1);
	}
	rtp->rtcp->rtcp_info = 1;	
	return f;
}

static void calc_rxstamp(struct timeval *when, struct ast_rtp *rtp, unsigned int timestamp, int mark)
{
	struct timeval now;
	struct timeval tmp;
	double transit;
	double current_time;
	double d;
	double dtv;
	double prog;
	double normdev_rxjitter_current;
	int rate = rtp_get_rate(rtp->f.subclass);

	if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
		gettimeofday(&rtp->rxcore, NULL);
		rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
		/* map timestamp to a real time */
		rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
		tmp = ast_samp2tv(timestamp, rate);
		rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
		/* Round to 0.1ms for nice, pretty timestamps */
		rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
	}

	gettimeofday(&now,NULL);
	/* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
	tmp = ast_samp2tv(timestamp, rate);
	*when = ast_tvadd(rtp->rxcore, tmp);

	prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
	dtv = (double)rtp->drxcore + (double)(prog);
	current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
	transit = current_time - dtv;
	d = transit - rtp->rxtransit;
	rtp->rxtransit = transit;
	if (d<0)
		d=-d;
	rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);

	if (rtp->rtcp) {
		if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
			rtp->rtcp->maxrxjitter = rtp->rxjitter;
		if (rtp->rtcp->rxjitter_count == 1) 
			rtp->rtcp->minrxjitter = rtp->rxjitter;
		if (rtp->rxjitter < rtp->rtcp->minrxjitter)
			rtp->rtcp->minrxjitter = rtp->rxjitter;
			
		normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
		rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);

		rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
		rtp->rtcp->rxjitter_count++;
	}
}

/*! \brief Perform a Packet2Packet RTP write */
static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
{
	int res = 0, payload = 0, bridged_payload = 0, mark;
	struct rtpPayloadType rtpPT;
	int reconstruct = ntohl(rtpheader[0]);

	/* Get fields from packet */
	payload = (reconstruct & 0x7f0000) >> 16;
	mark = (((reconstruct & 0x800000) >> 23) != 0);

	/* Check what the payload value should be */
	rtpPT = ast_rtp_lookup_pt(rtp, payload);

	/* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
	if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
		return -1;

	/* Otherwise adjust bridged payload to match */
	bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);

	/* If the payload coming in is not one of the negotiated ones then send it to the core, this will cause formats to change and the bridge to break */
	if (!bridged->current_RTP_PT[bridged_payload].code)
		return -1;


	/* If the mark bit has not been sent yet... do it now */
	if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
		mark = 1;
		ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
	}

	/* Reconstruct part of the packet */
	reconstruct &= 0xFF80FFFF;
	reconstruct |= (bridged_payload << 16);
	reconstruct |= (mark << 23);
	rtpheader[0] = htonl(reconstruct);

	/* Send the packet back out */
	res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
	if (res < 0) {
		if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
			ast_debug(1, "RTP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), strerror(errno));
		} else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
			if (option_debug || rtpdebug)
				ast_debug(0, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port));
			ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
		}
		return 0;
	} else if (rtp_debug_test_addr(&bridged->them))
			ast_verbose("Sent RTP P2P packet to %s:%u (type %-2.2d, len %-6.6u)\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), bridged_payload, len - hdrlen);

	return 0;
}

struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
{
	int res;
	struct sockaddr_in sock_in;
	socklen_t len;
	unsigned int seqno;
	int version;
	int payloadtype;
	int hdrlen = 12;
	int padding;
	int mark;
	int ext;
	int cc;
	unsigned int ssrc;
	unsigned int timestamp;
	unsigned int *rtpheader;
	struct rtpPayloadType rtpPT;
	struct ast_rtp *bridged = NULL;
	int prev_seqno;
	struct frame_list frames;
	
	/* If time is up, kill it */
	if (rtp->sending_digit)
		ast_rtp_senddigit_continuation(rtp);

	len = sizeof(sock_in);
	
	/* Cache where the header will go */
	res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
					0, (struct sockaddr *)&sock_in, &len);

	/* If strict RTP protection is enabled see if we need to learn this address or if the packet should be dropped */
	if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
		/* Copy over address that this packet was received on */
		memcpy(&rtp->strict_rtp_address, &sock_in, sizeof(rtp->strict_rtp_address));
		/* Now move over to actually protecting the RTP port */
		rtp->strict_rtp_state = STRICT_RTP_CLOSED;
		ast_debug(1, "Learned remote address is %s:%d for strict RTP purposes, now protecting the port.\n", ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
	} else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
		/* If the address we previously learned doesn't match the address this packet came in on simply drop it */
		if ((rtp->strict_rtp_address.sin_addr.s_addr != sock_in.sin_addr.s_addr) || (rtp->strict_rtp_address.sin_port != sock_in.sin_port)) {
			ast_debug(1, "Received RTP packet from %s:%d, dropping due to strict RTP protection. Expected it to be from %s:%d\n", ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port), ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
			return &ast_null_frame;
		}
	}

	rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
	if (res < 0) {
		ast_assert(errno != EBADF);
		if (errno != EAGAIN) {
			ast_log(LOG_WARNING, "RTP Read error: %s.  Hanging up.\n", strerror(errno));
			return NULL;
		}
		return &ast_null_frame;
	}
	
	if (res < hdrlen) {
		ast_log(LOG_WARNING, "RTP Read too short\n");
		return &ast_null_frame;
	}

	/* Get fields */
	seqno = ntohl(rtpheader[0]);

	/* Check RTP version */
	version = (seqno & 0xC0000000) >> 30;
	if (!version) {
		/* If the two high bits are 0, this might be a
		 * STUN message, so process it. stun_handle_packet()
		 * answers to requests, and it returns STUN_ACCEPT
		 * if the request is valid.
		 */
		if ((stun_handle_packet(rtp->s, &sock_in, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
			(!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
			memcpy(&rtp->them, &sock_in, sizeof(rtp->them));
		}
		return &ast_null_frame;
	}

#if 0	/* Allow to receive RTP stream with closed transmission path */
	/* If we don't have the other side's address, then ignore this */
	if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
		return &ast_null_frame;
#endif

	/* Send to whoever send to us if NAT is turned on */
	if (rtp->nat) {
		if (((rtp->them.sin_addr.s_addr != sock_in.sin_addr.s_addr) ||
		    (rtp->them.sin_port != sock_in.sin_port)) && 
		    ((rtp->altthem.sin_addr.s_addr != sock_in.sin_addr.s_addr) ||
		    (rtp->altthem.sin_port != sock_in.sin_port))) {
			rtp->them = sock_in;
			if (rtp->rtcp) {
				int h = 0;
				memcpy(&rtp->rtcp->them, &sock_in, sizeof(rtp->rtcp->them));
				h = ntohs(rtp->them.sin_port);
				rtp->rtcp->them.sin_port = htons(h + 1);
			}
			rtp->rxseqno = 0;
			ast_set_flag(rtp, FLAG_NAT_ACTIVE);
			if (option_debug || rtpdebug)
				ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
		}
	}

	/* If we are bridged to another RTP stream, send direct */
	if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
		return &ast_null_frame;

	if (version != 2)
		return &ast_null_frame;

	payloadtype = (seqno & 0x7f0000) >> 16;
	padding = seqno & (1 << 29);
	mark = seqno & (1 << 23);
	ext = seqno & (1 << 28);
	cc = (seqno & 0xF000000) >> 24;
	seqno &= 0xffff;
	timestamp = ntohl(rtpheader[1]);
	ssrc = ntohl(rtpheader[2]);
	
	AST_LIST_HEAD_INIT_NOLOCK(&frames);
	/* Force a marker bit and change SSRC if the SSRC changes */
	if (rtp->rxssrc && rtp->rxssrc != ssrc) {
		struct ast_frame *f, srcupdate = {
			AST_FRAME_CONTROL,
			.subclass = AST_CONTROL_SRCCHANGE,
		};

		if (!mark) {
			if (option_debug || rtpdebug) {
				ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
			}
			mark = 1;
		}
		f = ast_frisolate(&srcupdate);
		AST_LIST_INSERT_TAIL(&frames, f, frame_list);
	}

	rtp->rxssrc = ssrc;
	
	if (padding) {
		/* Remove padding bytes */
		res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
	}
	
	if (cc) {
		/* CSRC fields present */
		hdrlen += cc*4;
	}

	if (ext) {
		/* RTP Extension present */
		hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
		hdrlen += 4;
		if (option_debug) {
			int profile;
			profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
			if (profile == 0x505a)
				ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
			else
				ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
		}
	}

	if (res < hdrlen) {
		ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
		return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
	}

	rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */

	if (rtp->rxcount==1) {
		/* This is the first RTP packet successfully received from source */
		rtp->seedrxseqno = seqno;
	}

	/* Do not schedule RR if RTCP isn't run */
	if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
		/* Schedule transmission of Receiver Report */
		rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
	}
	if ((int)rtp->lastrxseqno - (int)seqno  > 100) /* if so it would indicate that the sender cycled; allow for misordering */
		rtp->cycles += RTP_SEQ_MOD;
	
	prev_seqno = rtp->lastrxseqno;

	rtp->lastrxseqno = seqno;
	
	if (!rtp->themssrc)
		rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
	
	if (rtp_debug_test_addr(&sock_in))
		ast_verbose("Got  RTP packet from    %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
			ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port), payloadtype, seqno, timestamp,res - hdrlen);

	rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
	if (!rtpPT.isAstFormat) {
		struct ast_frame *f = NULL;

		/* This is special in-band data that's not one of our codecs */
		if (rtpPT.code == AST_RTP_DTMF) {
			/* It's special -- rfc2833 process it */
			if (rtp_debug_test_addr(&sock_in)) {
				unsigned char *data;
				unsigned int event;
				unsigned int event_end;
				unsigned int duration;
				data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
				event = ntohl(*((unsigned int *)(data)));
				event >>= 24;
				event_end = ntohl(*((unsigned int *)(data)));
				event_end <<= 8;
				event_end >>= 24;
				duration = ntohl(*((unsigned int *)(data)));
				duration &= 0xFFFF;
				ast_verbose("Got  RTP RFC2833 from   %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
			}
			/* process_rfc2833 may need to return multiple frames. We do this
			 * by passing the pointer to the frame list to it so that the method
			 * can append frames to the list as needed
			 */
			process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &frames);
		} else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
			/* It's really special -- process it the Cisco way */
			if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
				f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
				rtp->lastevent = seqno;
			}
		} else if (rtpPT.code == AST_RTP_CN) {
			/* Comfort Noise */
			f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
		} else {
			ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
		}
		if (f) {
			AST_LIST_INSERT_TAIL(&frames, f, frame_list);
		}
		/* Even if no frame was returned by one of the above methods,
		 * we may have a frame to return in our frame list
		 */
		if (!AST_LIST_EMPTY(&frames)) {
			return AST_LIST_FIRST(&frames);
		}
		return &ast_null_frame;
	}
	rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
	rtp->f.frametype = (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) ? AST_FRAME_VOICE : (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;

	rtp->rxseqno = seqno;

	if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
		rtp->dtmf_timeout = 0;

		if (rtp->resp) {
			struct ast_frame *f;
			f = create_dtmf_frame(rtp, AST_FRAME_DTMF_END);
			f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
			rtp->resp = 0;
			rtp->dtmf_timeout = rtp->dtmf_duration = 0;
			AST_LIST_INSERT_TAIL(&frames, f, frame_list);
			return AST_LIST_FIRST(&frames);
		}
	}

	/* Record received timestamp as last received now */
	rtp->lastrxts = timestamp;

	rtp->f.mallocd = 0;
	rtp->f.datalen = res - hdrlen;
	rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
	rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
	rtp->f.seqno = seqno;

	if (rtp->f.subclass == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
		  unsigned char *data = rtp->f.data.ptr;
		  
		  memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
		  rtp->f.datalen +=3;
		  *data++ = 0xEF;
		  *data++ = 0xBF;
		  *data = 0xBD;
	}
 
	if (rtp->f.subclass == AST_FORMAT_T140RED) {
		unsigned char *data = rtp->f.data.ptr;
		unsigned char *header_end;
		int num_generations;
		int header_length;
		int length;
		int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
		int x;

		rtp->f.subclass = AST_FORMAT_T140;
		header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
		if (header_end == NULL) {
			return &ast_null_frame;
		}
		header_end++;
		
		header_length = header_end - data;
		num_generations = header_length / 4;
		length = header_length;

		if (!diff) {
			for (x = 0; x < num_generations; x++)
				length += data[x * 4 + 3];
			
			if (!(rtp->f.datalen - length))
				return &ast_null_frame;
			
			rtp->f.data.ptr += length;
			rtp->f.datalen -= length;
		} else if (diff > num_generations && diff < 10) {
			length -= 3;
			rtp->f.data.ptr += length;
			rtp->f.datalen -= length;
			
			data = rtp->f.data.ptr;
			*data++ = 0xEF;
			*data++ = 0xBF;
			*data = 0xBD;
		} else 	{
			for ( x = 0; x < num_generations - diff; x++) 
				length += data[x * 4 + 3];
			
			rtp->f.data.ptr += length;
			rtp->f.datalen -= length;
		}
	}

	if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
		rtp->f.samples = ast_codec_get_samples(&rtp->f);
		if (rtp->f.subclass == AST_FORMAT_SLINEAR) 
			ast_frame_byteswap_be(&rtp->f);
		calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
		/* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
		ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
		rtp->f.ts = timestamp / (rtp_get_rate(rtp->f.subclass) / 1000);
		rtp->f.len = rtp->f.samples / ((ast_format_rate(rtp->f.subclass) / 1000));
	} else if (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
		/* Video -- samples is # of samples vs. 90000 */
		if (!rtp->lastividtimestamp)
			rtp->lastividtimestamp = timestamp;
		rtp->f.samples = timestamp - rtp->lastividtimestamp;
		rtp->lastividtimestamp = timestamp;
		rtp->f.delivery.tv_sec = 0;
		rtp->f.delivery.tv_usec = 0;
		/* Pass the RTP marker bit as bit 0 in the subclass field.
		 * This is ok because subclass is actually a bitmask, and
		 * the low bits represent audio formats, that are not
		 * involved here since we deal with video.
		 */
		if (mark)
			rtp->f.subclass |= 0x1;
	} else {
		/* TEXT -- samples is # of samples vs. 1000 */
		if (!rtp->lastitexttimestamp)
			rtp->lastitexttimestamp = timestamp;
		rtp->f.samples = timestamp - rtp->lastitexttimestamp;
		rtp->lastitexttimestamp = timestamp;
		rtp->f.delivery.tv_sec = 0;
		rtp->f.delivery.tv_usec = 0;
	}
	rtp->f.src = "RTP";

	AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
	return AST_LIST_FIRST(&frames);
}

/* The following array defines the MIME Media type (and subtype) for each
   of our codecs, or RTP-specific data type. */
static const struct mimeType {
	struct rtpPayloadType payloadType;
	char *type;
	char *subtype;
	unsigned int sample_rate;
} mimeTypes[] = {
	{{1, AST_FORMAT_G723_1}, "audio", "G723", 8000},
	{{1, AST_FORMAT_GSM}, "audio", "GSM", 8000},
	{{1, AST_FORMAT_ULAW}, "audio", "PCMU", 8000},
	{{1, AST_FORMAT_ULAW}, "audio", "G711U", 8000},
	{{1, AST_FORMAT_ALAW}, "audio", "PCMA", 8000},
	{{1, AST_FORMAT_ALAW}, "audio", "G711A", 8000},
	{{1, AST_FORMAT_G726}, "audio", "G726-32", 8000},
	{{1, AST_FORMAT_ADPCM}, "audio", "DVI4", 8000},
	{{1, AST_FORMAT_SLINEAR}, "audio", "L16", 8000},
	{{1, AST_FORMAT_LPC10}, "audio", "LPC", 8000},
	{{1, AST_FORMAT_G729A}, "audio", "G729", 8000},
	{{1, AST_FORMAT_G729A}, "audio", "G729A", 8000},
	{{1, AST_FORMAT_G729A}, "audio", "G.729", 8000},
	{{1, AST_FORMAT_SPEEX}, "audio", "speex", 8000},
	{{1, AST_FORMAT_ILBC}, "audio", "iLBC", 8000},
	/* this is the sample rate listed in the RTP profile for the G.722
	   codec, *NOT* the actual sample rate of the media stream
	*/
	{{1, AST_FORMAT_G722}, "audio", "G722", 8000},
	{{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32", 8000},
	{{0, AST_RTP_DTMF}, "audio", "telephone-event", 8000},
	{{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event", 8000},
	{{0, AST_RTP_CN}, "audio", "CN", 8000},
	{{1, AST_FORMAT_JPEG}, "video", "JPEG", 90000},
	{{1, AST_FORMAT_PNG}, "video", "PNG", 90000},
	{{1, AST_FORMAT_H261}, "video", "H261", 90000},
	{{1, AST_FORMAT_H263}, "video", "H263", 90000},
	{{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998", 90000},
	{{1, AST_FORMAT_H264}, "video", "H264", 90000},
	{{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES", 90000},
	{{1, AST_FORMAT_T140RED}, "text", "RED", 1000},
	{{1, AST_FORMAT_T140}, "text", "T140", 1000},
	{{1, AST_FORMAT_SIREN7}, "audio", "G7221", 16000},
	{{1, AST_FORMAT_SIREN14}, "audio", "G7221", 32000},
};

/*! 
 * \brief Mapping between Asterisk codecs and rtp payload types
 *
 * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
 * also, our own choices for dynamic payload types.  This is our master
 * table for transmission 
 * 
 * See http://www.iana.org/assignments/rtp-parameters for a list of
 * assigned values
 */
static const struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
	[0] = {1, AST_FORMAT_ULAW},
#ifdef USE_DEPRECATED_G726
	[2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
#endif
	[3] = {1, AST_FORMAT_GSM},
	[4] = {1, AST_FORMAT_G723_1},
	[5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
	[6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
	[7] = {1, AST_FORMAT_LPC10},
	[8] = {1, AST_FORMAT_ALAW},
	[9] = {1, AST_FORMAT_G722},
	[10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
	[11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
	[13] = {0, AST_RTP_CN},
	[16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
	[17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
	[18] = {1, AST_FORMAT_G729A},
	[19] = {0, AST_RTP_CN},		/* Also used for CN */
	[26] = {1, AST_FORMAT_JPEG},
	[31] = {1, AST_FORMAT_H261},
	[34] = {1, AST_FORMAT_H263},
	[97] = {1, AST_FORMAT_ILBC},
	[98] = {1, AST_FORMAT_H263_PLUS},
	[99] = {1, AST_FORMAT_H264},
	[101] = {0, AST_RTP_DTMF},
	[102] = {1, AST_FORMAT_SIREN7},
	[103] = {1, AST_FORMAT_H263_PLUS},
	[104] = {1, AST_FORMAT_MP4_VIDEO},
	[105] = {1, AST_FORMAT_T140RED},	/* Real time text chat (with redundancy encoding) */
	[106] = {1, AST_FORMAT_T140},	/* Real time text chat */
	[110] = {1, AST_FORMAT_SPEEX},
	[111] = {1, AST_FORMAT_G726},
	[112] = {1, AST_FORMAT_G726_AAL2},
	[115] = {1, AST_FORMAT_SIREN14},
	[121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
};

void ast_rtp_pt_clear(struct ast_rtp* rtp) 
{
	int i;

	if (!rtp)
		return;

	rtp_bridge_lock(rtp);

	for (i = 0; i < MAX_RTP_PT; ++i) {
		rtp->current_RTP_PT[i].isAstFormat = 0;
		rtp->current_RTP_PT[i].code = 0;
	}

	rtp->rtp_lookup_code_cache_isAstFormat = 0;
	rtp->rtp_lookup_code_cache_code = 0;
	rtp->rtp_lookup_code_cache_result = 0;

	rtp_bridge_unlock(rtp);
}

void ast_rtp_pt_default(struct ast_rtp* rtp) 
{
	int i;

	rtp_bridge_lock(rtp);

	/* Initialize to default payload types */
	for (i = 0; i < MAX_RTP_PT; ++i) {
		rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
		rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
	}

	rtp->rtp_lookup_code_cache_isAstFormat = 0;
	rtp->rtp_lookup_code_cache_code = 0;
	rtp->rtp_lookup_code_cache_result = 0;

	rtp_bridge_unlock(rtp);
}

void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
{
	unsigned int i;

	rtp_bridge_lock(dest);
	rtp_bridge_lock(src);

	for (i = 0; i < MAX_RTP_PT; ++i) {
		dest->current_RTP_PT[i].isAstFormat = 
			src->current_RTP_PT[i].isAstFormat;
		dest->current_RTP_PT[i].code = 
			src->current_RTP_PT[i].code; 
	}
	dest->rtp_lookup_code_cache_isAstFormat = 0;
	dest->rtp_lookup_code_cache_code = 0;
	dest->rtp_lookup_code_cache_result = 0;

	rtp_bridge_unlock(src);
	rtp_bridge_unlock(dest);
}

/*! \brief Get channel driver interface structure */
static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
{
	struct ast_rtp_protocol *cur = NULL;

	AST_RWLIST_RDLOCK(&protos);
	AST_RWLIST_TRAVERSE(&protos, cur, list) {
		if (cur->type == chan->tech->type)
			break;
	}
	AST_RWLIST_UNLOCK(&protos);

	return cur;
}

int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
{
	struct ast_rtp *destp = NULL, *srcp = NULL;		/* Audio RTP Channels */
	struct ast_rtp *vdestp = NULL, *vsrcp = NULL;		/* Video RTP channels */
	struct ast_rtp *tdestp = NULL, *tsrcp = NULL;		/* Text RTP channels */
	struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
	enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED, text_dest_res = AST_RTP_GET_FAILED;
	enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED, text_src_res = AST_RTP_GET_FAILED;
	int srccodec, destcodec, nat_active = 0;

	/* Lock channels */
	ast_channel_lock(c0);
	if (c1) {
		while (ast_channel_trylock(c1)) {
			ast_channel_unlock(c0);
			usleep(1);
			ast_channel_lock(c0);
		}
	}

	/* Find channel driver interfaces */
	destpr = get_proto(c0);
	if (c1)
		srcpr = get_proto(c1);
	if (!destpr) {
		ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
		ast_channel_unlock(c0);
		if (c1)
			ast_channel_unlock(c1);
		return -1;
	}
	if (!srcpr) {
		ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
		ast_channel_unlock(c0);
		if (c1)
			ast_channel_unlock(c1);
		return -1;
	}

	/* Get audio, video  and text interface (if native bridge is possible) */
	audio_dest_res = destpr->get_rtp_info(c0, &destp);
	video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
	text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
	if (srcpr) {
		audio_src_res = srcpr->get_rtp_info(c1, &srcp);
		video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
		text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
	}

	/* Check if bridge is still possible (In SIP directmedia=no stops this, like NAT) */
	if (audio_dest_res != AST_RTP_TRY_NATIVE || (video_dest_res != AST_RTP_GET_FAILED && video_dest_res != AST_RTP_TRY_NATIVE)) {
		/* Somebody doesn't want to play... */
		ast_channel_unlock(c0);
		if (c1)
			ast_channel_unlock(c1);
		return -1;
	}
	if (audio_src_res == AST_RTP_TRY_NATIVE && (video_src_res == AST_RTP_GET_FAILED || video_src_res == AST_RTP_TRY_NATIVE) && srcpr->get_codec)
		srccodec = srcpr->get_codec(c1);
	else
		srccodec = 0;
	if (audio_dest_res == AST_RTP_TRY_NATIVE && (video_dest_res == AST_RTP_GET_FAILED || video_dest_res == AST_RTP_TRY_NATIVE) && destpr->get_codec)
		destcodec = destpr->get_codec(c0);
	else
		destcodec = 0;
	/* Ensure we have at least one matching codec */
	if (srcp && !(srccodec & destcodec)) {
		ast_channel_unlock(c0);
		ast_channel_unlock(c1);
		return 0;
	}
	/* Consider empty media as non-existent */
	if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
		srcp = NULL;
	if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
		nat_active = 1;
	/* Bridge media early */
	if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
		ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
	ast_channel_unlock(c0);
	if (c1)
		ast_channel_unlock(c1);
	ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
	return 0;
}

int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
{
	struct ast_rtp *destp = NULL, *srcp = NULL;		/* Audio RTP Channels */
	struct ast_rtp *vdestp = NULL, *vsrcp = NULL;		/* Video RTP channels */
	struct ast_rtp *tdestp = NULL, *tsrcp = NULL;		/* Text RTP channels */
	struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
	enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED, text_dest_res = AST_RTP_GET_FAILED;
	enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED, text_src_res = AST_RTP_GET_FAILED; 
	int srccodec, destcodec;

	/* Lock channels */
	ast_channel_lock(dest);
	while (ast_channel_trylock(src)) {
		ast_channel_unlock(dest);
		usleep(1);
		ast_channel_lock(dest);
	}

	/* Find channel driver interfaces */
	if (!(destpr = get_proto(dest))) {
		ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
		ast_channel_unlock(dest);
		ast_channel_unlock(src);
		return 0;
	}
	if (!(srcpr = get_proto(src))) {
		ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
		ast_channel_unlock(dest);
		ast_channel_unlock(src);
		return 0;
	}

	/* Get audio and video interface (if native bridge is possible) */
	audio_dest_res = destpr->get_rtp_info(dest, &destp);
	video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
	text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
	audio_src_res = srcpr->get_rtp_info(src, &srcp);
	video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
	text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;

	/* Ensure we have at least one matching codec */
	if (srcpr->get_codec)
		srccodec = srcpr->get_codec(src);
	else
		srccodec = 0;
	if (destpr->get_codec)
		destcodec = destpr->get_codec(dest);
	else
		destcodec = 0;

	/* Check if bridge is still possible (In SIP directmedia=no stops this, like NAT) */
	if (audio_dest_res != AST_RTP_TRY_NATIVE || (video_dest_res != AST_RTP_GET_FAILED && video_dest_res != AST_RTP_TRY_NATIVE) || audio_src_res != AST_RTP_TRY_NATIVE || (video_src_res != AST_RTP_GET_FAILED && video_src_res != AST_RTP_TRY_NATIVE) || !(srccodec & destcodec)) {
		/* Somebody doesn't want to play... */
		ast_channel_unlock(dest);
		ast_channel_unlock(src);
		return 0;
	}
	ast_rtp_pt_copy(destp, srcp);
	if (vdestp && vsrcp)
		ast_rtp_pt_copy(vdestp, vsrcp);
	if (tdestp && tsrcp)
		ast_rtp_pt_copy(tdestp, tsrcp);
	if (media) {
		/* Bridge early */
		if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
			ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
	}
	ast_channel_unlock(dest);
	ast_channel_unlock(src);
	ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
	return 1;
}

/*! \brief  Make a note of a RTP payload type that was seen in a SDP "m=" line.
 * By default, use the well-known value for this type (although it may 
 * still be set to a different value by a subsequent "a=rtpmap:" line)
 */
void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt) 
{
	if (pt < 0 || pt >= MAX_RTP_PT || static_RTP_PT[pt].code == 0) 
		return; /* bogus payload type */

	rtp_bridge_lock(rtp);
	rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
	rtp_bridge_unlock(rtp);
} 

/*! \brief remove setting from payload type list if the rtpmap header indicates
	an unknown media type */
void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt) 
{
	if (pt < 0 || pt >= MAX_RTP_PT)
		return; /* bogus payload type */

	rtp_bridge_lock(rtp);
	rtp->current_RTP_PT[pt].isAstFormat = 0;
	rtp->current_RTP_PT[pt].code = 0;
	rtp_bridge_unlock(rtp);
}

/*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
 * an SDP "a=rtpmap:" line.
 * \return 0 if the MIME type was found and set, -1 if it wasn't found
 */
int ast_rtp_set_rtpmap_type_rate(struct ast_rtp *rtp, int pt,
				 char *mimeType, char *mimeSubtype,
				 enum ast_rtp_options options,
				 unsigned int sample_rate)
{
	unsigned int i;
	int found = 0;

	if (pt < 0 || pt >= MAX_RTP_PT)
		return -1; /* bogus payload type */

	rtp_bridge_lock(rtp);

	for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
		const struct mimeType *t = &mimeTypes[i];

		if (strcasecmp(mimeSubtype, t->subtype)) {
			continue;
		}

		if (strcasecmp(mimeType, t->type)) {
			continue;
		}

		/* if both sample rates have been supplied, and they don't match,
		   then this not a match; if one has not been supplied, then the
		   rates are not compared */
		if (sample_rate && t->sample_rate &&
		    (sample_rate != t->sample_rate)) {
			continue;
		}

		found = 1;
		rtp->current_RTP_PT[pt] = t->payloadType;

		if ((t->payloadType.code == AST_FORMAT_G726) &&
		    t->payloadType.isAstFormat &&
		    (options & AST_RTP_OPT_G726_NONSTANDARD)) {
			rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
		}

		break;
	}

	rtp_bridge_unlock(rtp);

	return (found ? 0 : -2);
}

int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
			    char *mimeType, char *mimeSubtype,
			    enum ast_rtp_options options)
{
	return ast_rtp_set_rtpmap_type_rate(rtp, pt, mimeType, mimeSubtype, options, 0);
}

/*! \brief Return the union of all of the codecs that were set by rtp_set...() calls 
 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
void ast_rtp_get_current_formats(struct ast_rtp* rtp,
				 int* astFormats, int* nonAstFormats)
{
	int pt;
	
	rtp_bridge_lock(rtp);
	
	*astFormats = *nonAstFormats = 0;
	for (pt = 0; pt < MAX_RTP_PT; ++pt) {
		if (rtp->current_RTP_PT[pt].isAstFormat) {
			*astFormats |= rtp->current_RTP_PT[pt].code;
		} else {
			*nonAstFormats |= rtp->current_RTP_PT[pt].code;
		}
	}

	rtp_bridge_unlock(rtp);
}

struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt) 
{
	struct rtpPayloadType result;

	result.isAstFormat = result.code = 0;

	if (pt < 0 || pt >= MAX_RTP_PT) 
		return result; /* bogus payload type */

	/* Start with negotiated codecs */
	rtp_bridge_lock(rtp);
	result = rtp->current_RTP_PT[pt];
	rtp_bridge_unlock(rtp);

	/* If it doesn't exist, check our static RTP type list, just in case */
	if (!result.code) 
		result = static_RTP_PT[pt];

	return result;
}

/*! \brief Looks up an RTP code out of our *static* outbound list */
int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
{
	int pt = 0;

	rtp_bridge_lock(rtp);

	if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
		code == rtp->rtp_lookup_code_cache_code) {
		/* Use our cached mapping, to avoid the overhead of the loop below */
		pt = rtp->rtp_lookup_code_cache_result;
		rtp_bridge_unlock(rtp);
		return pt;
	}

	/* Check the dynamic list first */
	for (pt = 0; pt < MAX_RTP_PT; ++pt) {
		if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
			rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
			rtp->rtp_lookup_code_cache_code = code;
			rtp->rtp_lookup_code_cache_result = pt;
			rtp_bridge_unlock(rtp);
			return pt;
		}
	}

	/* Then the static list */
	for (pt = 0; pt < MAX_RTP_PT; ++pt) {
		if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
			rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
  			rtp->rtp_lookup_code_cache_code = code;
			rtp->rtp_lookup_code_cache_result = pt;
			rtp_bridge_unlock(rtp);
			return pt;
		}
	}

	rtp_bridge_unlock(rtp);

	return -1;
}

const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
				  enum ast_rtp_options options)
{
	unsigned int i;

	for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
		if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
			if (isAstFormat &&
			    (code == AST_FORMAT_G726_AAL2) &&
			    (options & AST_RTP_OPT_G726_NONSTANDARD))
				return "G726-32";
			else
				return mimeTypes[i].subtype;
		}
	}

	return "";
}

unsigned int ast_rtp_lookup_sample_rate(int isAstFormat, int code)
{
	unsigned int i;

	for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
		if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
			return mimeTypes[i].sample_rate;
		}
	}

	return 0;
}

char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
				   const int isAstFormat, enum ast_rtp_options options)
{
	int format;
	unsigned len;
	char *end = buf;
	char *start = buf;

	if (!buf || !size)
		return NULL;

	snprintf(end, size, "0x%x (", capability);

	len = strlen(end);
	end += len;
	size -= len;
	start = end;

	for (format = 1; format < AST_RTP_MAX; format <<= 1) {
		if (capability & format) {
			const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);

			snprintf(end, size, "%s|", name);
			len = strlen(end);
			end += len;
			size -= len;
		}
	}

	if (start == end)
		ast_copy_string(start, "nothing)", size); 
	else if (size > 1)
		*(end -1) = ')';
	
	return buf;
}

/*! \brief Open RTP or RTCP socket for a session.
 * Print a message on failure. 
 */
static int rtp_socket(const char *type)
{
	int s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s < 0) {
		if (type == NULL)
			type = "RTP/RTCP";
		ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
	} else {
		long flags = fcntl(s, F_GETFL);
		fcntl(s, F_SETFL, flags | O_NONBLOCK);
#ifdef SO_NO_CHECK
		if (nochecksums)
			setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
#endif
	}
	return s;
}

/*!
 * \brief Initialize a new RTCP session.
 * 
 * \returns The newly initialized RTCP session.
 */
static struct ast_rtcp *ast_rtcp_new(void)
{
	struct ast_rtcp *rtcp;

	if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
		return NULL;
	rtcp->s = rtp_socket("RTCP");
	rtcp->us.sin_family = AF_INET;
	rtcp->them.sin_family = AF_INET;
	rtcp->schedid = -1;

	if (rtcp->s < 0) {
		ast_free(rtcp);
		return NULL;
	}

	return rtcp;
}

/*!
 * \brief Initialize a new RTP structure.
 *
 */
void ast_rtp_new_init(struct ast_rtp *rtp)
{
#ifdef P2P_INTENSE
	ast_mutex_init(&rtp->bridge_lock);
#endif

	rtp->them.sin_family = AF_INET;
	rtp->us.sin_family = AF_INET;
	rtp->ssrc = ast_random();
	rtp->seqno = ast_random() & 0xffff;
	ast_set_flag(rtp, FLAG_HAS_DTMF);
	rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
}

struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
{
	struct ast_rtp *rtp;
	int x;
	int startplace;
	
	if (!(rtp = ast_calloc(1, sizeof(*rtp))))
		return NULL;

	ast_rtp_new_init(rtp);

	rtp->s = rtp_socket("RTP");
	if (rtp->s < 0)
		goto fail;
	if (sched && rtcpenable) {
		rtp->sched = sched;
		rtp->rtcp = ast_rtcp_new();
	}
	
	/*
	 * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
	 * Start from a random (even, by RTP spec) port number, and
	 * iterate until success or no ports are available.
	 * Note that the requirement of RTP port being even, or RTCP being the
	 * next one, cannot be enforced in presence of a NAT box because the
	 * mapping is not under our control.
	 */
	x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
	x = x & ~1;		/* make it an even number */
	startplace = x;		/* remember the starting point */
	/* this is constant across the loop */
	rtp->us.sin_addr = addr;
	if (rtp->rtcp)
		rtp->rtcp->us.sin_addr = addr;
	for (;;) {
		rtp->us.sin_port = htons(x);
		if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
			/* bind succeeded, if no rtcp then we are done */
			if (!rtp->rtcp)
				break;
			/* have rtcp, try to bind it */
			rtp->rtcp->us.sin_port = htons(x + 1);
			if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
				break;	/* success again, we are really done */
			/*
			 * RTCP bind failed, so close and recreate the
			 * already bound RTP socket for the next round.
			 */
			close(rtp->s);
			rtp->s = rtp_socket("RTP");
			if (rtp->s < 0)
				goto fail;
		}
		/*
		 * If we get here, there was an error in one of the bind()
		 * calls, so make sure it is nothing unexpected.
		 */
		if (errno != EADDRINUSE) {
			/* We got an error that wasn't expected, abort! */
			ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
			goto fail;
		}
		/*
		 * One of the ports is in use. For the next iteration,
		 * increment by two and handle wraparound.
		 * If we reach the starting point, then declare failure.
		 */
		x += 2;
		if (x > rtpend)
			x = (rtpstart + 1) & ~1;
		if (x == startplace) {
			ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
			goto fail;
		}
	}
	rtp->sched = sched;
	rtp->io = io;
	if (callbackmode) {
		rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
		ast_set_flag(rtp, FLAG_CALLBACK_MODE);
	}
	ast_rtp_pt_default(rtp);
	return rtp;

fail:
	if (rtp->s >= 0)
		close(rtp->s);
	if (rtp->rtcp) {
		close(rtp->rtcp->s);
		ast_free(rtp->rtcp);
	}
	ast_free(rtp);
	return NULL;
}

struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
{
	struct in_addr ia;

	memset(&ia, 0, sizeof(ia));
	return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
}

int ast_rtp_setqos(struct ast_rtp *rtp, int type_of_service, int class_of_service, char *desc)
{
	return ast_netsock_set_qos(rtp->s, type_of_service, class_of_service, desc);
}

void ast_rtp_new_source(struct ast_rtp *rtp)
{
	if (rtp) {
		rtp->set_marker_bit = 1;
		ast_debug(3, "Setting the marker bit due to a source update\n");
	}
}

void ast_rtp_change_source(struct ast_rtp *rtp)
{
	if (rtp) {
		unsigned int ssrc = ast_random();

		rtp->set_marker_bit = 1;
		ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
		rtp->ssrc = ssrc;
	}
}

void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
{
	rtp->them.sin_port = them->sin_port;
	rtp->them.sin_addr = them->sin_addr;
	if (rtp->rtcp) {
		int h = ntohs(them->sin_port);
		rtp->rtcp->them.sin_port = htons(h + 1);
		rtp->rtcp->them.sin_addr = them->sin_addr;
	}
	rtp->rxseqno = 0;
	/* If strict RTP protection is enabled switch back to the learn state so we don't drop packets from above */
	if (strictrtp)
		rtp->strict_rtp_state = STRICT_RTP_LEARN;
}

void ast_rtp_set_alt_peer(struct ast_rtp *rtp, struct sockaddr_in *alt)
{
	rtp->altthem.sin_port = alt->sin_port;
	rtp->altthem.sin_addr = alt->sin_addr;
	if (rtp->rtcp) {
		rtp->rtcp->altthem.sin_port = htons(ntohs(alt->sin_port) + 1);
		rtp->rtcp->altthem.sin_addr = alt->sin_addr;
	}
}

int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
{
	if ((them->sin_family != AF_INET) ||
		(them->sin_port != rtp->them.sin_port) ||
		(them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
		them->sin_family = AF_INET;
		them->sin_port = rtp->them.sin_port;
		them->sin_addr = rtp->them.sin_addr;
		return 1;
	}
	return 0;
}

void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
{
	*us = rtp->us;
}

struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
{
	struct ast_rtp *bridged = NULL;

	rtp_bridge_lock(rtp);
	bridged = rtp->bridged;
	rtp_bridge_unlock(rtp);

	return bridged;
}

void ast_rtp_stop(struct ast_rtp *rtp)
{
	if (rtp->rtcp) {
		AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
	}
	if (rtp->red) {
		AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
		free(rtp->red);
		rtp->red = NULL;
	}

	memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
	memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
	if (rtp->rtcp) {
		memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
		memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
	}
	
	ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
}

void ast_rtp_reset(struct ast_rtp *rtp)
{
	memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
	memset(&rtp->txcore, 0, sizeof(rtp->txcore));
	memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
	rtp->lastts = 0;
	rtp->lastdigitts = 0;
	rtp->lastrxts = 0;
	rtp->lastividtimestamp = 0;
	rtp->lastovidtimestamp = 0;
	rtp->lastitexttimestamp = 0;
	rtp->lastotexttimestamp = 0;
	rtp->lasteventseqn = 0;
	rtp->lastevent = 0;
	rtp->lasttxformat = 0;
	rtp->lastrxformat = 0;
	rtp->dtmf_timeout = 0;
	rtp->dtmfsamples = 0;
	rtp->seqno = 0;
	rtp->rxseqno = 0;
}

/*! Get QoS values from RTP and RTCP data (used in "sip show channelstats") */
unsigned int ast_rtp_get_qosvalue(struct ast_rtp *rtp, enum ast_rtp_qos_vars value)
{
	if (rtp == NULL) {
		if (option_debug > 1)
			ast_log(LOG_DEBUG, "NO RTP Structure? Kidding me? \n");
		return 0;
	}
	if (option_debug > 1 && rtp->rtcp == NULL) {
		ast_log(LOG_DEBUG, "NO RTCP structure. Maybe in RTP p2p bridging mode? \n");
	}

	switch (value) {
	case AST_RTP_TXCOUNT:
		return (unsigned int) rtp->txcount;
	case AST_RTP_RXCOUNT:
		return (unsigned int) rtp->rxcount;
	case AST_RTP_TXJITTER:
		return (unsigned int) (rtp->rxjitter * 1000.0);
	case AST_RTP_RXJITTER:
		return (unsigned int) (rtp->rtcp ? (rtp->rtcp->reported_jitter / (unsigned int) 65536.0) : 0);
	case AST_RTP_RXPLOSS:
		return rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0;
	case AST_RTP_TXPLOSS:
		return rtp->rtcp ? rtp->rtcp->reported_lost : 0;
	case AST_RTP_RTT:
		return (unsigned int) (rtp->rtcp ? (rtp->rtcp->rtt * 100) : 0);
	}
	return 0;	/* To make the compiler happy */
}

static double __ast_rtp_get_qos(struct ast_rtp *rtp, const char *qos, int *found)
{
	*found = 1;

	if (!strcasecmp(qos, "remote_maxjitter"))
		return rtp->rtcp->reported_maxjitter * 1000.0;
	if (!strcasecmp(qos, "remote_minjitter"))
		return rtp->rtcp->reported_minjitter * 1000.0;
	if (!strcasecmp(qos, "remote_normdevjitter"))
		return rtp->rtcp->reported_normdev_jitter * 1000.0;
	if (!strcasecmp(qos, "remote_stdevjitter"))
		return sqrt(rtp->rtcp->reported_stdev_jitter) * 1000.0;

	if (!strcasecmp(qos, "local_maxjitter"))
		return rtp->rtcp->maxrxjitter * 1000.0;
	if (!strcasecmp(qos, "local_minjitter"))
		return rtp->rtcp->minrxjitter * 1000.0;
	if (!strcasecmp(qos, "local_normdevjitter"))
		return rtp->rtcp->normdev_rxjitter * 1000.0;
	if (!strcasecmp(qos, "local_stdevjitter"))
		return sqrt(rtp->rtcp->stdev_rxjitter) * 1000.0;

	if (!strcasecmp(qos, "maxrtt"))
		return rtp->rtcp->maxrtt * 1000.0;
	if (!strcasecmp(qos, "minrtt"))
		return rtp->rtcp->minrtt * 1000.0;
	if (!strcasecmp(qos, "normdevrtt"))
		return rtp->rtcp->normdevrtt * 1000.0;
	if (!strcasecmp(qos, "stdevrtt"))
		return sqrt(rtp->rtcp->stdevrtt) * 1000.0;

	*found = 0;

	return 0.0;
}

int ast_rtp_get_qos(struct ast_rtp *rtp, const char *qos, char *buf, unsigned int buflen)
{
	double value;
	int found;

	value = __ast_rtp_get_qos(rtp, qos, &found);

	if (!found)
		return -1;

	snprintf(buf, buflen, "%.0lf", value);

	return 0;
}

void ast_rtp_set_vars(struct ast_channel *chan, struct ast_rtp *rtp) {
	char *audioqos;
	char *audioqos_jitter;
	char *audioqos_loss;
	char *audioqos_rtt;
	struct ast_channel *bridge;

	if (!rtp || !chan)
		return;

	bridge = ast_bridged_channel(chan);

	audioqos        = ast_rtp_get_quality(rtp, NULL, RTPQOS_SUMMARY);
	audioqos_jitter = ast_rtp_get_quality(rtp, NULL, RTPQOS_JITTER);
	audioqos_loss   = ast_rtp_get_quality(rtp, NULL, RTPQOS_LOSS);
	audioqos_rtt    = ast_rtp_get_quality(rtp, NULL, RTPQOS_RTT);

	pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", audioqos);
	pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", audioqos_jitter);
	pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", audioqos_loss);
	pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", audioqos_rtt);

	if (!bridge)
		return;

	pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", audioqos);
	pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", audioqos_jitter);
	pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", audioqos_loss);
	pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", audioqos_rtt);
}

static char *__ast_rtp_get_quality_jitter(struct ast_rtp *rtp)
{
	/*
	*ssrc          our ssrc
	*themssrc      their ssrc
	*lp            lost packets
	*rxjitter      our calculated jitter(rx)
	*rxcount       no. received packets
	*txjitter      reported jitter of the other end
	*txcount       transmitted packets
	*rlp           remote lost packets
	*rtt           round trip time
	*/
#define RTCP_JITTER_FORMAT1 \
	"minrxjitter=%f;" \
	"maxrxjitter=%f;" \
	"avgrxjitter=%f;" \
	"stdevrxjitter=%f;" \
	"reported_minjitter=%f;" \
	"reported_maxjitter=%f;" \
	"reported_avgjitter=%f;" \
	"reported_stdevjitter=%f;"

#define RTCP_JITTER_FORMAT2 \
	"rxjitter=%f;"

	if (rtp->rtcp && rtp->rtcp->rtcp_info) {
		snprintf(rtp->rtcp->quality_jitter, sizeof(rtp->rtcp->quality_jitter), RTCP_JITTER_FORMAT1,
			rtp->rtcp->minrxjitter,
			rtp->rtcp->maxrxjitter,
			rtp->rtcp->normdev_rxjitter,
			sqrt(rtp->rtcp->stdev_rxjitter),
			rtp->rtcp->reported_minjitter,
			rtp->rtcp->reported_maxjitter,
			rtp->rtcp->reported_normdev_jitter,
			sqrt(rtp->rtcp->reported_stdev_jitter)
		);
	} else {
		snprintf(rtp->rtcp->quality_jitter, sizeof(rtp->rtcp->quality_jitter), RTCP_JITTER_FORMAT2,
			rtp->rxjitter
		);
	}

	return rtp->rtcp->quality_jitter;

#undef RTCP_JITTER_FORMAT1
#undef RTCP_JITTER_FORMAT2
}

static char *__ast_rtp_get_quality_loss(struct ast_rtp *rtp)
{
	unsigned int lost;
	unsigned int extended;
	unsigned int expected;
	int fraction;

#define RTCP_LOSS_FORMAT1 \
	"minrxlost=%f;" \
	"maxrxlost=%f;" \
	"avgrxlostr=%f;" \
	"stdevrxlost=%f;" \
	"reported_minlost=%f;" \
	"reported_maxlost=%f;" \
	"reported_avglost=%f;" \
	"reported_stdevlost=%f;"

#define RTCP_LOSS_FORMAT2 \
	"lost=%d;" \
	"expected=%d;"
	
	if (rtp->rtcp && rtp->rtcp->rtcp_info && rtp->rtcp->maxrxlost > 0) {
		snprintf(rtp->rtcp->quality_loss, sizeof(rtp->rtcp->quality_loss), RTCP_LOSS_FORMAT1,
			rtp->rtcp->minrxlost,
			rtp->rtcp->maxrxlost,
			rtp->rtcp->normdev_rxlost,
			sqrt(rtp->rtcp->stdev_rxlost),
			rtp->rtcp->reported_minlost,
			rtp->rtcp->reported_maxlost,
			rtp->rtcp->reported_normdev_lost,
			sqrt(rtp->rtcp->reported_stdev_lost)
		);
	} else {
		extended = rtp->cycles + rtp->lastrxseqno;
		expected = extended - rtp->seedrxseqno + 1;
		if (rtp->rxcount > expected) 
			expected += rtp->rxcount - expected;
		lost = expected - rtp->rxcount;

		if (!expected || lost <= 0)
			fraction = 0;
		else
			fraction = (lost << 8) / expected;

		snprintf(rtp->rtcp->quality_loss, sizeof(rtp->rtcp->quality_loss), RTCP_LOSS_FORMAT2,
			lost,
			expected
		);
	}

	return rtp->rtcp->quality_loss;

#undef RTCP_LOSS_FORMAT1
#undef RTCP_LOSS_FORMAT2
}

static char *__ast_rtp_get_quality_rtt(struct ast_rtp *rtp)
{
	if (rtp->rtcp && rtp->rtcp->rtcp_info) {
		snprintf(rtp->rtcp->quality_rtt, sizeof(rtp->rtcp->quality_rtt), "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;",
			rtp->rtcp->minrtt,
			rtp->rtcp->maxrtt,
			rtp->rtcp->normdevrtt,
			sqrt(rtp->rtcp->stdevrtt)
		);
	} else {
		snprintf(rtp->rtcp->quality_rtt, sizeof(rtp->rtcp->quality_rtt), "Not available");
	}

	return rtp->rtcp->quality_rtt;
}

static char *__ast_rtp_get_quality(struct ast_rtp *rtp)
{
	/*
	*ssrc          our ssrc
	*themssrc      their ssrc
	*lp            lost packets
	*rxjitter      our calculated jitter(rx)
	*rxcount       no. received packets
	*txjitter      reported jitter of the other end
	*txcount       transmitted packets
	*rlp           remote lost packets
	*rtt           round trip time
	*/	

	if (rtp->rtcp && rtp->rtcp->rtcp_info) {
		snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
			"ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
			rtp->ssrc,
			rtp->themssrc,
			rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
			rtp->rxjitter,
			rtp->rxcount,
			(double)rtp->rtcp->reported_jitter / 65536.0,
			rtp->txcount,
			rtp->rtcp->reported_lost,
			rtp->rtcp->rtt
		);
	} else {
		snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;rxjitter=%f;rxcount=%u;txcount=%u;",
			rtp->ssrc,
			rtp->themssrc,
			rtp->rxjitter,
			rtp->rxcount,
			rtp->txcount
		);
	}

	return rtp->rtcp->quality;
}

char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual, enum ast_rtp_quality_type qtype) 
{
	if (qual && rtp) {
		qual->local_ssrc   = rtp->ssrc;
		qual->local_jitter = rtp->rxjitter;
		qual->local_count  = rtp->rxcount;
		qual->remote_ssrc  = rtp->themssrc;
		qual->remote_count = rtp->txcount;

		if (rtp->rtcp) {
			qual->local_lostpackets  = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
			qual->remote_lostpackets = rtp->rtcp->reported_lost;
			qual->remote_jitter      = rtp->rtcp->reported_jitter / 65536.0;
			qual->rtt                = rtp->rtcp->rtt;
		}
	}

	switch (qtype) {
	case RTPQOS_SUMMARY:
		return __ast_rtp_get_quality(rtp);
	case RTPQOS_JITTER:
		return __ast_rtp_get_quality_jitter(rtp);
	case RTPQOS_LOSS:
		return __ast_rtp_get_quality_loss(rtp);
	case RTPQOS_RTT:
		return __ast_rtp_get_quality_rtt(rtp);
	}

	return NULL;
}

void ast_rtp_destroy(struct ast_rtp *rtp)
{
	if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
		/*Print some info on the call here */
		ast_verbose("  RTP-stats\n");
		ast_verbose("* Our Receiver:\n");
		ast_verbose("  SSRC:		 %u\n", rtp->themssrc);
		ast_verbose("  Received packets: %u\n", rtp->rxcount);
		ast_verbose("  Lost packets:	 %u\n", rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0);
		ast_verbose("  Jitter:		 %.4f\n", rtp->rxjitter);
		ast_verbose("  Transit:		 %.4f\n", rtp->rxtransit);
		ast_verbose("  RR-count:	 %u\n", rtp->rtcp ? rtp->rtcp->rr_count : 0);
		ast_verbose("* Our Sender:\n");
		ast_verbose("  SSRC:		 %u\n", rtp->ssrc);
		ast_verbose("  Sent packets:	 %u\n", rtp->txcount);
		ast_verbose("  Lost packets:	 %u\n", rtp->rtcp ? rtp->rtcp->reported_lost : 0);
		ast_verbose("  Jitter:		 %u\n", rtp->rtcp ? (rtp->rtcp->reported_jitter / (unsigned int)65536.0) : 0);
		ast_verbose("  SR-count:	 %u\n", rtp->rtcp ? rtp->rtcp->sr_count : 0);
		ast_verbose("  RTT:		 %f\n", rtp->rtcp ? rtp->rtcp->rtt : 0);
	}

	manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
					    "ReceivedPackets: %u\r\n"
					    "LostPackets: %u\r\n"
					    "Jitter: %.4f\r\n"
					    "Transit: %.4f\r\n"
					    "RRCount: %u\r\n",
					    rtp->themssrc,
					    rtp->rxcount,
					    rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0,
					    rtp->rxjitter,
					    rtp->rxtransit,
					    rtp->rtcp ? rtp->rtcp->rr_count : 0);
	manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
					    "SentPackets: %u\r\n"
					    "LostPackets: %u\r\n"
					    "Jitter: %u\r\n"
					    "SRCount: %u\r\n"
					    "RTT: %f\r\n",
					    rtp->ssrc,
					    rtp->txcount,
					    rtp->rtcp ? rtp->rtcp->reported_lost : 0,
					    rtp->rtcp ? rtp->rtcp->reported_jitter : 0,
					    rtp->rtcp ? rtp->rtcp->sr_count : 0,
					    rtp->rtcp ? rtp->rtcp->rtt : 0);
	if (rtp->smoother)
		ast_smoother_free(rtp->smoother);
	if (rtp->ioid)
		ast_io_remove(rtp->io, rtp->ioid);
	if (rtp->s > -1)
		close(rtp->s);
	if (rtp->rtcp) {
		AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
		close(rtp->rtcp->s);
		ast_free(rtp->rtcp);
		rtp->rtcp=NULL;
	}
#ifdef P2P_INTENSE
	ast_mutex_destroy(&rtp->bridge_lock);
#endif
	ast_free(rtp);
}

static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
{
	struct timeval t;
	long ms;
	if (ast_tvzero(rtp->txcore)) {
		rtp->txcore = ast_tvnow();
		/* Round to 20ms for nice, pretty timestamps */
		rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
	}
	/* Use previous txcore if available */
	t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
	ms = ast_tvdiff_ms(t, rtp->txcore);
	if (ms < 0)
		ms = 0;
	/* Use what we just got for next time */
	rtp->txcore = t;
	return (unsigned int) ms;
}

/*! \brief Send begin frames for DTMF */
int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
{
	unsigned int *rtpheader;
	int hdrlen = 12, res = 0, i = 0, payload = 0;
	char data[256];

	if ((digit <= '9') && (digit >= '0'))
		digit -= '0';
	else if (digit == '*')
		digit = 10;
	else if (digit == '#')
		digit = 11;
	else if ((digit >= 'A') && (digit <= 'D'))
		digit = digit - 'A' + 12;
	else if ((digit >= 'a') && (digit <= 'd'))
		digit = digit - 'a' + 12;
	else {
		ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
		return 0;
	}

	/* If we have no peer, return immediately */	
	if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
		return 0;

	payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);

	rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
	rtp->send_duration = 160;
	rtp->lastdigitts = rtp->lastts + rtp->send_duration;
	
	/* Get a pointer to the header */
	rtpheader = (unsigned int *)data;
	rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
	rtpheader[1] = htonl(rtp->lastdigitts);
	rtpheader[2] = htonl(rtp->ssrc); 

	for (i = 0; i < 2; i++) {
		rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
		res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
		if (res < 0) 
			ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
				ast_inet_ntoa(rtp->them.sin_addr),
				ntohs(rtp->them.sin_port), strerror(errno));
		if (rtp_debug_test_addr(&rtp->them))
			ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
				    ast_inet_ntoa(rtp->them.sin_addr),
				    ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
		/* Increment sequence number */
		rtp->seqno++;
		/* Increment duration */
		rtp->send_duration += 160;
		/* Clear marker bit and set seqno */
		rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
	}

	/* Since we received a begin, we can safely store the digit and disable any compensation */
	rtp->sending_digit = 1;
	rtp->send_digit = digit;
	rtp->send_payload = payload;

	return 0;
}

/*! \brief Send continuation frame for DTMF */
static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
{
	unsigned int *rtpheader;
	int hdrlen = 12, res = 0;
	char data[256];

	if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
		return 0;

	/* Setup packet to send */
	rtpheader = (unsigned int *)data;
	rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
	rtpheader[1] = htonl(rtp->lastdigitts);
	rtpheader[2] = htonl(rtp->ssrc);
	rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
	rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
	
	/* Transmit */
	res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
	if (res < 0)
		ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
			ast_inet_ntoa(rtp->them.sin_addr),
			ntohs(rtp->them.sin_port), strerror(errno));
	if (rtp_debug_test_addr(&rtp->them))
		ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
			    ast_inet_ntoa(rtp->them.sin_addr),
			    ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);

	/* Increment sequence number */
	rtp->seqno++;
	/* Increment duration */
	rtp->send_duration += 160;

	return 0;
}

/*! \brief Send end packets for DTMF */
int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
{
	unsigned int *rtpheader;
	int hdrlen = 12, res = 0, i = 0;
	char data[256];
	
	/* If no address, then bail out */
	if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
		return 0;
	
	if ((digit <= '9') && (digit >= '0'))
		digit -= '0';
	else if (digit == '*')
		digit = 10;
	else if (digit == '#')
		digit = 11;
	else if ((digit >= 'A') && (digit <= 'D'))
		digit = digit - 'A' + 12;
	else if ((digit >= 'a') && (digit <= 'd'))
		digit = digit - 'a' + 12;
	else {
		ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
		return 0;
	}

	rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));

	rtpheader = (unsigned int *)data;
	rtpheader[1] = htonl(rtp->lastdigitts);
	rtpheader[2] = htonl(rtp->ssrc);
	rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
	/* Set end bit */
	rtpheader[3] |= htonl((1 << 23));

	/* Send 3 termination packets */
	for (i = 0; i < 3; i++) {
		rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
		res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
		rtp->seqno++;
		if (res < 0)
			ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
				ast_inet_ntoa(rtp->them.sin_addr),
				ntohs(rtp->them.sin_port), strerror(errno));
		if (rtp_debug_test_addr(&rtp->them))
			ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
				    ast_inet_ntoa(rtp->them.sin_addr),
				    ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
	}
	rtp->lastts += rtp->send_duration;
	rtp->sending_digit = 0;
	rtp->send_digit = 0;

	return res;
}

/*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
int ast_rtcp_send_h261fur(void *data)
{
	struct ast_rtp *rtp = data;
	int res;

	rtp->rtcp->sendfur = 1;
	res = ast_rtcp_write(data);
	
	return res;
}

/*! \brief Send RTCP sender's report */
static int ast_rtcp_write_sr(const void *data)
{
	struct ast_rtp *rtp = (struct ast_rtp *)data;
	int res;
	int len = 0;
	struct timeval now;
	unsigned int now_lsw;
	unsigned int now_msw;
	unsigned int *rtcpheader;
	unsigned int lost;
	unsigned int extended;
	unsigned int expected;
	unsigned int expected_interval;
	unsigned int received_interval;
	int lost_interval;
	int fraction;
	struct timeval dlsr;
	char bdata[512];

	/* Commented condition is always not NULL if rtp->rtcp is not NULL */
	if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
		return 0;
	
	if (!rtp->rtcp->them.sin_addr.s_addr) {  /* This'll stop rtcp for this rtp session */
		ast_verbose("RTCP SR transmission error, rtcp halted\n");
		AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
		return 0;
	}

	gettimeofday(&now, NULL);
	timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
	rtcpheader = (unsigned int *)bdata;
	rtcpheader[1] = htonl(rtp->ssrc);               /* Our SSRC */
	rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
	rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
	rtcpheader[4] = htonl(rtp->lastts);             /* FIXME shouldn't be that, it should be now */
	rtcpheader[5] = htonl(rtp->txcount);            /* No. packets sent */
	rtcpheader[6] = htonl(rtp->txoctetcount);       /* No. bytes sent */
	len += 28;
	
	extended = rtp->cycles + rtp->lastrxseqno;
	expected = extended - rtp->seedrxseqno + 1;
	if (rtp->rxcount > expected) 
		expected += rtp->rxcount - expected;
	lost = expected - rtp->rxcount;
	expected_interval = expected - rtp->rtcp->expected_prior;
	rtp->rtcp->expected_prior = expected;
	received_interval = rtp->rxcount - rtp->rtcp->received_prior;
	rtp->rtcp->received_prior = rtp->rxcount;
	lost_interval = expected_interval - received_interval;
	if (expected_interval == 0 || lost_interval <= 0)
		fraction = 0;
	else
		fraction = (lost_interval << 8) / expected_interval;
	timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
	rtcpheader[7] = htonl(rtp->themssrc);
	rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
	rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
	rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
	rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
	rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
	len += 24;
	
	rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));

	if (rtp->rtcp->sendfur) {
		rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
		rtcpheader[14] = htonl(rtp->ssrc);               /* Our SSRC */
		len += 8;
		rtp->rtcp->sendfur = 0;
	}
	
	/* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */ 
	/* it can change mid call, and SDES can't) */
	rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
	rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
	rtcpheader[(len/4)+2] = htonl(0x01 << 24);                    /* Empty for the moment */
	len += 12;
	
	res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
	if (res < 0) {
		ast_log(LOG_ERROR, "RTCP SR transmission error to %s:%d, rtcp halted %s\n",ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port), strerror(errno));
		AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
		return 0;
	}
	
	/* FIXME Don't need to get a new one */
	gettimeofday(&rtp->rtcp->txlsr, NULL);
	rtp->rtcp->sr_count++;

	rtp->rtcp->lastsrtxcount = rtp->txcount;	
	
	if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
		ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
		ast_verbose("  Our SSRC: %u\n", rtp->ssrc);
		ast_verbose("  Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
		ast_verbose("  Sent(RTP): %u\n", rtp->lastts);
		ast_verbose("  Sent packets: %u\n", rtp->txcount);
		ast_verbose("  Sent octets: %u\n", rtp->txoctetcount);
		ast_verbose("  Report block:\n");
		ast_verbose("  Fraction lost: %u\n", fraction);
		ast_verbose("  Cumulative loss: %u\n", lost);
		ast_verbose("  IA jitter: %.4f\n", rtp->rxjitter);
		ast_verbose("  Their last SR: %u\n", rtp->rtcp->themrxlsr);
		ast_verbose("  DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
	}
	manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To: %s:%d\r\n"
					    "OurSSRC: %u\r\n"
					    "SentNTP: %u.%010u\r\n"
					    "SentRTP: %u\r\n"
					    "SentPackets: %u\r\n"
					    "SentOctets: %u\r\n"
					    "ReportBlock:\r\n"
					    "FractionLost: %u\r\n"
					    "CumulativeLoss: %u\r\n"
					    "IAJitter: %.4f\r\n"
					    "TheirLastSR: %u\r\n"
					    "DLSR: %4.4f (sec)\r\n",
					    ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
					    rtp->ssrc,
					    (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
					    rtp->lastts,
					    rtp->txcount,
					    rtp->txoctetcount,
					    fraction,
					    lost,
					    rtp->rxjitter,
					    rtp->rtcp->themrxlsr,
					    (double)(ntohl(rtcpheader[12])/65536.0));
	return res;
}

/*! \brief Send RTCP recipient's report */
static int ast_rtcp_write_rr(const void *data)
{
	struct ast_rtp *rtp = (struct ast_rtp *)data;
	int res;
	int len = 32;
	unsigned int lost;
	unsigned int extended;
	unsigned int expected;
	unsigned int expected_interval;
	unsigned int received_interval;
	int lost_interval;
	struct timeval now;
	unsigned int *rtcpheader;
	char bdata[1024];
	struct timeval dlsr;
	int fraction;

	double rxlost_current;
	
	if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
		return 0;
	  
	if (!rtp->rtcp->them.sin_addr.s_addr) {
		ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
		AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
		return 0;
	}

	extended = rtp->cycles + rtp->lastrxseqno;
	expected = extended - rtp->seedrxseqno + 1;
	lost = expected - rtp->rxcount;
	expected_interval = expected - rtp->rtcp->expected_prior;
	rtp->rtcp->expected_prior = expected;
	received_interval = rtp->rxcount - rtp->rtcp->received_prior;
	rtp->rtcp->received_prior = rtp->rxcount;
	lost_interval = expected_interval - received_interval;

	if (lost_interval <= 0)
		rtp->rtcp->rxlost = 0;
	else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
	if (rtp->rtcp->rxlost_count == 0)
		rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
	if (lost_interval < rtp->rtcp->minrxlost) 
		rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
	if (lost_interval > rtp->rtcp->maxrxlost) 
		rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;

	rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
	rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
	rtp->rtcp->normdev_rxlost = rxlost_current;
	rtp->rtcp->rxlost_count++;

	if (expected_interval == 0 || lost_interval <= 0)
		fraction = 0;
	else
		fraction = (lost_interval << 8) / expected_interval;
	gettimeofday(&now, NULL);
	timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
	rtcpheader = (unsigned int *)bdata;
	rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
	rtcpheader[1] = htonl(rtp->ssrc);
	rtcpheader[2] = htonl(rtp->themssrc);
	rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
	rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
	rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
	rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
	rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);

	if (rtp->rtcp->sendfur) {
		rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
		rtcpheader[9] = htonl(rtp->ssrc);               /* Our SSRC */
		len += 8;
		rtp->rtcp->sendfur = 0;
	}

	/*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos 
	it can change mid call, and SDES can't) */
	rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
	rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
	rtcpheader[(len/4)+2] = htonl(0x01 << 24);              /* Empty for the moment */
	len += 12;
	
	res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));

	if (res < 0) {
		ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
		/* Remove the scheduler */
		AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
		return 0;
	}

	rtp->rtcp->rr_count++;

	if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
		ast_verbose("\n* Sending RTCP RR to %s:%d\n"
			"  Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n" 
			"  IA jitter: %.4f\n" 
			"  Their last SR: %u\n" 
			"  DLSR: %4.4f (sec)\n\n",
			ast_inet_ntoa(rtp->rtcp->them.sin_addr),
			ntohs(rtp->rtcp->them.sin_port),
			rtp->ssrc, rtp->themssrc, fraction, lost,
			rtp->rxjitter,
			rtp->rtcp->themrxlsr,
			(double)(ntohl(rtcpheader[7])/65536.0));
	}

	return res;
}

/*! \brief Write and RTCP packet to the far end
 * \note Decide if we are going to send an SR (with Reception Block) or RR 
 * RR is sent if we have not sent any rtp packets in the previous interval */
static int ast_rtcp_write(const void *data)
{
	struct ast_rtp *rtp = (struct ast_rtp *)data;
	int res;
	
	if (!rtp || !rtp->rtcp)
		return 0;

	if (rtp->txcount > rtp->rtcp->lastsrtxcount)
		res = ast_rtcp_write_sr(data);
	else
		res = ast_rtcp_write_rr(data);
	
	return res;
}

/*! \brief generate comfort noice (CNG) */
int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
{
	unsigned int *rtpheader;
	int hdrlen = 12;
	int res;
	int payload;
	char data[256];
	level = 127 - (level & 0x7f);
	payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);

	/* If we have no peer, return immediately */	
	if (!rtp->them.sin_addr.s_addr)
		return 0;

	rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));

	/* Get a pointer to the header */
	rtpheader = (unsigned int *)data;
	rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
	rtpheader[1] = htonl(rtp->lastts);
	rtpheader[2] = htonl(rtp->ssrc); 
	data[12] = level;
	if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
		res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
		if (res <0) 
			ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s:%d: %s\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
		if (rtp_debug_test_addr(&rtp->them))
			ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
					, ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);		   
		   
	}
	return 0;
}

/*! \brief Write RTP packet with audio or video media frames into UDP packet */
static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
{
	unsigned char *rtpheader;
	int hdrlen = 12;
	int res;
	unsigned int ms;
	int pred;
	int mark = 0;
	int rate = rtp_get_rate(f->subclass) / 1000;

	if (f->subclass == AST_FORMAT_G722) {
		f->samples /= 2;
	}

	if (rtp->sending_digit) {
		return 0;
	}

	ms = calc_txstamp(rtp, &f->delivery);
	/* Default prediction */
	if (f->frametype == AST_FRAME_VOICE) {
		pred = rtp->lastts + f->samples;

		/* Re-calculate last TS */
		rtp->lastts = rtp->lastts + ms * rate;
		if (ast_tvzero(f->delivery)) {
			/* If this isn't an absolute delivery time, Check if it is close to our prediction, 
			   and if so, go with our prediction */
			if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
				rtp->lastts = pred;
			else {
				ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
				mark = 1;
			}
		}
	} else if (f->frametype == AST_FRAME_VIDEO) {
		mark = f->subclass & 0x1;
		pred = rtp->lastovidtimestamp + f->samples;
		/* Re-calculate last TS */
		rtp->lastts = rtp->lastts + ms * 90;
		/* If it's close to our prediction, go for it */
		if (ast_tvzero(f->delivery)) {
			if (abs(rtp->lastts - pred) < 7200) {
				rtp->lastts = pred;
				rtp->lastovidtimestamp += f->samples;
			} else {
				ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, f->samples);
				rtp->lastovidtimestamp = rtp->lastts;
			}
		}
	} else {
		pred = rtp->lastotexttimestamp + f->samples;
		/* Re-calculate last TS */
		rtp->lastts = rtp->lastts + ms;
		/* If it's close to our prediction, go for it */
		if (ast_tvzero(f->delivery)) {
			if (abs(rtp->lastts - pred) < 7200) {
				rtp->lastts = pred;
				rtp->lastotexttimestamp += f->samples;
			} else {
				ast_debug(3, "Difference is %d, ms is %d, pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, rtp->lastts, pred, f->samples);
				rtp->lastotexttimestamp = rtp->lastts;
			}
		}
	}

	/* If we have been explicitly told to set the marker bit do so */
	if (rtp->set_marker_bit) {
		mark = 1;
		rtp->set_marker_bit = 0;
	}

	/* If the timestamp for non-digit packets has moved beyond the timestamp
	   for digits, update the digit timestamp.
	*/
	if (rtp->lastts > rtp->lastdigitts)
		rtp->lastdigitts = rtp->lastts;

	if (ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO))
		rtp->lastts = f->ts * rate;

	/* Get a pointer to the header */
	rtpheader = (unsigned char *)(f->data.ptr - hdrlen);

	put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
	put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
	put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc)); 

	if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
		res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
		if (res < 0) {
			if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
				ast_debug(1, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
			} else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
				/* Only give this error message once if we are not RTP debugging */
				if (option_debug || rtpdebug)
					ast_debug(0, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
				ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
			}
		} else {
			rtp->txcount++;
			rtp->txoctetcount +=(res - hdrlen);
			
			/* Do not schedule RR if RTCP isn't run */
			if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
				rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
			}
		}
				
		if (rtp_debug_test_addr(&rtp->them))
			ast_verbose("Sent RTP packet to      %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
					ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
	}

	rtp->seqno++;

	return 0;
}

void ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
{
	struct ast_format_list current_format_old, current_format_new;

	/* if no packets have been sent through this session yet, then
	 *  changing preferences does not require any extra work
	 */
	if (rtp->lasttxformat == 0) {
		rtp->pref = *prefs;
		return;
	}

	current_format_old = ast_codec_pref_getsize(&rtp->pref, rtp->lasttxformat);

	rtp->pref = *prefs;

	current_format_new = ast_codec_pref_getsize(&rtp->pref, rtp->lasttxformat);

	/* if the framing desired for the current format has changed, we may have to create
	 * or adjust the smoother for this session
	 */
	if ((current_format_new.inc_ms != 0) &&
	    (current_format_new.cur_ms != current_format_old.cur_ms)) {
		int new_size = (current_format_new.cur_ms * current_format_new.fr_len) / current_format_new.inc_ms;

		if (rtp->smoother) {
			ast_smoother_reconfigure(rtp->smoother, new_size);
			if (option_debug) {
				ast_log(LOG_DEBUG, "Adjusted smoother to %d ms and %d bytes\n", current_format_new.cur_ms, new_size);
			}
		} else {
			if (!(rtp->smoother = ast_smoother_new(new_size))) {
				ast_log(LOG_WARNING, "Unable to create smoother: format: %d ms: %d len: %d\n", rtp->lasttxformat, current_format_new.cur_ms, new_size);
				return;
			}
			if (current_format_new.flags) {
				ast_smoother_set_flags(rtp->smoother, current_format_new.flags);
			}
			if (option_debug) {
				ast_log(LOG_DEBUG, "Created smoother: format: %d ms: %d len: %d\n", rtp->lasttxformat, current_format_new.cur_ms, new_size);
			}
		}
	}

}

struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
{
	return &rtp->pref;
}

int ast_rtp_codec_getformat(int pt)
{
	if (pt < 0 || pt >= MAX_RTP_PT)
		return 0; /* bogus payload type */

	if (static_RTP_PT[pt].isAstFormat)
		return static_RTP_PT[pt].code;
	else
		return 0;
}

int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
{
	struct ast_frame *f;
	int codec;
	int hdrlen = 12;
	int subclass;
	

	/* If we have no peer, return immediately */	
	if (!rtp->them.sin_addr.s_addr)
		return 0;

	/* If there is no data length, return immediately */
	if (!_f->datalen && !rtp->red)
		return 0;
	
	/* Make sure we have enough space for RTP header */
	if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO) && (_f->frametype != AST_FRAME_TEXT)) {
		ast_log(LOG_WARNING, "RTP can only send voice, video and text\n");
		return -1;
	}

	if (rtp->red) {
		/* return 0; */
		/* no primary data or generations to send */
		if ((_f = red_t140_to_red(rtp->red)) == NULL) 
			return 0;
	}

	/* The bottom bit of a video subclass contains the marker bit */
	subclass = _f->subclass;
	if (_f->frametype == AST_FRAME_VIDEO)
		subclass &= ~0x1;

	codec = ast_rtp_lookup_code(rtp, 1, subclass);
	if (codec < 0) {
		ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
		return -1;
	}

	if (rtp->lasttxformat != subclass) {
		/* New format, reset the smoother */
		ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
		rtp->lasttxformat = subclass;
		if (rtp->smoother)
			ast_smoother_free(rtp->smoother);
		rtp->smoother = NULL;
	}

	if (!rtp->smoother) {
		struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);

		switch (subclass) {
		case AST_FORMAT_SPEEX:
		case AST_FORMAT_G723_1:
		case AST_FORMAT_SIREN7:
		case AST_FORMAT_SIREN14:
			/* these are all frame-based codecs and cannot be safely run through
			   a smoother */
			break;
		default:
			if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
				if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
					ast_log(LOG_WARNING, "Unable to create smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
					return -1;
				}
				if (fmt.flags)
					ast_smoother_set_flags(rtp->smoother, fmt.flags);
				ast_debug(1, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
			}
		}
	}
	if (rtp->smoother) {
		if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
			ast_smoother_feed_be(rtp->smoother, _f);
		} else {
			ast_smoother_feed(rtp->smoother, _f);
		}

		while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
			ast_rtp_raw_write(rtp, f, codec);
		}
	} else {
		/* Don't buffer outgoing frames; send them one-per-packet: */
		if (_f->offset < hdrlen) 
			f = ast_frdup(_f);	/*! \bug XXX this might never be free'd. Why do we do this? */
		else
			f = _f;
		if (f->data.ptr)
			ast_rtp_raw_write(rtp, f, codec);
		if (f != _f)
			ast_frfree(f);
	}
		
	return 0;
}

/*! \brief Unregister interface to channel driver */
void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
{
	AST_RWLIST_WRLOCK(&protos);
	AST_RWLIST_REMOVE(&protos, proto, list);
	AST_RWLIST_UNLOCK(&protos);
}

/*! \brief Register interface to channel driver */
int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
{
	struct ast_rtp_protocol *cur;

	AST_RWLIST_WRLOCK(&protos);
	AST_RWLIST_TRAVERSE(&protos, cur, list) {	
		if (!strcmp(cur->type, proto->type)) {
			ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
			AST_RWLIST_UNLOCK(&protos);
			return -1;
		}
	}
	AST_RWLIST_INSERT_HEAD(&protos, proto, list);
	AST_RWLIST_UNLOCK(&protos);
	
	return 0;
}

/*! \brief Bridge loop for true native bridge (reinvite) */
static enum ast_bridge_result bridge_native_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, struct ast_rtp *vp0, struct ast_rtp *vp1, struct ast_rtp *tp0, struct ast_rtp *tp1, struct ast_rtp_protocol *pr0, struct ast_rtp_protocol *pr1, int codec0, int codec1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
{
	struct ast_frame *fr = NULL;
	struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
	int oldcodec0 = codec0, oldcodec1 = codec1;
	struct sockaddr_in ac1 = {0,}, vac1 = {0,}, tac1 = {0,}, ac0 = {0,}, vac0 = {0,}, tac0 = {0,};
	struct sockaddr_in t1 = {0,}, vt1 = {0,}, tt1 = {0,}, t0 = {0,}, vt0 = {0,}, tt0 = {0,};
	
	/* Set it up so audio goes directly between the two endpoints */

	/* Test the first channel */
	if (!(pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
		ast_rtp_get_peer(p1, &ac1);
		if (vp1)
			ast_rtp_get_peer(vp1, &vac1);
		if (tp1)
			ast_rtp_get_peer(tp1, &tac1);
	} else
		ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
	
	/* Test the second channel */
	if (!(pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
		ast_rtp_get_peer(p0, &ac0);
		if (vp0)
			ast_rtp_get_peer(vp0, &vac0);
		if (tp0)
			ast_rtp_get_peer(tp0, &tac0);
	} else
		ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);

	/* Now we can unlock and move into our loop */
	ast_channel_unlock(c0);
	ast_channel_unlock(c1);

	ast_poll_channel_add(c0, c1);

	/* Throw our channels into the structure and enter the loop */
	cs[0] = c0;
	cs[1] = c1;
	cs[2] = NULL;
	for (;;) {
		/* Check if anything changed */
		if ((c0->tech_pvt != pvt0) ||
		    (c1->tech_pvt != pvt1) ||
		    (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
		    (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
			ast_debug(1, "Oooh, something is weird, backing out\n");
			if (c0->tech_pvt == pvt0)
				if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
					ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
			if (c1->tech_pvt == pvt1)
				if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
					ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
			ast_poll_channel_del(c0, c1);
			return AST_BRIDGE_RETRY;
		}

		/* Check if they have changed their address */
		ast_rtp_get_peer(p1, &t1);
		if (vp1)
			ast_rtp_get_peer(vp1, &vt1);
		if (tp1)
			ast_rtp_get_peer(tp1, &tt1);
		if (pr1->get_codec)
			codec1 = pr1->get_codec(c1);
		ast_rtp_get_peer(p0, &t0);
		if (vp0)
			ast_rtp_get_peer(vp0, &vt0);
		if (tp0)
			ast_rtp_get_peer(tp0, &tt0);
		if (pr0->get_codec)
			codec0 = pr0->get_codec(c0);
		if ((inaddrcmp(&t1, &ac1)) ||
		    (vp1 && inaddrcmp(&vt1, &vac1)) ||
		    (tp1 && inaddrcmp(&tt1, &tac1)) ||
		    (codec1 != oldcodec1)) {
			ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
				c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
			ast_debug(2, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
				c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
			ast_debug(2, "Oooh, '%s' changed end taddress to %s:%d (format %d)\n",
				c1->name, ast_inet_ntoa(tt1.sin_addr), ntohs(tt1.sin_port), codec1);
			ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
				c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
			ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
				c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
			ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
				c1->name, ast_inet_ntoa(tac1.sin_addr), ntohs(tac1.sin_port), oldcodec1);
			if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, tt1.sin_addr.s_addr ? tp1 : NULL, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
				ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
			memcpy(&ac1, &t1, sizeof(ac1));
			memcpy(&vac1, &vt1, sizeof(vac1));
			memcpy(&tac1, &tt1, sizeof(tac1));
			oldcodec1 = codec1;
		}
		if ((inaddrcmp(&t0, &ac0)) ||
		    (vp0 && inaddrcmp(&vt0, &vac0)) ||
		    (tp0 && inaddrcmp(&tt0, &tac0)) ||
		    (codec0 != oldcodec0)) {
			ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
				c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
			ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
				c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
			if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, tt0.sin_addr.s_addr ? tp0 : NULL, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
				ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
			memcpy(&ac0, &t0, sizeof(ac0));
			memcpy(&vac0, &vt0, sizeof(vac0));
			memcpy(&tac0, &tt0, sizeof(tac0));
			oldcodec0 = codec0;
		}

		/* Wait for frame to come in on the channels */
		if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
			if (!timeoutms) {
				if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
					ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
				if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
					ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
				return AST_BRIDGE_RETRY;
			}
			ast_debug(1, "Ooh, empty read...\n");
			if (ast_check_hangup(c0) || ast_check_hangup(c1))
				break;
			continue;
		}
		fr = ast_read(who);
		other = (who == c0) ? c1 : c0;
		if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
			    (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
			     ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
			/* Break out of bridge */
			*fo = fr;
			*rc = who;
			ast_debug(1, "Oooh, got a %s\n", fr ? "digit" : "hangup");
			if (c0->tech_pvt == pvt0)
				if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
					ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
			if (c1->tech_pvt == pvt1)
				if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
					ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
			ast_poll_channel_del(c0, c1);
			return AST_BRIDGE_COMPLETE;
		} else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
			if ((fr->subclass == AST_CONTROL_HOLD) ||
			    (fr->subclass == AST_CONTROL_UNHOLD) ||
			    (fr->subclass == AST_CONTROL_VIDUPDATE) ||
			    (fr->subclass == AST_CONTROL_SRCUPDATE) ||
			    (fr->subclass == AST_CONTROL_T38_PARAMETERS)) {
				if (fr->subclass == AST_CONTROL_HOLD) {
					/* If we someone went on hold we want the other side to reinvite back to us */
					if (who == c0)
						pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0);
					else
						pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0);
				} else if (fr->subclass == AST_CONTROL_UNHOLD) {
					/* If they went off hold they should go back to being direct */
					if (who == c0)
						pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE));
					else
						pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE));
				}
				/* Update local address information */
				ast_rtp_get_peer(p0, &t0);
				memcpy(&ac0, &t0, sizeof(ac0));
				ast_rtp_get_peer(p1, &t1);
				memcpy(&ac1, &t1, sizeof(ac1));
				/* Update codec information */
				if (pr0->get_codec && c0->tech_pvt)
					oldcodec0 = codec0 = pr0->get_codec(c0);
				if (pr1->get_codec && c1->tech_pvt)
					oldcodec1 = codec1 = pr1->get_codec(c1);
				ast_indicate_data(other, fr->subclass, fr->data.ptr, fr->datalen);
				ast_frfree(fr);
			} else {
				*fo = fr;
				*rc = who;
				ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
				return AST_BRIDGE_COMPLETE;
			}
		} else {
			if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
			    (fr->frametype == AST_FRAME_DTMF_END) ||
			    (fr->frametype == AST_FRAME_VOICE) ||
			    (fr->frametype == AST_FRAME_VIDEO) ||
			    (fr->frametype == AST_FRAME_IMAGE) ||
			    (fr->frametype == AST_FRAME_HTML) ||
			    (fr->frametype == AST_FRAME_MODEM) ||
			    (fr->frametype == AST_FRAME_TEXT)) {
				ast_write(other, fr);
			}
			ast_frfree(fr);
		}
		/* Swap priority */
#ifndef HAVE_EPOLL
		cs[2] = cs[0];
		cs[0] = cs[1];
		cs[1] = cs[2];
#endif
	}

	ast_poll_channel_del(c0, c1);

	if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
		ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
	if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
		ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);

	return AST_BRIDGE_FAILED;
}

/*! \brief P2P RTP Callback */
#ifdef P2P_INTENSE
static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
{
	int res = 0, hdrlen = 12;
	struct sockaddr_in sin;
	socklen_t len;
	unsigned int *header;
	struct ast_rtp *rtp = cbdata, *bridged = NULL;

	if (!rtp)
		return 1;

	len = sizeof(sin);
	if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
		return 1;

	header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
	
	/* If NAT support is turned on, then see if we need to change their address */
	if ((rtp->nat) && 
	    ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
	     (rtp->them.sin_port != sin.sin_port))) {
		rtp->them = sin;
		rtp->rxseqno = 0;
		ast_set_flag(rtp, FLAG_NAT_ACTIVE);
		if (option_debug || rtpdebug)
			ast_debug(0, "P2P RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
	}

	/* Write directly out to other RTP stream if bridged */
	if ((bridged = ast_rtp_get_bridged(rtp)))
		bridge_p2p_rtp_write(rtp, bridged, header, res, hdrlen);
	
	return 1;
}

/*! \brief Helper function to switch a channel and RTP stream into callback mode */
static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
{
	/* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
	if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || ast_test_flag(rtp, FLAG_HAS_STUN) || !rtp->io)
		return 0;

	/* If the RTP structure is already in callback mode, remove it temporarily */
	if (rtp->ioid) {
		ast_io_remove(rtp->io, rtp->ioid);
		rtp->ioid = NULL;
	}

	/* Steal the file descriptors from the channel */
	chan->fds[0] = -1;

	/* Now, fire up callback mode */
	iod[0] = ast_io_add(rtp->io, ast_rtp_fd(rtp), p2p_rtp_callback, AST_IO_IN, rtp);

	return 1;
}
#else
static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
{
	return 0;
}
#endif

/*! \brief Helper function to switch a channel and RTP stream out of callback mode */
static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
{
	ast_channel_lock(chan);

	/* Remove the callback from the IO context */
	ast_io_remove(rtp->io, iod[0]);

	/* Restore file descriptors */
	chan->fds[0] = ast_rtp_fd(rtp);
	ast_channel_unlock(chan);

	/* Restore callback mode if previously used */
	if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
		rtp->ioid = ast_io_add(rtp->io, ast_rtp_fd(rtp), rtpread, AST_IO_IN, rtp);

	return 0;
}

/*! \brief Helper function that sets what an RTP structure is bridged to */
static void p2p_set_bridge(struct ast_rtp *rtp0, struct ast_rtp *rtp1)
{
	rtp_bridge_lock(rtp0);
	rtp0->bridged = rtp1;
	rtp_bridge_unlock(rtp0);
}

/*! \brief Bridge loop for partial native bridge (packet2packet) 

	In p2p mode, Asterisk is a very basic RTP proxy, just forwarding whatever
	rtp/rtcp we get in to the channel. 
	\note this currently only works for Audio
*/
static enum ast_bridge_result bridge_p2p_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
{
	struct ast_frame *fr = NULL;
	struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
	int *p0_iod[2] = {NULL, NULL}, *p1_iod[2] = {NULL, NULL};
	int p0_callback = 0, p1_callback = 0;
	enum ast_bridge_result res = AST_BRIDGE_FAILED;

	/* Okay, setup each RTP structure to do P2P forwarding */
	ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
	p2p_set_bridge(p0, p1);
	ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
	p2p_set_bridge(p1, p0);

	/* Activate callback modes if possible */
	p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
	p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);

	/* Now let go of the channel locks and be on our way */
	ast_channel_unlock(c0);
	ast_channel_unlock(c1);

	ast_poll_channel_add(c0, c1);

	/* Go into a loop forwarding frames until we don't need to anymore */
	cs[0] = c0;
	cs[1] = c1;
	cs[2] = NULL;
	for (;;) {
		/* If the underlying formats have changed force this bridge to break */
		if ((c0->rawreadformat != c1->rawwriteformat) || (c1->rawreadformat != c0->rawwriteformat)) {
			ast_debug(3, "p2p-rtp-bridge: Oooh, formats changed, backing out\n");
			res = AST_BRIDGE_FAILED_NOWARN;
			break;
		}
		/* Check if anything changed */
		if ((c0->tech_pvt != pvt0) ||
		    (c1->tech_pvt != pvt1) ||
		    (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
		    (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
			ast_debug(3, "p2p-rtp-bridge: Oooh, something is weird, backing out\n");
			/* If a masquerade needs to happen we have to try to read in a frame so that it actually happens. Without this we risk being called again and going into a loop */
			if ((c0->masq || c0->masqr) && (fr = ast_read(c0)))
				ast_frfree(fr);
			if ((c1->masq || c1->masqr) && (fr = ast_read(c1)))
				ast_frfree(fr);
			res = AST_BRIDGE_RETRY;
			break;
		}
		/* Wait on a channel to feed us a frame */
		if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
			if (!timeoutms) {
				res = AST_BRIDGE_RETRY;
				break;
			}
			if (option_debug > 2)
				ast_log(LOG_NOTICE, "p2p-rtp-bridge: Ooh, empty read...\n");
			if (ast_check_hangup(c0) || ast_check_hangup(c1))
				break;
			continue;
		}
		/* Read in frame from channel */
		fr = ast_read(who);
		other = (who == c0) ? c1 : c0;
		/* Depending on the frame we may need to break out of our bridge */
		if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
			    ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
			    ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
			/* Record received frame and who */
			*fo = fr;
			*rc = who;
			ast_debug(3, "p2p-rtp-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
			res = AST_BRIDGE_COMPLETE;
			break;
		} else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
			if ((fr->subclass == AST_CONTROL_HOLD) ||
			    (fr->subclass == AST_CONTROL_UNHOLD) ||
			    (fr->subclass == AST_CONTROL_VIDUPDATE) ||
			    (fr->subclass == AST_CONTROL_SRCUPDATE) ||
			    (fr->subclass == AST_CONTROL_T38_PARAMETERS)) {
				/* If we are going on hold, then break callback mode and P2P bridging */
				if (fr->subclass == AST_CONTROL_HOLD) {
					if (p0_callback)
						p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
					if (p1_callback)
						p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
					p2p_set_bridge(p0, NULL);
					p2p_set_bridge(p1, NULL);
				} else if (fr->subclass == AST_CONTROL_UNHOLD) {
					/* If we are off hold, then go back to callback mode and P2P bridging */
					ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
					p2p_set_bridge(p0, p1);
					ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
					p2p_set_bridge(p1, p0);
					p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
					p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
				}
				ast_indicate_data(other, fr->subclass, fr->data.ptr, fr->datalen);
				ast_frfree(fr);
			} else {
				*fo = fr;
				*rc = who;
				ast_debug(3, "p2p-rtp-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
				res = AST_BRIDGE_COMPLETE;
				break;
			}
		} else {
			if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
			    (fr->frametype == AST_FRAME_DTMF_END) ||
			    (fr->frametype == AST_FRAME_VOICE) ||
			    (fr->frametype == AST_FRAME_VIDEO) ||
			    (fr->frametype == AST_FRAME_IMAGE) ||
			    (fr->frametype == AST_FRAME_HTML) ||
			    (fr->frametype == AST_FRAME_MODEM) ||
			    (fr->frametype == AST_FRAME_TEXT)) {
				ast_write(other, fr);
			}

			ast_frfree(fr);
		}
		/* Swap priority */
#ifndef HAVE_EPOLL
		cs[2] = cs[0];
		cs[0] = cs[1];
		cs[1] = cs[2];
#endif
	}

	/* If we are totally avoiding the core, then restore our link to it */
	if (p0_callback)
		p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
	if (p1_callback)
		p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);

	/* Break out of the direct bridge */
	p2p_set_bridge(p0, NULL);
	p2p_set_bridge(p1, NULL);

	ast_poll_channel_del(c0, c1);

	return res;
}

/*! \page AstRTPbridge The Asterisk RTP bridge 
	The RTP bridge is called from the channel drivers that are using the RTP
	subsystem in Asterisk - like SIP, H.323 and Jingle/Google Talk.

	This bridge aims to offload the Asterisk server by setting up
	the media stream directly between the endpoints, keeping the
	signalling in Asterisk.

	It checks with the channel driver, using a callback function, if
	there are possibilities for a remote bridge.

	If this fails, the bridge hands off to the core bridge. Reasons
	can be NAT support needed, DTMF features in audio needed by
	the PBX for transfers or spying/monitoring on channels.

	If transcoding is needed - we can't do a remote bridge.
	If only NAT support is needed, we're using Asterisk in
	RTP proxy mode with the p2p RTP bridge, basically
	forwarding incoming audio packets to the outbound
	stream on a network level.

	References:
	- ast_rtp_bridge()
	- ast_channel_early_bridge()
	- ast_channel_bridge()
	- rtp.c
	- rtp.h
*/
/*! \brief Bridge calls. If possible and allowed, initiate
	re-invite so the peers exchange media directly outside 
	of Asterisk. 
*/
enum ast_bridge_result ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
{
	struct ast_rtp *p0 = NULL, *p1 = NULL;		/* Audio RTP Channels */
	struct ast_rtp *vp0 = NULL, *vp1 = NULL;	/* Video RTP channels */
	struct ast_rtp *tp0 = NULL, *tp1 = NULL;	/* Text RTP channels */
	struct ast_rtp_protocol *pr0 = NULL, *pr1 = NULL;
	enum ast_rtp_get_result audio_p0_res = AST_RTP_GET_FAILED, video_p0_res = AST_RTP_GET_FAILED, text_p0_res = AST_RTP_GET_FAILED;
	enum ast_rtp_get_result audio_p1_res = AST_RTP_GET_FAILED, video_p1_res = AST_RTP_GET_FAILED, text_p1_res = AST_RTP_GET_FAILED;
	enum ast_bridge_result res = AST_BRIDGE_FAILED;
	int codec0 = 0, codec1 = 0;
	void *pvt0 = NULL, *pvt1 = NULL;

	/* Lock channels */
	ast_channel_lock(c0);
	while (ast_channel_trylock(c1)) {
		ast_channel_unlock(c0);
		usleep(1);
		ast_channel_lock(c0);
	}

	/* Ensure neither channel got hungup during lock avoidance */
	if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
		ast_log(LOG_WARNING, "Got hangup while attempting to bridge '%s' and '%s'\n", c0->name, c1->name);
		ast_channel_unlock(c0);
		ast_channel_unlock(c1);
		return AST_BRIDGE_FAILED;
	}
		
	/* Find channel driver interfaces */
	if (!(pr0 = get_proto(c0))) {
		ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
		ast_channel_unlock(c0);
		ast_channel_unlock(c1);
		return AST_BRIDGE_FAILED;
	}
	if (!(pr1 = get_proto(c1))) {
		ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
		ast_channel_unlock(c0);
		ast_channel_unlock(c1);
		return AST_BRIDGE_FAILED;
	}

	/* Get channel specific interface structures */
	pvt0 = c0->tech_pvt;
	pvt1 = c1->tech_pvt;

	/* Get audio and video interface (if native bridge is possible) */
	audio_p0_res = pr0->get_rtp_info(c0, &p0);
	video_p0_res = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
	text_p0_res = pr0->get_trtp_info ? pr0->get_trtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
	audio_p1_res = pr1->get_rtp_info(c1, &p1);
	video_p1_res = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
	text_p1_res = pr1->get_trtp_info ? pr1->get_trtp_info(c1, &vp1) : AST_RTP_GET_FAILED;

	/* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
	if (video_p0_res != AST_RTP_GET_FAILED && (audio_p0_res != AST_RTP_TRY_NATIVE || video_p0_res != AST_RTP_TRY_NATIVE))
		audio_p0_res = AST_RTP_GET_FAILED;
	if (video_p1_res != AST_RTP_GET_FAILED && (audio_p1_res != AST_RTP_TRY_NATIVE || video_p1_res != AST_RTP_TRY_NATIVE))
		audio_p1_res = AST_RTP_GET_FAILED;

	/* Check if a bridge is possible (partial/native) */
	if (audio_p0_res == AST_RTP_GET_FAILED || audio_p1_res == AST_RTP_GET_FAILED) {
		/* Somebody doesn't want to play... */
		ast_channel_unlock(c0);
		ast_channel_unlock(c1);
		return AST_BRIDGE_FAILED_NOWARN;
	}

	/* If we need to feed DTMF frames into the core then only do a partial native bridge */
	if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
		ast_set_flag(p0, FLAG_P2P_NEED_DTMF);
		audio_p0_res = AST_RTP_TRY_PARTIAL;
	}

	if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
		ast_set_flag(p1, FLAG_P2P_NEED_DTMF);
		audio_p1_res = AST_RTP_TRY_PARTIAL;
	}

	/* If both sides are not using the same method of DTMF transmission 
	 * (ie: one is RFC2833, other is INFO... then we can not do direct media. 
	 * --------------------------------------------------
	 * | DTMF Mode |  HAS_DTMF  |  Accepts Begin Frames |
	 * |-----------|------------|-----------------------|
	 * | Inband    | False      | True                  |
	 * | RFC2833   | True       | True                  |
	 * | SIP INFO  | False      | False                 |
	 * --------------------------------------------------
	 * However, if DTMF from both channels is being monitored by the core, then
	 * we can still do packet-to-packet bridging, because passing through the 
	 * core will handle DTMF mode translation.
	 */
	if ((ast_test_flag(p0, FLAG_HAS_DTMF) != ast_test_flag(p1, FLAG_HAS_DTMF)) ||
		(!c0->tech->send_digit_begin != !c1->tech->send_digit_begin)) {
		if (!ast_test_flag(p0, FLAG_P2P_NEED_DTMF) || !ast_test_flag(p1, FLAG_P2P_NEED_DTMF)) {
			ast_channel_unlock(c0);
			ast_channel_unlock(c1);
			return AST_BRIDGE_FAILED_NOWARN;
		}
		audio_p0_res = AST_RTP_TRY_PARTIAL;
		audio_p1_res = AST_RTP_TRY_PARTIAL;
	}

	/* If we need to feed frames into the core don't do a P2P bridge */
	if ((audio_p0_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p0, FLAG_P2P_NEED_DTMF)) ||
	    (audio_p1_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p1, FLAG_P2P_NEED_DTMF))) {
		ast_channel_unlock(c0);
		ast_channel_unlock(c1);
		return AST_BRIDGE_FAILED_NOWARN;
	}

	/* Get codecs from both sides */
	codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
	codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
	if (codec0 && codec1 && !(codec0 & codec1)) {
		/* Hey, we can't do native bridging if both parties speak different codecs */
		ast_debug(3, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
		ast_channel_unlock(c0);
		ast_channel_unlock(c1);
		return AST_BRIDGE_FAILED_NOWARN;
	}

	/* If either side can only do a partial bridge, then don't try for a true native bridge */
	if (audio_p0_res == AST_RTP_TRY_PARTIAL || audio_p1_res == AST_RTP_TRY_PARTIAL) {
		struct ast_format_list fmt0, fmt1;

		/* In order to do Packet2Packet bridging both sides must be in the same rawread/rawwrite */
		if (c0->rawreadformat != c1->rawwriteformat || c1->rawreadformat != c0->rawwriteformat) {
			ast_debug(1, "Cannot packet2packet bridge - raw formats are incompatible\n");
			ast_channel_unlock(c0);
			ast_channel_unlock(c1);
			return AST_BRIDGE_FAILED_NOWARN;
		}
		/* They must also be using the same packetization */
		fmt0 = ast_codec_pref_getsize(&p0->pref, c0->rawreadformat);
		fmt1 = ast_codec_pref_getsize(&p1->pref, c1->rawreadformat);
		if (fmt0.cur_ms != fmt1.cur_ms) {
			ast_debug(1, "Cannot packet2packet bridge - packetization settings prevent it\n");
			ast_channel_unlock(c0);
			ast_channel_unlock(c1);
			return AST_BRIDGE_FAILED_NOWARN;
		}

		ast_verb(3, "Packet2Packet bridging %s and %s\n", c0->name, c1->name);
		res = bridge_p2p_loop(c0, c1, p0, p1, timeoutms, flags, fo, rc, pvt0, pvt1);
	} else {
		ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
		res = bridge_native_loop(c0, c1, p0, p1, vp0, vp1, tp0, tp1, pr0, pr1, codec0, codec1, timeoutms, flags, fo, rc, pvt0, pvt1);
	}

	return res;
}

static char *rtp_do_debug_ip(struct ast_cli_args *a)
{
	struct hostent *hp;
	struct ast_hostent ahp;
	int port = 0;
	char *p, *arg;

	arg = a->argv[4];
	p = strstr(arg, ":");
	if (p) {
		*p = '\0';
		p++;
		port = atoi(p);
	}
	hp = ast_gethostbyname(arg, &ahp);
	if (hp == NULL) {
		ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
		return CLI_FAILURE;
	}
	rtpdebugaddr.sin_family = AF_INET;
	memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
	rtpdebugaddr.sin_port = htons(port);
	if (port == 0)
		ast_cli(a->fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
	else
		ast_cli(a->fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
	rtpdebug = 1;
	return CLI_SUCCESS;
}

static char *rtcp_do_debug_ip(struct ast_cli_args *a)
{
	struct hostent *hp;
	struct ast_hostent ahp;
	int port = 0;
	char *p, *arg;

	arg = a->argv[4];
	p = strstr(arg, ":");
	if (p) {
		*p = '\0';
		p++;
		port = atoi(p);
	}
	hp = ast_gethostbyname(arg, &ahp);
	if (hp == NULL) {
		ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
		return CLI_FAILURE;
	}
	rtcpdebugaddr.sin_family = AF_INET;
	memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
	rtcpdebugaddr.sin_port = htons(port);
	if (port == 0)
		ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
	else
		ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
	rtcpdebug = 1;
	return CLI_SUCCESS;
}

static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "rtp set debug {on|off|ip}";
		e->usage =
			"Usage: rtp set debug {on|off|ip host[:port]}\n"
			"       Enable/Disable dumping of all RTP packets. If 'ip' is\n"
			"       specified, limit the dumped packets to those to and from\n"
			"       the specified 'host' with optional port.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc == e->args) { /* set on or off */
		if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
			rtpdebug = 1;
			memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
			ast_cli(a->fd, "RTP Debugging Enabled\n");
			return CLI_SUCCESS;
		} else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
			rtpdebug = 0;
			ast_cli(a->fd, "RTP Debugging Disabled\n");
			return CLI_SUCCESS;
		}
	} else if (a->argc == e->args +1) { /* ip */
		return rtp_do_debug_ip(a);
	}

	return CLI_SHOWUSAGE;   /* default, failure */
}

static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "rtcp set debug {on|off|ip}";
		e->usage =
			"Usage: rtcp set debug {on|off|ip host[:port]}\n"
			"       Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
			"       specified, limit the dumped packets to those to and from\n"
			"       the specified 'host' with optional port.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc == e->args) { /* set on or off */
		if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
			rtcpdebug = 1;
			memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
			ast_cli(a->fd, "RTCP Debugging Enabled\n");
			return CLI_SUCCESS;
		} else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
			rtcpdebug = 0;
			ast_cli(a->fd, "RTCP Debugging Disabled\n");
			return CLI_SUCCESS;
		}
	} else if (a->argc == e->args +1) { /* ip */
		return rtcp_do_debug_ip(a);
	}

	return CLI_SHOWUSAGE;   /* default, failure */
}

static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "rtcp set stats {on|off}";
		e->usage =
			"Usage: rtcp set stats {on|off}\n"
			"       Enable/Disable dumping of RTCP stats.\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc != e->args)
		return CLI_SHOWUSAGE;

	if (!strncasecmp(a->argv[e->args-1], "on", 2))
		rtcpstats = 1;
	else if (!strncasecmp(a->argv[e->args-1], "off", 3))
		rtcpstats = 0;
	else
		return CLI_SHOWUSAGE;

	ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
	return CLI_SUCCESS;
}

static char *handle_cli_stun_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
	switch (cmd) {
	case CLI_INIT:
		e->command = "stun set debug {on|off}";
		e->usage =
			"Usage: stun set debug {on|off}\n"
			"       Enable/Disable STUN (Simple Traversal of UDP through NATs)\n"
			"       debugging\n";
		return NULL;
	case CLI_GENERATE:
		return NULL;
	}

	if (a->argc != e->args)
		return CLI_SHOWUSAGE;

	if (!strncasecmp(a->argv[e->args-1], "on", 2))
		stundebug = 1;
	else if (!strncasecmp(a->argv[e->args-1], "off", 3))
		stundebug = 0;
	else
		return CLI_SHOWUSAGE;

	ast_cli(a->fd, "STUN Debugging %s\n", stundebug ? "Enabled" : "Disabled");
	return CLI_SUCCESS;
}

static struct ast_cli_entry cli_rtp[] = {
	AST_CLI_DEFINE(handle_cli_rtp_set_debug,  "Enable/Disable RTP debugging"),
	AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
	AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
	AST_CLI_DEFINE(handle_cli_stun_set_debug, "Enable/Disable STUN debugging"),
};

static int __ast_rtp_reload(int reload)
{
	struct ast_config *cfg;
	const char *s;
	struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };

	cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
	if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
		return 0;
	}

	rtpstart = 5000;
	rtpend = 31000;
	dtmftimeout = DEFAULT_DTMF_TIMEOUT;
	strictrtp = STRICT_RTP_OPEN;
	if (cfg) {
		if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
			rtpstart = atoi(s);
			if (rtpstart < 1024)
				rtpstart = 1024;
			if (rtpstart > 65535)
				rtpstart = 65535;
		}
		if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
			rtpend = atoi(s);
			if (rtpend < 1024)
				rtpend = 1024;
			if (rtpend > 65535)
				rtpend = 65535;
		}
		if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
			rtcpinterval = atoi(s);
			if (rtcpinterval == 0)
				rtcpinterval = 0; /* Just so we're clear... it's zero */
			if (rtcpinterval < RTCP_MIN_INTERVALMS)
				rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
			if (rtcpinterval > RTCP_MAX_INTERVALMS)
				rtcpinterval = RTCP_MAX_INTERVALMS;
		}
		if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
#ifdef SO_NO_CHECK
			if (ast_false(s))
				nochecksums = 1;
			else
				nochecksums = 0;
#else
			if (ast_false(s))
				ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
#endif
		}
		if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
			dtmftimeout = atoi(s);
			if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
				ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
					dtmftimeout, DEFAULT_DTMF_TIMEOUT);
				dtmftimeout = DEFAULT_DTMF_TIMEOUT;
			};
		}
		if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
			strictrtp = ast_true(s);
		}
		ast_config_destroy(cfg);
	}
	if (rtpstart >= rtpend) {
		ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
		rtpstart = 5000;
		rtpend = 31000;
	}
	ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
	return 0;
}

int ast_rtp_reload(void)
{
	return __ast_rtp_reload(1);
}

/*! \brief Initialize the RTP system in Asterisk */
void ast_rtp_init(void)
{
	ast_cli_register_multiple(cli_rtp, sizeof(cli_rtp) / sizeof(struct ast_cli_entry));
	__ast_rtp_reload(0);
}

/*! \brief Write t140 redundacy frame 
 * \param data primary data to be buffered
 */
static int red_write(const void *data)
{
	struct ast_rtp *rtp = (struct ast_rtp*) data;
	
	ast_rtp_write(rtp, &rtp->red->t140); 

	return 1;  	
}

/*! \brief Construct a redundant frame 
 * \param red redundant data structure
 */
static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
	unsigned char *data = red->t140red.data.ptr;
	int len = 0;
	int i;

	/* replace most aged generation */
	if (red->len[0]) {
		for (i = 1; i < red->num_gen+1; i++)
			len += red->len[i];

		memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len); 
	}
	
	/* Store length of each generation and primary data length*/
	for (i = 0; i < red->num_gen; i++)
		red->len[i] = red->len[i+1];
	red->len[i] = red->t140.datalen;
	
	/* write each generation length in red header */
	len = red->hdrlen;
	for (i = 0; i < red->num_gen; i++)
		len += data[i*4+3] = red->len[i];
	
	/* add primary data to buffer */
	memcpy(&data[len], red->t140.data.ptr, red->t140.datalen); 
	red->t140red.datalen = len + red->t140.datalen;
	
	/* no primary data and no generations to send */
	if (len == red->hdrlen && !red->t140.datalen)
		return NULL;

	/* reset t.140 buffer */
	red->t140.datalen = 0; 
	
	return &red->t140red;
}

/*! \brief Initialize t140 redundancy 
 * \param rtp
 * \param ti buffer t140 for ti (msecs) before sending redundant frame
 * \param red_data_pt Payloadtypes for primary- and generation-data
 * \param num_gen numbers of generations (primary generation not encounted)
 *
*/
int rtp_red_init(struct ast_rtp *rtp, int ti, int *red_data_pt, int num_gen)
{
	struct rtp_red *r;
	int x;
	
	if (!(r = ast_calloc(1, sizeof(struct rtp_red))))
		return -1;

	r->t140.frametype = AST_FRAME_TEXT;
	r->t140.subclass = AST_FORMAT_T140RED;
	r->t140.data.ptr = &r->buf_data; 

	r->t140.ts = 0;
	r->t140red = r->t140;
	r->t140red.data.ptr = &r->t140red_data;
	r->t140red.datalen = 0;
	r->ti = ti;
	r->num_gen = num_gen;
	r->hdrlen = num_gen * 4 + 1;
	r->prev_ts = 0;

	for (x = 0; x < num_gen; x++) {
		r->pt[x] = red_data_pt[x];
		r->pt[x] |= 1 << 7; /* mark redundant generations pt */ 
		r->t140red_data[x*4] = r->pt[x];
	}
	r->t140red_data[x*4] = r->pt[x] = red_data_pt[x]; /* primary pt */
	r->schedid = ast_sched_add(rtp->sched, ti, red_write, rtp);
	rtp->red = r;

	r->t140.datalen = 0;
	
	return 0;
}

/*! \brief Buffer t140 from chan_sip
 * \param rtp
 * \param f frame
 */
void red_buffer_t140(struct ast_rtp *rtp, struct ast_frame *f)
{
	if (f->datalen > -1) {
		struct rtp_red *red = rtp->red;
		memcpy(&red->buf_data[red->t140.datalen], f->data.ptr, f->datalen);
		red->t140.datalen += f->datalen;
		red->t140.ts = f->ts;
	}
}